From 663caf52aab7ec3c66a7c7e3bd0d6cec4ae306a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=96mer=20A=C4=9Facan?= Date: Tue, 23 Sep 2025 14:17:55 +0100 Subject: [PATCH] Improve golden file checking Currently when I have a typo in the golden file path, `expectGolden` creates a new file, which makes the test pass. Update `expectGolden` to only create (or update if already exists) a golden file when the env variable `PROTOC_UPDATE_GOLDENS` is set. Without the env variable it expects the file to exist, with the right contents. So typos now cause test failures as expected. --- protoc_plugin/test/src/golden_file.dart | 34 ++++++++++++------------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/protoc_plugin/test/src/golden_file.dart b/protoc_plugin/test/src/golden_file.dart index d3526ba8..60d8ccb8 100644 --- a/protoc_plugin/test/src/golden_file.dart +++ b/protoc_plugin/test/src/golden_file.dart @@ -7,28 +7,26 @@ import 'dart:io'; import 'package:path/path.dart' as path; import 'package:test/test.dart'; -/// Will test [actual] against the contests of the file at [file]. +/// Test [actual] against the contests of the file at [file]. /// -/// If the file doesn't exist, the file is instead created containing [actual]. +/// When the `PROTOC_UPDATE_GOLDENS` environment variable is set, the [file] +/// will be crated (overwritten if already exists) with the [actual] as the +/// contents. This can be used to automatically update golden test expectations. void expectGolden(String actual, String file) { - final goldens = Directory(path.join('test', 'goldens')); - if (!goldens.existsSync()) { - goldens.createSync(); - } - - var golden = File(path.join(goldens.path, file)); - if (golden.existsSync()) { - expect( - actual, - equals(golden.readAsStringSync()), - reason: 'golden: "${golden.path}"', - ); - } else { - // Writing the updated file if none exists. + var goldenFilePath = path.join('test', 'goldens', file); + if (Platform.environment.containsKey('PROTOC_UPDATE_GOLDENS')) { final workspace = Platform.environment['BUILD_WORKSPACE_DIRECTORY']; if (workspace != null) { - golden = File(path.join(workspace, 'test', 'goldens', file)); + goldenFilePath = path.join(workspace, goldenFilePath); } - golden.writeAsStringSync(actual); + File(goldenFilePath) + ..createSync(recursive: true) + ..writeAsStringSync(actual); + } else { + expect( + actual, + equals(File(goldenFilePath).readAsStringSync()), + reason: 'golden: "$goldenFilePath"', + ); } }