expectScreen function
Compares actual with the golden file at path.
When update is true (by default when the environment variable
DART_TUI_UPDATE_GOLDENS is 1), it writes actual to path instead.
Throws TuiTestFailure when the file is missing or differs, naming the
first differing line. Line endings in the file are normalised to \n.
Pass TuiTester.screen for a plain-text golden, or TuiTester.styledScreen for one that keeps the colours.
Implementation
void expectScreen(String actual, String path, {bool? update}) {
final file = File(path);
if (update ?? Platform.environment['DART_TUI_UPDATE_GOLDENS'] == '1') {
file.parent.createSync(recursive: true);
file.writeAsStringSync('$actual\n');
return;
}
if (!file.existsSync()) {
throw TuiTestFailure(
'golden file $path does not exist. Run the test '
'with DART_TUI_UPDATE_GOLDENS=1 to create it.',
);
}
var expected = file.readAsStringSync().replaceAll('\r\n', '\n');
if (expected.endsWith('\n')) {
expected = expected.substring(0, expected.length - 1);
}
if (expected == actual) return;
final want = expected.split('\n');
final got = actual.split('\n');
var line = 0;
while (line < want.length && line < got.length && want[line] == got[line]) {
line++;
}
String show(List<String> lines) =>
line < lines.length ? jsonEncode(lines[line]) : '(no line)';
throw TuiTestFailure(
'screen does not match golden file $path\n'
'first difference at line ${line + 1} '
'(expected ${want.length} lines, got ${got.length}):\n'
' expected: ${show(want)}\n'
' actual: ${show(got)}\n'
'Run with DART_TUI_UPDATE_GOLDENS=1 to accept the new screen.',
);
}