compareOrCreateGolden function

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

Core golden file comparison logic.

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

update defaults to updateGoldens; createMissing defaults to true, except on CI (CI=true).

Implementation

void compareOrCreateGolden(String actual, String goldenPath, {bool? update, bool? createMissing}) {
  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()) {
    if (!(createMissing ?? !_onCi)) {
      fail(
        'Golden file missing: $goldenPath\n\n'
        'Create it with a local run (or TRELLIS_UPDATE_GOLDENS=true dart test) and commit it.',
      );
    }
    _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));
}