Skip to content

Commit 46a3b30

Browse files
authored
Default onLog falls back to print. (#4049)
1 parent 3d10b16 commit 46a3b30

File tree

3 files changed

+34
-7
lines changed

3 files changed

+34
-7
lines changed

build_test/CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
read and resolved.
66
- Add `loadIsolateSources` to `ReaderWriterTesting`. It loads all real
77
sources visible to the test into memory.
8+
- `testBuilder` default `onLog` now works outside of tests: it falls
9+
back to `print` instead of crashing.
810

911
## 3.0.0
1012

build_test/lib/src/test_builder.dart

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -230,12 +230,7 @@ Future<TestBuilderResult> testBuilders(
230230
TestReaderWriter? readerWriter,
231231
bool enableLowResourceMode = false,
232232
}) async {
233-
onLog ??=
234-
(log) => printOnFailure(
235-
'$log'
236-
'${log.error == null ? '' : ' ${log.error}'}'
237-
'${log.stackTrace == null ? '' : ' ${log.stackTrace}'}',
238-
);
233+
onLog ??= _printOnFailureOrPrint;
239234

240235
var inputIds = {
241236
for (var descriptor in sourceAssets.keys) makeAssetId(descriptor),
@@ -370,3 +365,17 @@ class TestBuilderResult {
370365

371366
TestBuilderResult({required this.buildResult, required this.readerWriter});
372367
}
368+
369+
void _printOnFailureOrPrint(LogRecord record) {
370+
final message =
371+
'$record'
372+
'${record.error == null ? '' : ' ${record.error}'}'
373+
'${record.stackTrace == null ? '' : ' ${record.stackTrace}'}';
374+
try {
375+
// This throws if a test is not currently running.
376+
printOnFailure(message);
377+
} catch (_) {
378+
// Print instead.
379+
print(message);
380+
}
381+
}

build_test/test/test_builder_test.dart

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,23 @@ import 'package:glob/glob.dart';
1010
import 'package:package_config/package_config.dart';
1111
import 'package:test/test.dart';
1212

13-
void main() {
13+
Future<void> main() async {
14+
// Default logging uses `printOnFailure` which crashes outside tests; check
15+
// that it falls back to `print` outside tests.
16+
final printed = <String>[];
17+
await runZonedGuarded(
18+
() async {
19+
await testBuilder(TestBuilder(), {'a|lib/a.dart': ''}, rootPackage: 'a');
20+
},
21+
(_, _) {},
22+
zoneSpecification: ZoneSpecification(
23+
print: (_, _, _, string) {
24+
printed.add(string);
25+
},
26+
),
27+
);
28+
if (printed.isEmpty) throw StateError('Expected some prints.');
29+
1430
test('can glob files in the root package', () async {
1531
var assets = {
1632
'a|lib/a.globPlaceholder': '',

0 commit comments

Comments
 (0)