Skip to content

Commit 82fc34f

Browse files
authored
Improve golden file checking (#1053)
Currently when I have a typo in the golden file path, `expectGolden` creates a new file, which makes the test pass. Locally I can notice the new file if I run `git status`, but if I'm not careful and rely on CI, because the tests pass, I can merge the PR. 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.
1 parent 456e2ee commit 82fc34f

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

protoc_plugin/test/src/golden_file.dart

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,28 +7,26 @@ import 'dart:io';
77
import 'package:path/path.dart' as path;
88
import 'package:test/test.dart';
99

10-
/// Will test [actual] against the contests of the file at [file].
10+
/// Test [actual] against the contests of the file at [file].
1111
///
12-
/// If the file doesn't exist, the file is instead created containing [actual].
12+
/// When the `PROTOC_UPDATE_GOLDENS` environment variable is set, the [file]
13+
/// will be crated (overwritten if already exists) with the [actual] as the
14+
/// contents. This can be used to automatically update golden test expectations.
1315
void expectGolden(String actual, String file) {
14-
final goldens = Directory(path.join('test', 'goldens'));
15-
if (!goldens.existsSync()) {
16-
goldens.createSync();
17-
}
18-
19-
var golden = File(path.join(goldens.path, file));
20-
if (golden.existsSync()) {
21-
expect(
22-
actual,
23-
equals(golden.readAsStringSync()),
24-
reason: 'golden: "${golden.path}"',
25-
);
26-
} else {
27-
// Writing the updated file if none exists.
16+
var goldenFilePath = path.join('test', 'goldens', file);
17+
if (Platform.environment.containsKey('PROTOC_UPDATE_GOLDENS')) {
2818
final workspace = Platform.environment['BUILD_WORKSPACE_DIRECTORY'];
2919
if (workspace != null) {
30-
golden = File(path.join(workspace, 'test', 'goldens', file));
20+
goldenFilePath = path.join(workspace, goldenFilePath);
3121
}
32-
golden.writeAsStringSync(actual);
22+
File(goldenFilePath)
23+
..createSync(recursive: true)
24+
..writeAsStringSync(actual);
25+
} else {
26+
expect(
27+
actual,
28+
equals(File(goldenFilePath).readAsStringSync()),
29+
reason: 'golden: "$goldenFilePath"',
30+
);
3331
}
3432
}

0 commit comments

Comments
 (0)