ci(#1173): a code change needs a test that fails on dev's code
Every fix and every new capability is meant to ship with a regression test, and nothing enforced it: a PR could change lib/ with no test, or add a test that passes on the old code too. The rule held only while an agent remembered it. - Check 1: a change to lib/ (translations excepted) needs an added or changed *_test.dart. A deleted test does not count. - Check 2: CI puts back the base branch's lib/, regenerates code, and runs only the changed test files. At least one real test must fail or throw there. A file that does not compile against the base, a failing setUpAll hook, a skipped test, or a run that never finished proves nothing and does not count. - Exempt only by PR type (refactor, chore, ci, build, docs, style, test), printed in the job summary. No skip label or flag (#927). - Paths are read NUL-separated (git diff -z, xargs -0), so a space, tab, newline or quote in a name cannot hide a file or split it. - A self-check runs known fixtures through the real runner before check 2, so a Flutter change to the JSON format fails the gate instead of quietly passing it. - Logic lives in tool/test_gate.dart with 35 unit tests. Each guard was shown failing against a deliberately broken copy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>pull/1184/head
parent
d012a2cc36
commit
f414e5c0d8
@ -0,0 +1,118 @@
|
||||
name: Test gate
|
||||
|
||||
# #1173: every fix and every new capability ships with a test that fails
|
||||
# without it. Check 1: a change to lib/ needs an added or changed *_test.dart.
|
||||
# Check 2: those test files, run against the base branch's lib/, must include
|
||||
# a real test that fails there. Logic and messages: tool/test_gate.dart.
|
||||
#
|
||||
# No skip flag or label, by design (#927). The only exemption is a PR title
|
||||
# whose conventional type claims no behavior change, and it is printed in the
|
||||
# job summary. `edited` is a trigger so a title change re-evaluates it.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test-gate:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: "3.44.1"
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
# The title reaches the tool through the environment only. Pasting it
|
||||
# into the script would let a crafted title run commands here.
|
||||
- name: "Check 1: code change comes with a test change"
|
||||
id: scope
|
||||
env:
|
||||
PR_TITLE: ${{ github.event.pull_request.title }}
|
||||
run: |
|
||||
set -eu
|
||||
# checkout hands us the PR merge commit (forks included); parent 1
|
||||
# is the base tip. -z: NUL-separated and never quoted, so no path
|
||||
# can hide from the gate or split into two arguments.
|
||||
git diff --name-status -z HEAD^1 HEAD > "$RUNNER_TEMP/changed.bin"
|
||||
dart run tool/test_gate.dart scope \
|
||||
--changed "$RUNNER_TEMP/changed.bin" \
|
||||
--entries "$RUNNER_TEMP/entries.bin"
|
||||
|
||||
# The verdict below depends on reading the runner's JSON correctly. If a
|
||||
# Flutter upgrade changes that format, the gate must fail, not quietly
|
||||
# start passing. Known fixtures, known verdicts, on every check 2 run.
|
||||
- name: "Gate self-check: the runner's output still reads correctly"
|
||||
if: steps.scope.outputs.evaluate == 'true'
|
||||
run: |
|
||||
set -u
|
||||
canary=test/zz_gate_canary
|
||||
mkdir -p "$canary"
|
||||
cat > "$canary/fails_test.dart" <<'EOF'
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
void main() {
|
||||
test('canary passes', () => expect(1, 1));
|
||||
test('canary fails an expectation', () => expect(1, 2));
|
||||
}
|
||||
EOF
|
||||
cat > "$canary/hook_only_test.dart" <<'EOF'
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
void main() {
|
||||
setUpAll(() => throw StateError('canary hook'));
|
||||
test('canary never runs', () => expect(1, 1));
|
||||
}
|
||||
EOF
|
||||
cat > "$canary/no_compile_test.dart" <<'EOF'
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
void main() {
|
||||
test('canary', () => expect(canaryUndefinedSymbol(), 1));
|
||||
}
|
||||
EOF
|
||||
flutter test --reporter json "$canary/fails_test.dart" \
|
||||
> "$RUNNER_TEMP/canary_real.jsonl" || true
|
||||
flutter test --reporter json "$canary/hook_only_test.dart" \
|
||||
"$canary/no_compile_test.dart" \
|
||||
> "$RUNNER_TEMP/canary_none.jsonl" || true
|
||||
rm -rf "$canary"
|
||||
if ! dart run tool/test_gate.dart evaluate \
|
||||
--results "$RUNNER_TEMP/canary_real.jsonl"; then
|
||||
echo "::error::Gate self-check: a real failing test was not recognized. The runner's JSON format has changed; fix tool/test_gate.dart."
|
||||
exit 1
|
||||
fi
|
||||
if dart run tool/test_gate.dart evaluate \
|
||||
--results "$RUNNER_TEMP/canary_none.jsonl"; then
|
||||
echo "::error::Gate self-check: a hook or compile failure was counted as proof. The runner's JSON format has changed; fix tool/test_gate.dart."
|
||||
exit 1
|
||||
fi
|
||||
echo "Gate self-check passed."
|
||||
|
||||
- name: "Check 2: put back the base branch's code"
|
||||
if: steps.scope.outputs.evaluate == 'true'
|
||||
run: |
|
||||
set -eu
|
||||
rm -rf lib
|
||||
git checkout HEAD^1 -- lib
|
||||
echo "lib/ is now the base branch's; the tests are the PR's:"
|
||||
tr '\0' '\n' < "$RUNNER_TEMP/entries.bin"
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
|
||||
- name: "Check 2: the changed tests must fail on the base code"
|
||||
if: steps.scope.outputs.evaluate == 'true'
|
||||
run: |
|
||||
set -u
|
||||
# Failing tests are the expected outcome here, so the runner's exit
|
||||
# code is not the verdict; the evaluator reads every result instead.
|
||||
xargs -0 -a "$RUNNER_TEMP/entries.bin" \
|
||||
flutter test --reporter json > "$RUNNER_TEMP/results.jsonl" || true
|
||||
dart run tool/test_gate.dart evaluate \
|
||||
--results "$RUNNER_TEMP/results.jsonl"
|
||||
@ -0,0 +1,178 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import '../../tool/test_gate.dart';
|
||||
|
||||
/// Builds runner output in the shape `flutter test --reporter json` emits,
|
||||
/// as observed on Flutter 3.44: each file is a suite with a `loading <path>`
|
||||
/// test (hidden when it compiles, a visible error when it does not), group
|
||||
/// hooks appear as `(setUpAll)` / `(tearDownAll)`, then a final `done`.
|
||||
class _Run {
|
||||
final _lines = <String>['Some non-JSON preamble the runner may print'];
|
||||
var _id = 0;
|
||||
|
||||
void _emit(Map<String, Object?> event) => _lines.add(jsonEncode(event));
|
||||
|
||||
int _start(int suite, String name) {
|
||||
final id = ++_id;
|
||||
_emit({
|
||||
'type': 'testStart',
|
||||
'test': {'id': id, 'name': name, 'suiteID': suite},
|
||||
});
|
||||
return id;
|
||||
}
|
||||
|
||||
void _done(
|
||||
int id,
|
||||
String result, {
|
||||
bool hidden = false,
|
||||
bool skipped = false,
|
||||
}) => _emit({
|
||||
'type': 'testDone',
|
||||
'testID': id,
|
||||
'result': result,
|
||||
'hidden': hidden,
|
||||
'skipped': skipped,
|
||||
});
|
||||
|
||||
int suite(String path, {bool compiles = true}) {
|
||||
final suite = ++_id;
|
||||
_emit({
|
||||
'type': 'suite',
|
||||
'suite': {'id': suite, 'path': path},
|
||||
});
|
||||
final loading = _start(suite, 'loading $path');
|
||||
if (compiles) {
|
||||
_done(loading, 'success', hidden: true);
|
||||
} else {
|
||||
_emit({'type': 'error', 'testID': loading, 'isFailure': false});
|
||||
_done(loading, 'error');
|
||||
}
|
||||
return suite;
|
||||
}
|
||||
|
||||
void test(int suite, String name, String result, {bool skipped = false}) =>
|
||||
_done(_start(suite, name), result, skipped: skipped);
|
||||
|
||||
void failedSetUpAll(int suite) => _done(_start(suite, '(setUpAll)'), 'error');
|
||||
|
||||
String finish({bool done = true}) {
|
||||
if (done) _emit({'type': 'done', 'success': false});
|
||||
return _lines.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('check 2 passes', () {
|
||||
test('when a real test fails an expectation on the base code', () {
|
||||
final run = _Run();
|
||||
final s = run.suite('/repo/test/a_test.dart');
|
||||
run.test(s, 'a refused add is not kept', 'failure');
|
||||
run.test(s, 'an accepted add is kept', 'success');
|
||||
final d = evaluateResults(run.finish());
|
||||
expect(d.passed, isTrue);
|
||||
expect(d.message, contains('a refused add is not kept'));
|
||||
});
|
||||
|
||||
test('when a real test throws on the base code', () {
|
||||
final run = _Run();
|
||||
final s = run.suite('/repo/test/a_test.dart');
|
||||
run.test(s, 'throws on the old path', 'error');
|
||||
expect(evaluateResults(run.finish()).passed, isTrue);
|
||||
});
|
||||
|
||||
test('when one file fails to compile but another fails for real', () {
|
||||
final run = _Run();
|
||||
run.suite('/repo/test/new_api_test.dart', compiles: false);
|
||||
final s = run.suite('/repo/test/behavior_test.dart');
|
||||
run.test(s, 'old behavior is wrong', 'failure');
|
||||
expect(evaluateResults(run.finish()).passed, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('check 2 fails', () {
|
||||
test('when every changed test passes on the base code too', () {
|
||||
final run = _Run();
|
||||
final s = run.suite('/repo/test/a_test.dart');
|
||||
run.test(s, 'token test', 'success');
|
||||
run.test(s, 'another token test', 'success');
|
||||
final d = evaluateResults(run.finish());
|
||||
expect(d.passed, isFalse);
|
||||
expect(d.message, contains('pass on the base code too'));
|
||||
});
|
||||
|
||||
test('when the only failures are compile failures', () {
|
||||
final run = _Run();
|
||||
run.suite('/repo/test/new_api_test.dart', compiles: false);
|
||||
final d = evaluateResults(run.finish());
|
||||
expect(d.passed, isFalse);
|
||||
expect(d.message, contains('no changed test ran'));
|
||||
expect(d.message, contains('/repo/test/new_api_test.dart'));
|
||||
});
|
||||
|
||||
test('when compiled tests pass and the rest do not compile', () {
|
||||
final run = _Run();
|
||||
run.suite('/repo/test/new_api_test.dart', compiles: false);
|
||||
final s = run.suite('/repo/test/b_test.dart');
|
||||
run.test(s, 'passes anyway', 'success');
|
||||
final d = evaluateResults(run.finish());
|
||||
expect(d.passed, isFalse);
|
||||
expect(d.message, contains('/repo/test/new_api_test.dart'));
|
||||
});
|
||||
|
||||
test('when only a setUpAll hook fails, since no real test ran', () {
|
||||
final run = _Run();
|
||||
final s = run.suite('/repo/test/a_test.dart');
|
||||
run.failedSetUpAll(s);
|
||||
final d = evaluateResults(run.finish());
|
||||
expect(d.passed, isFalse);
|
||||
expect(d.message, contains('no changed test ran'));
|
||||
});
|
||||
|
||||
test('when the only non-passing test was skipped', () {
|
||||
final run = _Run();
|
||||
final s = run.suite('/repo/test/a_test.dart');
|
||||
run.test(s, 'skipped', 'success', skipped: true);
|
||||
expect(evaluateResults(run.finish()).passed, isFalse);
|
||||
});
|
||||
|
||||
test('when the run never finished', () {
|
||||
final run = _Run();
|
||||
final s = run.suite('/repo/test/a_test.dart');
|
||||
run.test(s, 'would have failed', 'failure');
|
||||
final d = evaluateResults(run.finish(done: false));
|
||||
expect(d.passed, isFalse);
|
||||
expect(d.message, contains('did not finish'));
|
||||
});
|
||||
|
||||
test('when the output is empty or not JSON', () {
|
||||
expect(evaluateResults('').passed, isFalse);
|
||||
expect(evaluateResults('Error: flutter crashed\n').passed, isFalse);
|
||||
});
|
||||
|
||||
test('when events are malformed, without crashing', () {
|
||||
const lines = [
|
||||
'{"type":"testStart"}',
|
||||
'{"type":"testStart","test":null}',
|
||||
'{"type":"testStart","test":{"id":"7","name":5}}',
|
||||
'{"type":"testDone"}',
|
||||
'{"type":"testDone","testID":"7","result":"failure"}',
|
||||
'{"type":"testDone","testID":99,"result":"failure"}',
|
||||
'{"type":"suite","suite":[]}',
|
||||
'[1,2,3]',
|
||||
'{"type":"done","success":false}',
|
||||
];
|
||||
final d = evaluateResults(lines.join('\n'));
|
||||
expect(d.passed, isFalse);
|
||||
});
|
||||
|
||||
test('a failure for a test that never started is not counted', () {
|
||||
const lines = [
|
||||
'{"type":"testDone","testID":42,"result":"failure","hidden":false}',
|
||||
'{"type":"done","success":false}',
|
||||
];
|
||||
expect(evaluateResults(lines.join('\n')).passed, isFalse);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,184 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import '../../tool/test_gate.dart';
|
||||
|
||||
List<ChangedFile> _changed(Map<String, String> files) =>
|
||||
files.entries.map((e) => ChangedFile(e.value, e.key)).toList();
|
||||
|
||||
void main() {
|
||||
group('prType', () {
|
||||
test('reads the type with and without a scope', () {
|
||||
expect(prType('fix(#1028): wait for the radio'), 'fix');
|
||||
expect(prType('feat: a new thing'), 'feat');
|
||||
expect(prType('Refactor(#1): tidy'), 'refactor');
|
||||
expect(prType('feat!: breaking'), 'feat');
|
||||
});
|
||||
|
||||
test('is null when the title has no conventional type', () {
|
||||
expect(prType('Wait for the radio before adding'), isNull);
|
||||
expect(prType('fix the add path'), isNull);
|
||||
expect(prType(''), isNull);
|
||||
});
|
||||
});
|
||||
|
||||
group('parseNameStatus', () {
|
||||
// `git diff --name-status -z`: every field ends in NUL; a rename or copy
|
||||
// carries the old path, then the new one.
|
||||
test('keeps the new path of a rename and the status letter', () {
|
||||
final files = parseNameStatus(
|
||||
'M\x00lib/a.dart\x00R087\x00test/old_test.dart\x00test/new_test.dart\x00'
|
||||
'D\x00test/gone_test.dart\x00C100\x00lib/x.dart\x00lib/y.dart\x00',
|
||||
);
|
||||
expect(files.map((f) => f.path), [
|
||||
'lib/a.dart',
|
||||
'test/new_test.dart',
|
||||
'test/gone_test.dart',
|
||||
'lib/y.dart',
|
||||
]);
|
||||
expect(files[2].removed, isTrue);
|
||||
expect(files.first.removed, isFalse);
|
||||
});
|
||||
|
||||
test('takes a path with a space, tab or newline as it is, unquoted', () {
|
||||
final files = parseNameStatus(
|
||||
'M\x00lib/odd name.dart\x00A\x00test/tab\there_test.dart\x00'
|
||||
'M\x00lib/new\nline.dart\x00',
|
||||
);
|
||||
expect(files.map((f) => f.path), [
|
||||
'lib/odd name.dart',
|
||||
'test/tab\there_test.dart',
|
||||
'lib/new\nline.dart',
|
||||
]);
|
||||
});
|
||||
|
||||
test('a path git would quote still counts as app code', () {
|
||||
final d = decideScope(
|
||||
title: 'fix: x',
|
||||
changed: parseNameStatus('M\x00lib/odd "name".dart\x00'),
|
||||
);
|
||||
expect(d.passed, isFalse);
|
||||
});
|
||||
|
||||
test('ignores a truncated trailing record', () {
|
||||
final files = parseNameStatus(
|
||||
'M\x00lib/a.dart\x00R100\x00lib/b.dart\x00',
|
||||
);
|
||||
expect(files.map((f) => f.path), ['lib/a.dart']);
|
||||
});
|
||||
});
|
||||
|
||||
group('entries file', () {
|
||||
test('is NUL-separated so xargs -0 passes each path whole', () {
|
||||
expect(
|
||||
encodeEntries(['test/a b_test.dart', 'test/c_test.dart']),
|
||||
'test/a b_test.dart\x00test/c_test.dart\x00',
|
||||
);
|
||||
expect(encodeEntries([]), '');
|
||||
});
|
||||
});
|
||||
|
||||
group('check 1: a code change needs a test change', () {
|
||||
test('code with no test change fails and names the code files', () {
|
||||
final d = decideScope(
|
||||
title: 'fix(#1): something',
|
||||
changed: _changed({'lib/connector/x.dart': 'M'}),
|
||||
);
|
||||
expect(d.passed, isFalse);
|
||||
expect(d.runEvaluate, isFalse);
|
||||
expect(d.message, contains('lib/connector/x.dart'));
|
||||
});
|
||||
|
||||
test('a title with no type is enforced, not exempt', () {
|
||||
final d = decideScope(
|
||||
title: 'Make the add wait',
|
||||
changed: _changed({'lib/x.dart': 'M'}),
|
||||
);
|
||||
expect(d.passed, isFalse);
|
||||
});
|
||||
|
||||
test('a deleted test does not count as a test change', () {
|
||||
final d = decideScope(
|
||||
title: 'fix: x',
|
||||
changed: _changed({'lib/x.dart': 'M', 'test/x_test.dart': 'D'}),
|
||||
);
|
||||
expect(d.passed, isFalse);
|
||||
});
|
||||
|
||||
test('a changed helper that is not a *_test.dart does not count', () {
|
||||
final d = decideScope(
|
||||
title: 'fix: x',
|
||||
changed: _changed({'lib/x.dart': 'M', 'test/helpers/fake.dart': 'M'}),
|
||||
);
|
||||
expect(d.passed, isFalse);
|
||||
});
|
||||
|
||||
test('code with a changed test passes and hands the tests to check 2', () {
|
||||
final d = decideScope(
|
||||
title: 'fix(#1): x',
|
||||
changed: _changed({
|
||||
'lib/x.dart': 'M',
|
||||
'test/x_test.dart': 'A',
|
||||
'test/y_test.dart': 'M',
|
||||
'test/z_test.dart': 'D',
|
||||
}),
|
||||
);
|
||||
expect(d.passed, isTrue);
|
||||
expect(d.runEvaluate, isTrue);
|
||||
expect(d.testEntries, ['test/x_test.dart', 'test/y_test.dart']);
|
||||
});
|
||||
|
||||
test('translations alone are not app code', () {
|
||||
final d = decideScope(
|
||||
title: 'fix: wording',
|
||||
changed: _changed({
|
||||
'lib/l10n/app_en.arb': 'M',
|
||||
'lib/l10n/app_localizations_en.dart': 'M',
|
||||
}),
|
||||
);
|
||||
expect(d.passed, isTrue);
|
||||
expect(d.runEvaluate, isFalse);
|
||||
});
|
||||
|
||||
test('no code change passes without running check 2', () {
|
||||
final d = decideScope(
|
||||
title: 'fix: docs and a tool',
|
||||
changed: _changed({'README.md': 'M', 'tool/x.dart': 'M'}),
|
||||
);
|
||||
expect(d.passed, isTrue);
|
||||
expect(d.runEvaluate, isFalse);
|
||||
});
|
||||
|
||||
test('a test-only change passes without running check 2', () {
|
||||
final d = decideScope(
|
||||
title: 'test: cover the self-key path',
|
||||
changed: _changed({'test/x_test.dart': 'A'}),
|
||||
);
|
||||
expect(d.passed, isTrue);
|
||||
expect(d.runEvaluate, isFalse);
|
||||
});
|
||||
});
|
||||
|
||||
group('exempt types', () {
|
||||
for (final type in exemptTypes) {
|
||||
test('$type is exempt and says so', () {
|
||||
final d = decideScope(
|
||||
title: '$type(#1): no behavior change',
|
||||
changed: _changed({'lib/x.dart': 'M'}),
|
||||
);
|
||||
expect(d.passed, isTrue);
|
||||
expect(d.runEvaluate, isFalse);
|
||||
expect(d.message, startsWith('EXEMPT'));
|
||||
});
|
||||
}
|
||||
|
||||
test('fix and feat are enforced', () {
|
||||
for (final type in ['fix', 'feat', 'perf']) {
|
||||
final d = decideScope(
|
||||
title: '$type: x',
|
||||
changed: _changed({'lib/x.dart': 'M'}),
|
||||
);
|
||||
expect(d.passed, isFalse, reason: type);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,307 @@
|
||||
// CI test gate (#1173). Two checks on a pull request:
|
||||
//
|
||||
// 1. scope: a change to app code (lib/) must come with an added or
|
||||
// changed *_test.dart file.
|
||||
// 2. evaluate: those test files, run against the base branch's lib/, must
|
||||
// include at least one real test that fails or throws. A test
|
||||
// file that only fails to compile against the base does not
|
||||
// count: it proves nothing about behavior.
|
||||
//
|
||||
// A PR whose title declares a type that claims no new or fixed behavior is
|
||||
// exempt from both. Anything else, including no type at all, is enforced.
|
||||
// There is no flag or label that skips the gate (#927).
|
||||
//
|
||||
// Usage (from .github/workflows/test_gate.yml):
|
||||
// dart run tool/test_gate.dart scope --changed changed.txt --entries entries.txt
|
||||
// dart run tool/test_gate.dart evaluate --results results.jsonl
|
||||
// The PR title is read from the PR_TITLE environment variable, never from an
|
||||
// argument the workflow interpolates into a shell line.
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
const exemptTypes = {
|
||||
'refactor',
|
||||
'chore',
|
||||
'ci',
|
||||
'build',
|
||||
'docs',
|
||||
'style',
|
||||
'test',
|
||||
};
|
||||
|
||||
/// The conventional-commit type of a PR title, lowercased, or null when the
|
||||
/// title does not start with one (`type:`, `type(scope):`, `type!:`).
|
||||
String? prType(String title) {
|
||||
final match = RegExp(r'^([A-Za-z]+)(\([^)]*\))?!?:').firstMatch(title.trim());
|
||||
return match?.group(1)!.toLowerCase();
|
||||
}
|
||||
|
||||
/// App code the gate holds to the rule. Translations and their generated
|
||||
/// Dart are mechanical and excluded.
|
||||
bool isAppCode(String path) =>
|
||||
path.startsWith('lib/') && !path.startsWith('lib/l10n/');
|
||||
|
||||
bool isTestEntry(String path) =>
|
||||
path.startsWith('test/') && path.endsWith('_test.dart');
|
||||
|
||||
class ChangedFile {
|
||||
const ChangedFile(this.status, this.path);
|
||||
final String status;
|
||||
final String path;
|
||||
|
||||
bool get removed => status.startsWith('D');
|
||||
}
|
||||
|
||||
/// Parses `git diff --name-status -z` output: NUL-terminated fields, paths
|
||||
/// never quoted. A rename or copy (status R or C) carries the old path and
|
||||
/// then the new one; the new path is the one that exists in the PR.
|
||||
List<ChangedFile> parseNameStatus(String text) {
|
||||
final fields = text.split('\x00');
|
||||
// Every field ends in NUL, so the split leaves one empty string after the
|
||||
// last one. It is not a field, and must not be read as a path.
|
||||
if (fields.isNotEmpty && fields.last.isEmpty) fields.removeLast();
|
||||
final files = <ChangedFile>[];
|
||||
var i = 0;
|
||||
while (i < fields.length) {
|
||||
final status = fields[i];
|
||||
if (status.isEmpty) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
final paths = status.startsWith('R') || status.startsWith('C') ? 2 : 1;
|
||||
if (i + paths >= fields.length) break;
|
||||
files.add(ChangedFile(status, fields[i + paths]));
|
||||
i += paths + 1;
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/// The test files for check 2, NUL-terminated for `xargs -0`.
|
||||
String encodeEntries(List<String> entries) =>
|
||||
entries.map((e) => '$e\x00').join();
|
||||
|
||||
class ScopeDecision {
|
||||
const ScopeDecision({
|
||||
required this.passed,
|
||||
required this.runEvaluate,
|
||||
required this.message,
|
||||
this.testEntries = const [],
|
||||
});
|
||||
|
||||
final bool passed;
|
||||
final bool runEvaluate;
|
||||
final String message;
|
||||
final List<String> testEntries;
|
||||
}
|
||||
|
||||
ScopeDecision decideScope({
|
||||
required String title,
|
||||
required List<ChangedFile> changed,
|
||||
}) {
|
||||
final type = prType(title);
|
||||
if (type != null && exemptTypes.contains(type)) {
|
||||
return ScopeDecision(
|
||||
passed: true,
|
||||
runEvaluate: false,
|
||||
message:
|
||||
'EXEMPT: PR type "$type" claims no new or fixed behavior, so the '
|
||||
'test gate does not apply. A fix or a feature must not use this type.',
|
||||
);
|
||||
}
|
||||
final code = changed.where((f) => isAppCode(f.path)).toList();
|
||||
if (code.isEmpty) {
|
||||
return const ScopeDecision(
|
||||
passed: true,
|
||||
runEvaluate: false,
|
||||
message:
|
||||
'No app code (lib/) changed; nothing for the test gate to check.',
|
||||
);
|
||||
}
|
||||
final entries = changed
|
||||
.where((f) => !f.removed && isTestEntry(f.path))
|
||||
.map((f) => f.path)
|
||||
.toList();
|
||||
if (entries.isEmpty) {
|
||||
final list = code.map((f) => ' ${f.path}').join('\n');
|
||||
return ScopeDecision(
|
||||
passed: false,
|
||||
runEvaluate: false,
|
||||
message:
|
||||
'FAIL (check 1): app code changed but no *_test.dart file was added '
|
||||
'or changed. Every fix and every new capability ships with a test.\n'
|
||||
'Code changed:\n$list',
|
||||
);
|
||||
}
|
||||
return ScopeDecision(
|
||||
passed: true,
|
||||
runEvaluate: true,
|
||||
testEntries: entries,
|
||||
message:
|
||||
'Check 1 passed: ${entries.length} test file(s) changed alongside '
|
||||
'${code.length} code file(s). Check 2 runs them against the base code.',
|
||||
);
|
||||
}
|
||||
|
||||
class EvaluateDecision {
|
||||
const EvaluateDecision(this.passed, this.message);
|
||||
final bool passed;
|
||||
final String message;
|
||||
}
|
||||
|
||||
/// The runner reports a file's compile as a `loading <path>` test, and a
|
||||
/// group hook as `(setUpAll)` / `(tearDownAll)`. None of them is a test of
|
||||
/// behavior: a hook that throws stops the file's real tests from running.
|
||||
bool _isPseudoTest(String name) =>
|
||||
name.startsWith('loading ') ||
|
||||
name == '(setUpAll)' ||
|
||||
name == '(tearDownAll)';
|
||||
|
||||
/// Reads `flutter test --reporter json` output from a run of the PR's test
|
||||
/// files against the base branch's code.
|
||||
EvaluateDecision evaluateResults(String jsonLines) {
|
||||
final names = <int, String>{};
|
||||
final suitePaths = <int, String>{};
|
||||
final testSuite = <int, int>{};
|
||||
final failing = <String>[];
|
||||
final unloadable = <String>{};
|
||||
var realTestsRun = 0;
|
||||
var sawDone = false;
|
||||
|
||||
// Every field is type-checked, and anything unexpected is skipped. A
|
||||
// skipped event can only lose proof, never invent it, so a format change
|
||||
// fails the gate closed (and the workflow's self-check names it).
|
||||
for (final line in const LineSplitter().convert(jsonLines)) {
|
||||
final trimmed = line.trim();
|
||||
if (!trimmed.startsWith('{')) continue;
|
||||
final Object? decoded;
|
||||
try {
|
||||
decoded = jsonDecode(trimmed);
|
||||
} on FormatException {
|
||||
continue;
|
||||
}
|
||||
if (decoded is! Map<String, dynamic>) continue;
|
||||
switch (decoded['type']) {
|
||||
case 'suite':
|
||||
final suite = decoded['suite'];
|
||||
if (suite is! Map<String, dynamic>) break;
|
||||
final id = suite['id'];
|
||||
final path = suite['path'];
|
||||
if (id is int && path is String) suitePaths[id] = path;
|
||||
case 'testStart':
|
||||
final test = decoded['test'];
|
||||
if (test is! Map<String, dynamic>) break;
|
||||
final id = test['id'];
|
||||
final name = test['name'];
|
||||
if (id is! int || name is! String) break;
|
||||
names[id] = name;
|
||||
final suiteId = test['suiteID'];
|
||||
if (suiteId is int) testSuite[id] = suiteId;
|
||||
case 'testDone':
|
||||
final id = decoded['testID'];
|
||||
if (id is! int) break;
|
||||
// A result for a test that never started proves nothing.
|
||||
final name = names[id];
|
||||
if (name == null) break;
|
||||
final result = decoded['result'];
|
||||
if (decoded['skipped'] == true) break;
|
||||
if (_isPseudoTest(name)) {
|
||||
if (name.startsWith('loading ') && result != 'success') {
|
||||
unloadable.add(suitePaths[testSuite[id]] ?? name);
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (decoded['hidden'] == true) break;
|
||||
realTestsRun++;
|
||||
if (result == 'failure' || result == 'error') failing.add(name);
|
||||
case 'done':
|
||||
sawDone = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!sawDone) {
|
||||
return const EvaluateDecision(
|
||||
false,
|
||||
'FAIL (check 2): the test run did not finish, so nothing was proven. '
|
||||
'See the step log for the runner output.',
|
||||
);
|
||||
}
|
||||
if (failing.isNotEmpty) {
|
||||
final list = failing.map((n) => ' $n').join('\n');
|
||||
return EvaluateDecision(
|
||||
true,
|
||||
'Check 2 passed: ${failing.length} test(s) fail on the base code, so '
|
||||
'they guard this change:\n$list',
|
||||
);
|
||||
}
|
||||
final notCompiled = unloadable.isEmpty
|
||||
? ''
|
||||
: '\nThese files do not compile against the base code, which proves '
|
||||
'nothing about behavior:\n${unloadable.map((p) => ' $p').join('\n')}';
|
||||
if (realTestsRun == 0) {
|
||||
return EvaluateDecision(
|
||||
false,
|
||||
'FAIL (check 2): no changed test ran against the base code, so none of '
|
||||
'them shows the old behavior failing. Add at least one test that uses '
|
||||
'only code the base branch already has, and that fails there.'
|
||||
'$notCompiled',
|
||||
);
|
||||
}
|
||||
return EvaluateDecision(
|
||||
false,
|
||||
'FAIL (check 2): all $realTestsRun changed test(s) that ran pass on the '
|
||||
'base code too, so none of them guards this change. A regression test '
|
||||
'must fail without the fix.$notCompiled',
|
||||
);
|
||||
}
|
||||
|
||||
void _appendTo(String? path, String text) {
|
||||
if (path == null || path.isEmpty) return;
|
||||
File(path).writeAsStringSync(text, mode: FileMode.append);
|
||||
}
|
||||
|
||||
String _arg(List<String> args, String name) {
|
||||
final i = args.indexOf(name);
|
||||
if (i < 0 || i + 1 >= args.length) {
|
||||
stderr.writeln('missing $name');
|
||||
exit(2);
|
||||
}
|
||||
return args[i + 1];
|
||||
}
|
||||
|
||||
void main(List<String> args) {
|
||||
if (args.isEmpty) {
|
||||
stderr.writeln('usage: test_gate.dart scope|evaluate ...');
|
||||
exit(2);
|
||||
}
|
||||
final summary = Platform.environment['GITHUB_STEP_SUMMARY'];
|
||||
switch (args.first) {
|
||||
case 'scope':
|
||||
final decision = decideScope(
|
||||
title: Platform.environment['PR_TITLE'] ?? '',
|
||||
changed: parseNameStatus(
|
||||
File(_arg(args, '--changed')).readAsStringSync(),
|
||||
),
|
||||
);
|
||||
File(
|
||||
_arg(args, '--entries'),
|
||||
).writeAsStringSync(encodeEntries(decision.testEntries));
|
||||
_appendTo(
|
||||
Platform.environment['GITHUB_OUTPUT'],
|
||||
'evaluate=${decision.runEvaluate}\n',
|
||||
);
|
||||
_appendTo(summary, '### Test gate\n\n${decision.message}\n\n');
|
||||
stdout.writeln(decision.message);
|
||||
exit(decision.passed ? 0 : 1);
|
||||
case 'evaluate':
|
||||
final decision = evaluateResults(
|
||||
File(_arg(args, '--results')).readAsStringSync(),
|
||||
);
|
||||
_appendTo(summary, '${decision.message}\n');
|
||||
stdout.writeln(decision.message);
|
||||
exit(decision.passed ? 0 : 1);
|
||||
default:
|
||||
stderr.writeln('unknown command ${args.first}');
|
||||
exit(2);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in new issue