compareOrCreateGolden function

void compareOrCreateGolden(
  1. String actual,
  2. String goldenPath, {
  3. bool? update,
})

Core golden file comparison logic. Package-private for testability.

  1. If update is true: write actual to goldenPath, return (pass).
  2. If golden file does not exist: create it with actual, print info message, return (pass).
  3. If golden file exists: read expected, compare with actual.
    • Match: return (pass).
    • Mismatch: throw TestFailure with a readable line-by-line diff.

Implementation

void compareOrCreateGolden(String actual, String goldenPath, {bool? update}) {
  final shouldUpdate = update ?? updateGoldens;
  final file = File(goldenPath);

  if (shouldUpdate) {
    _writeGolden(file, actual);
    // ignore: avoid_print
    print('Golden file updated: $goldenPath');
    return;
  }

  if (!file.existsSync()) {
    _writeGolden(file, actual);
    // ignore: avoid_print
    print('Golden file created: $goldenPath (first run)');
    return;
  }

  final expected = file.readAsStringSync();
  if (expected == actual) return;

  fail(_buildDiff(expected, actual, goldenPath));
}