-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathhot_reload_suite.dart
1420 lines (1334 loc) · 56.9 KB
/
hot_reload_suite.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:_fe_analyzer_shared/src/util/relativize.dart' as fe_shared;
import 'package:args/args.dart';
import 'package:collection/collection.dart';
import 'package:dev_compiler/dev_compiler.dart' as ddc_names
show libraryUriToJsIdentifier;
import 'package:front_end/src/api_unstable/ddc.dart' as fe;
import 'package:path/path.dart' as p;
import 'package:reload_test/ddc_helpers.dart' as ddc_helpers;
import 'package:reload_test/frontend_server_controller.dart';
import 'package:reload_test/hot_reload_memory_filesystem.dart';
import 'package:reload_test/hot_reload_receipt.dart';
import 'package:reload_test/test_helpers.dart';
final buildRootUri = fe.computePlatformBinariesLocation(forceBuildDir: true);
final sdkRoot = Platform.script.resolve('../../../');
/// SDK test directory containing hot reload tests.
final allTestsUri = sdkRoot.resolve('tests/hot_reload/');
/// The separator between a test file and its inlined diff.
///
/// All contents after this separator are considered are diff comments.
final testDiffSeparator = '/** DIFF **/';
Future<void> main(List<String> args) async {
final options = Options.parse(args);
if (options.help) {
print(options.usage);
return;
}
final runner = switch (options.runtime) {
RuntimePlatforms.chrome => ChromeSuiteRunner(options),
RuntimePlatforms.d8 => D8SuiteRunner(options),
RuntimePlatforms.vm => VMSuiteRunner(options),
};
await runner.runSuite(options);
}
/// Command line options for the hot reload test suite.
class Options {
final bool help;
final RuntimePlatforms runtime;
final String namedConfiguration;
final Uri? testResultsOutputDir;
final RegExp testNameFilter;
final DiffMode diffMode;
final bool debug;
final bool verbose;
Options._({
required this.help,
required this.runtime,
required this.namedConfiguration,
required this.testResultsOutputDir,
required this.testNameFilter,
required this.diffMode,
required this.debug,
required this.verbose,
});
static final _parser = ArgParser()
..addFlag('help',
abbr: 'h',
help: 'Display this message.',
negatable: false,
defaultsTo: false)
..addOption('runtime',
abbr: 'r',
defaultsTo: 'd8',
allowed: RuntimePlatforms.values.map((v) => v.text),
help: 'runtime platform used to run tests.')
..addOption('named-configuration',
abbr: 'n',
defaultsTo: 'no-configuration',
help: 'configuration name to use for emitting test result files.')
..addOption('output-directory',
help: 'directory to emit test results files.')
..addOption('filter',
abbr: 'f', defaultsTo: r'.*', help: 'regexp filter over tests to run.')
..addOption('diff',
allowed: ['check', 'write', 'ignore'],
allowedHelp: {
'check': 'validate that reload test diffs are generated and correct.',
'write': 'write diffs for reload tests.',
'ignore': 'ignore reload diffs.',
},
defaultsTo: 'check',
help: 'selects whether test diffs should be checked, written, or '
'ignored.')
..addFlag('debug',
abbr: 'd',
defaultsTo: false,
negatable: true,
help: 'enables additional debug behavior and logging.')
..addFlag('verbose',
abbr: 'v',
defaultsTo: true,
negatable: true,
help: 'enables verbose logging.');
/// Usage description for these command line options.
String get usage => _parser.usage;
factory Options.parse(List<String> args) {
final results = _parser.parse(args);
return Options._(
help: results.flag('help'),
runtime: RuntimePlatforms.values.byName(results.option('runtime')!),
namedConfiguration: results.option('named-configuration')!,
testResultsOutputDir: results.wasParsed('output-directory')
? Uri.directory(results.option('output-directory')!)
: null,
testNameFilter: RegExp(results.option('filter')!),
diffMode: switch (results.option('diff')!) {
'check' => DiffMode.check,
'write' => DiffMode.write,
'ignore' => DiffMode.ignore,
_ => throw Exception('Invalid diff mode: ${results.option('diff')}'),
},
debug: results.flag('debug'),
verbose: results.flag('verbose'),
);
}
}
/// Modes for running diff check tests on the hot reload suite.
enum DiffMode { check, write, ignore }
/// A single test for the hot reload test suite.
///
/// A hot reload test is made of a collection of one or more Dart files over a
/// number of generational edits that represent interactions with source files
/// over the life of a running test program.
///
/// Tests in this suite also define a config.json file with further information
/// describing how the test runs.
class HotReloadTest {
/// Root [Directory] containing the source files for this test.
final Directory directory;
/// Test name used in results.
///
/// By convention this matches the name of the [directory].
final String name;
/// The files that make up this test.
final List<TestFile> files;
/// The number of generations in this test (one-based).
final int generationCount;
/// Platforms that should not run this test.
final Set<RuntimePlatforms> excludedPlatforms;
/// Edit rejection error messages expected from this test when a hot reload is
/// triggered by the generation in which the error is expected.
///
/// Specified in the `config.json` file.
// TODO(nshahan): Support multiple expected errors for a single generation.
final Map<int, String> expectedErrors;
/// Map of generation number to whether a hot restart was triggered before the
/// generation.
final Map<int, bool> isHotRestart;
HotReloadTest(this.directory, this.name, this.generationCount, this.files,
ReloadTestConfiguration config, this.isHotRestart)
: excludedPlatforms = config.excludedPlatforms,
expectedErrors = config.expectedErrors;
/// The files edited in the provided [generation] (zero-based).
List<TestFile> filesEditedInGeneration(int generation) => [
for (final file in files)
if (file._editsByGeneration.containsKey(generation)) file
];
}
/// An individual test file for a hot reload test across all generations.
class TestFile {
/// The reconstructed name of the file after removing the generation tag.
///
/// For example given the files foo.0.dart, foo.1.dart, and foo.2.dart the
/// [baseName] would be 'foo.dart'.
final String baseName;
/// The individual edits of this file by their generations (zero-based).
///
/// By convention, iterating the entries produces them in generational order
/// but there could be gaps in the generation numbers.
// TODO(nshahan): Move the creation of this data structure to this class to
// ensure the iteration order. Alternatively, update the representation to
// require there are no gaps in the generations so we don't have to handle
// them and can just use a list.
final LinkedHashMap<int, TestFileEdit> _editsByGeneration;
TestFile(this.baseName, this._editsByGeneration);
/// Returns the [TestFileEdit] for the given [generation] (zero-based) for
/// this file.
TestFileEdit editForGeneration(int generation) {
final edit = _editsByGeneration[generation];
if (edit == null) {
throw Exception('File: $baseName has no generation: $generation.');
}
return edit;
}
/// All edits for this file in order by generation.
List<TestFileEdit> get edits => _editsByGeneration.values.toList();
}
/// A single version of a test file at a specific generation.
class TestFileEdit {
/// The generation this edit belongs to.
final int generation;
/// The location of this file on disk.
final Uri fileUri;
TestFileEdit(this.generation, this.fileUri);
}
abstract class HotReloadSuiteRunner {
Options options;
/// The root directory containing generated code for all tests.
late final Directory generatedCodeDir = Directory.systemTemp.createTempSync();
/// The directory containing files emitted from Frontend Server compiles and
/// recompiles.
late final Directory frontendServerEmittedFilesDir =
Directory.fromUri(generatedCodeDir.uri.resolve('.fes/'))..createSync();
/// The output location for .dill file created by the front end server.
late final Uri outputDillUri =
frontendServerEmittedFilesDir.uri.resolve('output.dill');
/// The output location for the incremental .dill file created by the front
/// end server.
late final Uri outputIncrementalDillUri =
frontendServerEmittedFilesDir.uri.resolve('output_incremental.dill');
/// All test results that are reported after running the entire test suite.
final List<TestResultOutcome> testOutcomes = [];
/// The directory used as a temporary staging area to construct a compile-able
/// test app across reload/restart generations.
late final Directory snapshotDir =
Directory.fromUri(generatedCodeDir.uri.resolve('.snapshot/'))
..createSync();
// TODO(markzipan): Support custom entrypoints.
late final Uri snapshotEntrypointUri = snapshotDir.uri.resolve('main.dart');
late final String snapshotEntrypointWithScheme = () {
final snapshotEntrypointLibraryName = fe_shared.relativizeUri(
snapshotDir.uri, snapshotEntrypointUri, fe_shared.isWindows);
return '$filesystemScheme:///$snapshotEntrypointLibraryName';
}();
HotReloadMemoryFilesystem? filesystem;
final stopwatch = Stopwatch();
final filesystemScheme = 'hot-reload-test';
HotReloadSuiteRunner(this.options);
Future<void> runSuite(Options options) async {
// TODO(nshahan): report time for collecting and validating test sources.
final testSuite = collectTestSources(options);
_debugPrint(
'See generated hot reload framework code in ${generatedCodeDir.uri}');
final controller = createFrontEndServer();
for (final test in testSuite) {
stopwatch
..start()
..reset();
diffCheck(test);
final tempDirectory =
Directory.fromUri(generatedCodeDir.uri.resolve('${test.name}/'))
..createSync();
if (options.runtime.emitsJS) {
filesystem = HotReloadMemoryFilesystem(tempDirectory.uri);
}
var compileSuccess = false;
_print('Generating test assets.', label: test.name);
// TODO(markzipan): replace this with a test-configurable main entrypoint.
final mainDartFilePath =
test.directory.uri.resolve('main.dart').toFilePath();
_debugPrint('Test entrypoint: $mainDartFilePath', label: test.name);
_print('Generating code over ${test.generationCount} generations.',
label: test.name);
stopwatch
..start()
..reset();
for (var generation = 0;
generation < test.generationCount;
generation++) {
final updatedFiles = copyGenerationSources(test, generation);
compileSuccess = await compileGeneration(
test, generation, tempDirectory, updatedFiles, controller);
if (!compileSuccess) break;
}
if (!compileSuccess) {
_print('Did not emit all assets due to compilation error.',
label: test.name);
// Skip to the next test and avoid execution if there is an unexpected
// compilation error.
continue;
}
_print('Finished emitting assets.', label: test.name);
final testOutputStreamController = StreamController<List<int>>();
final testOutputBuffer = StringBuffer();
testOutputStreamController.stream
.transform(utf8.decoder)
.listen(testOutputBuffer.write);
final testPassed = await runTest(
test, tempDirectory, IOSink(testOutputStreamController.sink));
await reportTestOutcome(
test.name, testOutputBuffer.toString(), testPassed);
}
await shutdown(controller);
await reportAllResults();
}
/// Custom command line arguments passed to the Front End Server on startup.
List<String> get platformFrontEndServerArgs;
/// Returns a controller for a freshly started front end server instance to
/// handle compile and recompile requests for a hot reload test.
HotReloadFrontendServerController createFrontEndServer() {
_print('Initializing the Frontend Server.');
final packageConfigUri = sdkRoot.resolve('.dart_tool/package_config.json');
final fesArgs = [
'--incremental',
'--filesystem-root=${snapshotDir.uri.toFilePath()}',
'--filesystem-scheme=$filesystemScheme',
'--output-dill=${outputDillUri.toFilePath()}',
'--output-incremental-dill=${outputIncrementalDillUri.toFilePath()}',
'--packages=${packageConfigUri.toFilePath()}',
'--sdk-root=${sdkRoot.toFilePath()}',
'--verbosity=${options.verbose ? 'all' : 'info'}',
...platformFrontEndServerArgs,
];
return HotReloadFrontendServerController(fesArgs)..start();
}
Future<void> shutdown(HotReloadFrontendServerController controller) async {
// Persist the temp directory for debugging.
await controller.stop();
_print('Frontend Server has shut down.');
if (!options.debug) {
_print('Deleting temporary directory: ${generatedCodeDir.path}.');
generatedCodeDir.deleteSync(recursive: true);
}
}
/// Returns a suite of hot reload tests discovered in the directory
/// [allTestsUri].
///
/// Assumes all files that makeup a hot reload test are named like
/// '$name.$integer.dart', where 0 is the first generation.
///
/// Count the number of generations and ensure they're capped.
// TODO(markzipan): Account for subdirectories.
List<HotReloadTest> collectTestSources(Options options) {
// Set an arbitrary cap on generations.
final globalMaxGenerations = 100;
final validTestSourceName = RegExp(
// Begins with 1 or more word characters.
r'^(?<name>[\w,-]+)'
// Followed by a dot and 1 or more digits.
r'\.(?<generation>\d+)'
// Optionally a dot and either the word 'restart' indicating a hot
// restart, or the word 'reject', indicating a hot reload rejection.
r'((?<restart>\.restart)|(?<reject>\.reject))?'
// Ending with a dot and the word 'dart'
r'\.dart$');
final testSuite = <HotReloadTest>[];
for (var testDir in Directory.fromUri(allTestsUri).listSync()) {
if (testDir is! Directory) {
if (testDir is File) {
// Ignore Dart source files, which may be imported as helpers.
continue;
}
throw Exception('Non-directory or file entity found in '
'${allTestsUri.toFilePath()}: $testDir');
}
final testDirParts = testDir.uri.pathSegments;
final testName = testDirParts[testDirParts.length - 2];
// Skip tests that don't match the name filter.
if (!options.testNameFilter.hasMatch(testName)) {
_print('Skipping test', label: testName);
continue;
}
var maxGenerations = 0;
final configFileUri = testDir.uri.resolve('config.json');
final testConfig = File.fromUri(configFileUri).existsSync()
? ReloadTestConfiguration.fromJsonFile(configFileUri)
: ReloadTestConfiguration();
if (testConfig.excludedPlatforms.contains(options.runtime)) {
// Skip this test directory if this platform is excluded.
_print('Skipping test on platform: ${options.runtime.text}',
label: testName);
continue;
}
final isHotRestart = <int, bool>{};
final expectedErrors = testConfig.expectedErrors;
final dartFiles = testDir
.listSync()
.where((e) => e is File && e.uri.path.endsWith('.dart'));
// All files in this test clustered by file name - in generation order.
final filesByGeneration = <String, PriorityQueue<TestFileEdit>>{};
for (final file in dartFiles) {
final fileName = p.basename(file.uri.toFilePath());
final matches = validTestSourceName.allMatches(fileName);
if (matches.length != 1) {
throw Exception('Invalid test source file name: $fileName\n'
'Valid names look like "file_name.10.dart", '
'"file_name.10.restart.dart" or "file_name.10.reject.dart".');
}
final match = matches.single;
final name = match.namedGroup('name');
final restoredName = '$name.dart';
final generation = int.parse(match.namedGroup('generation')!);
maxGenerations = max(maxGenerations, generation);
final restart = match.namedGroup('restart') != null;
if (!isHotRestart.containsKey(generation)) {
isHotRestart[generation] = restart;
} else {
if (restart != isHotRestart[generation]) {
throw Exception('Expected all files for generation $generation to '
"be consistent about having a '.restart' suffix, but $fileName "
'does not match other files in the same generation.');
}
}
final rejectExpected = match.namedGroup('reject') != null;
assert(!(rejectExpected && restart));
if (rejectExpected && !expectedErrors.containsKey(generation)) {
throw Exception(
'Expected error for generation file missing from config.json: '
'$fileName');
}
if (!rejectExpected && expectedErrors.containsKey(generation)) {
throw Exception(
'Error for generation $generation found in config.json: '
'"${expectedErrors[generation]}"\n'
'Either remove the error or update the name of this file: '
'$fileName -> '
'$name.$generation.reject.dart');
}
if (generation == 0 && rejectExpected) {
throw Exception('The first generation may not be rejected: '
'$fileName');
}
filesByGeneration
.putIfAbsent(
restoredName,
() => PriorityQueue((TestFileEdit a, TestFileEdit b) =>
a.generation - b.generation))
.add(TestFileEdit(generation, file.uri));
}
if (maxGenerations > globalMaxGenerations) {
throw Exception('Too many generations specified in test '
'(requested: $maxGenerations, max: $globalMaxGenerations).');
}
final testFiles = <TestFile>[];
for (final entry in filesByGeneration.entries) {
final fileName = entry.key;
final fileEdits = entry.value.toList();
final editsByGeneration = LinkedHashMap<int, TestFileEdit>.from(
{for (final edit in fileEdits) edit.generation: edit});
testFiles.add(TestFile(fileName, editsByGeneration));
}
testSuite.add(HotReloadTest(testDir, testName, maxGenerations + 1,
testFiles, testConfig, isHotRestart));
}
return testSuite;
}
/// Report results for this test's execution.
Future<void> reportTestOutcome(
String testName, String testOutput, bool testPassed) async {
stopwatch.stop();
final outcome = TestResultOutcome(
configuration: options.namedConfiguration,
testName: testName,
testOutput: testOutput,
);
outcome.elapsedTime = stopwatch.elapsed;
outcome.matchedExpectations = testPassed;
testOutcomes.add(outcome);
if (testPassed) {
_print('PASSED with:\n $testOutput', label: testName);
} else {
_print('FAILED with:\n $testOutput', label: testName);
}
}
/// Report results for this test's sources' diff validations.
void reportDiffOutcome(
String testName, Uri fileUri, String testOutput, bool testPassed) {
stopwatch.stop();
final filePath = fileUri.path;
final relativeFilePath = p.relative(filePath, from: allTestsUri.path);
final outcome = TestResultOutcome(
configuration: options.namedConfiguration,
testName: '$relativeFilePath-diff',
testOutput: testOutput,
);
outcome.elapsedTime = stopwatch.elapsed;
outcome.matchedExpectations = testPassed;
testOutcomes.add(outcome);
if (testPassed) {
_debugPrint('PASSED (diff on $filePath) with:\n $testOutput',
label: testName);
} else {
_debugPrint('FAILED (diff on $filePath) with:\n $testOutput',
label: testName);
}
}
/// Performs the desired diff checks for [test] and reports the results.
void diffCheck(HotReloadTest test) {
var diffMode = options.diffMode;
if (fe_shared.isWindows && diffMode != DiffMode.ignore) {
_print("Diffing isn't supported on Windows. Defaulting to 'ignore'.",
label: test.name);
diffMode = DiffMode.ignore;
}
switch (diffMode) {
case DiffMode.check:
_print('Checking source file diffs.', label: test.name);
for (final file in test.files) {
_debugPrint('Checking source file diffs for $file.',
label: test.name);
var edits = file.edits.iterator;
if (!edits.moveNext()) {
throw Exception('Test file created with no generation edits.');
}
var currentEdit = edits.current;
// Check that the first file does not have a diff.
var (currentCode, currentDiff) =
_splitTestByDiff(currentEdit.fileUri);
var diffCount = testDiffSeparator.allMatches(currentDiff).length;
if (diffCount == 0) {
reportDiffOutcome(test.name, currentEdit.fileUri,
'First generation does not have a diff', true);
} else {
reportDiffOutcome(test.name, currentEdit.fileUri,
'First generation should not have any diffs', false);
}
while (edits.moveNext()) {
final previousEdit = currentEdit;
currentEdit = edits.current;
final previousCode = currentCode;
(currentCode, currentDiff) = _splitTestByDiff(currentEdit.fileUri);
// Check that exactly one diff exists.
diffCount = testDiffSeparator.allMatches(currentDiff).length;
if (diffCount == 0) {
reportDiffOutcome(test.name, currentEdit.fileUri,
'No diff found for ${currentEdit.fileUri}', false);
continue;
} else if (diffCount > 1) {
reportDiffOutcome(
test.name,
currentEdit.fileUri,
'Too many diffs found for ${currentEdit.fileUri} '
'(expected 1)',
false);
continue;
}
// Check that the diff is properly generated.
// 'main' is allowed to have empty diffs since the first
// generation must be specified.
if (file.baseName != 'main.dart' && previousCode == currentCode) {
// TODO(markzipan): Should we make this an error?
_print(
'Extraneous file detected. ${currentEdit.fileUri} '
'is identical to ${previousEdit.fileUri} and can be removed.',
label: test.name);
}
final previousTempUri = generatedCodeDir.uri.resolve('__previous');
final currentTempUri = generatedCodeDir.uri.resolve('__current');
// Avoid 'No newline at end of file' messages in the output by
// appending a newline to the trimmed source code strings.
File.fromUri(previousTempUri).writeAsStringSync('$previousCode\n');
File.fromUri(currentTempUri).writeAsStringSync('$currentCode\n');
final diffOutput = _diffWithFileUris(
previousTempUri, currentTempUri,
label: test.name);
File.fromUri(previousTempUri).deleteSync();
File.fromUri(currentTempUri).deleteSync();
if (diffOutput != currentDiff) {
reportDiffOutcome(
test.name,
currentEdit.fileUri,
'Unexpected diff found for ${currentEdit.fileUri}:\n'
'-- Expected --\n$diffOutput\n'
'-- Actual --\n$currentDiff',
false);
} else {
reportDiffOutcome(test.name, currentEdit.fileUri,
'Correct diff found for ${currentEdit.fileUri}', true);
}
}
}
case DiffMode.write:
_print('Generating source file diffs.', label: test.name);
for (final file in test.files) {
_debugPrint('Generating source file diffs for ${file.edits}.',
label: test.name);
var edits = file.edits.iterator;
if (!edits.moveNext()) {
throw Exception('Test file created with no generation edits.');
}
var currentEdit = edits.current;
var (currentCode, currentDiff) =
_splitTestByDiff(currentEdit.fileUri);
// Don't generate a diff for the first file of any generation,
// and delete any diffs encountered.
if (currentDiff.isNotEmpty) {
_print('Removing extraneous diff from ${currentEdit.fileUri}',
label: test.name);
File.fromUri(currentEdit.fileUri).writeAsStringSync(currentCode);
}
while (edits.moveNext()) {
currentEdit = edits.current;
final previousCode = currentCode;
(currentCode, currentDiff) = _splitTestByDiff(currentEdit.fileUri);
final previousTempUri = generatedCodeDir.uri.resolve('__previous');
final currentTempUri = generatedCodeDir.uri.resolve('__current');
// Avoid 'No newline at end of file' messages in the output by
// appending a newline to the trimmed source code strings.
File.fromUri(previousTempUri).writeAsStringSync('$previousCode\n');
File.fromUri(currentTempUri).writeAsStringSync('$currentCode\n');
final diffOutput = _diffWithFileUris(
previousTempUri, currentTempUri,
label: test.name);
File.fromUri(previousTempUri).deleteSync();
File.fromUri(currentTempUri).deleteSync();
// Write an empty line between the code and the diff comment to
// agree with the dart formatter.
final newCurrentText = '$currentCode\n\n$diffOutput\n';
File.fromUri(currentEdit.fileUri).writeAsStringSync(newCurrentText);
_print('Writing updated diff to $currentEdit.fileUri',
label: test.name);
_debugPrint('Updated diff:\n$diffOutput', label: test.name);
reportDiffOutcome(test.name, currentEdit.fileUri,
'diff updated for $currentEdit.fileUri', true);
}
}
case DiffMode.ignore:
_print('Ignoring source file diffs.', label: test.name);
for (final file in test.files) {
for (final edit in file.edits) {
var uri = edit.fileUri;
_debugPrint('Ignoring source file diffs for $uri.',
label: test.name);
reportDiffOutcome(test.name, uri, 'Ignoring diff for $uri', true);
}
}
}
}
/// Attempts to extract a reload receipt from [line] and if found passes it as
/// a [HotReloadReceipt] to [onReloadReceipt].
///
/// If no reload receipt is found the line is passed to [orElse]. [test] is
/// only used to label debug logs.
void parseReloadReceipt(HotReloadTest test, String line,
Function(HotReloadReceipt) onReloadReceipt, Function(String) orElse) {
if (line.startsWith(HotReloadReceipt.hotReloadReceiptTag)) {
// Reload utils write reload receipts as output lines with a leading tag
// so the lines can be extracted here.
final reloadReceipt = HotReloadReceipt.fromJson(jsonDecode(
line.substring(HotReloadReceipt.hotReloadReceiptTag.length))
as Map<String, dynamic>);
onReloadReceipt(reloadReceipt);
_debugPrint(
[
'Generation ${reloadReceipt.generation} '
'was ${reloadReceipt.status.name}',
if (reloadReceipt.status == Status.rejected)
': "${reloadReceipt.rejectionMessage}"'
else
'.',
].join(),
label: test.name);
} else {
orElse(line);
}
}
/// Validates all reloads/restarts and returns `true` if they were performed
/// as expected during the test run.
///
/// This serves as a sanity check to ensure that just because no errors were
/// reported, the test still ran through all expected generations with the
/// expected accept/reject/restart status.
bool reloadReceiptCheck(
HotReloadTest test, List<HotReloadReceipt> reloadReceipts) {
// Check number of reloads.
// No reload receipt will appear for generation 0.
final expectedReloadCount = test.generationCount - 1;
if (reloadReceipts.length != expectedReloadCount) {
_print(
'Unexpected number of reloads/restarts were performed. '
'Expected: $expectedReloadCount Actual: ${reloadReceipts.length}\n'
'${reloadReceipts.join('\n')}',
label: test.name);
return false;
}
var expectedGeneration = 0;
for (final reloadReceipt in reloadReceipts) {
expectedGeneration++;
// Validate order of reloads.
if (reloadReceipt.generation != expectedGeneration) {
_print(
'Generation reload order mismatch. '
'Expected: $expectedGeneration '
'Actual: ${reloadReceipt.generation}\n'
'${reloadReceipts.join('\n')}',
label: test.name);
return false;
}
final expectedError = test.expectedErrors[reloadReceipt.generation];
// Check the reloads match the expected accept/reject.
if (reloadReceipt.status == Status.accepted && expectedError != null) {
_print(
'Generation ${reloadReceipt.generation} was not rejected. '
'Expected: $expectedError',
label: test.name);
return false;
}
if (reloadReceipt.status == Status.rejected) {
if (expectedError == null) {
_print(
'Generation ${reloadReceipt.generation} was unexpectedly '
'rejected: ${reloadReceipt.rejectionMessage}',
label: test.name);
return false;
}
final rejectionMessage = reloadReceipt.rejectionMessage;
if (rejectionMessage == null ||
!rejectionMessage.contains(expectedError)) {
_print(
'Generation ${reloadReceipt.generation} was rejected but error '
'was unexpected. Expected: "$expectedError" Actual: '
'${reloadReceipt.rejectionMessage}',
label: test.name);
return false;
}
}
}
_debugPrint(
'Generation reloads matched expected outcomes:\n'
' ${reloadReceipts.join('\n ')}',
label: test.name);
return true;
}
/// Copy all files in [test] for the given [generation] into the snapshot
/// directory and returns uris of all the files copied.
///
/// The uris describe the copy destination in the form of the hot reload file
/// system scheme.
List<String> copyGenerationSources(HotReloadTest test, int generation) {
_debugPrint('Entering generation $generation', label: test.name);
final updatedFilesInCurrentGeneration = <String>[];
// Copy all files in this generation to the snapshot directory with their
// names restored (e.g., path/to/main' from 'path/to/main.0.dart).
// TODO(markzipan): support subdirectories.
_debugPrint(
'Copying Dart files to snapshot directory: '
'${snapshotDir.uri.toFilePath()}',
label: test.name);
for (final file in test.filesEditedInGeneration(generation)) {
final fileSnapshotUri = snapshotDir.uri.resolve(file.baseName);
final editUri = file.editForGeneration(generation).fileUri;
File.fromUri(editUri).copySync(fileSnapshotUri.toFilePath());
final relativeSnapshotPath = fe_shared.relativizeUri(
snapshotDir.uri, fileSnapshotUri, fe_shared.isWindows);
final snapshotPathWithScheme =
'$filesystemScheme:///$relativeSnapshotPath';
updatedFilesInCurrentGeneration.add(snapshotPathWithScheme);
}
_print(
'Updated files in generation $generation: '
'$updatedFilesInCurrentGeneration',
label: test.name);
return updatedFilesInCurrentGeneration;
}
/// Compiles all [updatedFiles] in [test] for the given [generation] with the
/// front end server [controller], copies all outputs to [outputDirectory],
/// and returns whether the compilation was successful.
///
/// Reports test failures on compile time errors.
Future<bool> compileGeneration(
HotReloadTest test,
int generation,
Directory outputDirectory,
List<String> updatedFiles,
HotReloadFrontendServerController controller);
/// Runs [test] from compiled and generated assets in [tempDirectory] and
/// returns `true` if it passes.
///
/// All output (standard and errors) from running the test is written to
/// [outputSink].
Future<bool> runTest(
HotReloadTest test, Directory tempDirectory, IOSink outputSink);
/// Reports test results to standard out as well as the output .json file if
/// requested.
Future<void> reportAllResults() async {
if (options.testResultsOutputDir != null) {
// Used to communicate individual test failures to our test bots.
final testOutcomeResults = testOutcomes.map((o) => o.toRecordJson());
final testOutcomeLogs = testOutcomes.map((o) => o.toLogJson());
final testResultsOutputDir = options.testResultsOutputDir!;
_print('Saving test results to ${testResultsOutputDir.toFilePath()}.');
// Test outputs must have one JSON blob per line and be
// newline-terminated.
final testResultsUri = testResultsOutputDir.resolve('results.json');
final testResultsSink = File.fromUri(testResultsUri).openWrite();
testOutcomeResults.forEach(testResultsSink.writeln);
await testResultsSink.flush();
await testResultsSink.close();
final testLogsUri = testResultsOutputDir.resolve('logs.json');
if (Platform.isWindows) {
// TODO(55297): Logs are disabled on windows until this but is fixed.
_print('Logs are not written on Windows. '
'See: https://github.com/dart-lang/sdk/issues/55297');
} else {
final testLogsSink = File.fromUri(testLogsUri).openWrite();
testOutcomeLogs.forEach(testLogsSink.writeln);
await testLogsSink.flush();
await testLogsSink.close();
}
_print('Emitted logs to ${testResultsUri.toFilePath()} '
'and ${testLogsUri.toFilePath()}.');
}
if (testOutcomes.isEmpty) {
print('No tests ran: no sub-directories in ${allTestsUri.toFilePath()} '
'match the provided filter:\n'
'${options.testNameFilter}');
exit(0);
}
// Report failed tests.
var failedTests =
testOutcomes.where((outcome) => !outcome.matchedExpectations);
if (failedTests.isNotEmpty) {
print('Some tests failed:');
failedTests.forEach((outcome) {
print(outcome.testName);
});
// Exit cleanly after writing test results.
exit(0);
}
}
/// Runs the [command] with [args] in [environment].
///
/// Will echo the commands to the console before running them when running in
/// `verbose` mode.
Future<Process> startProcess(String name, String command, List<String> args,
{Map<String, String> environment = const {},
ProcessStartMode mode = ProcessStartMode.normal}) {
if (options.verbose) {
print('Running $name:\n$command ${args.join(' ')}\n');
if (environment.isNotEmpty) {
var environmentVariables =
environment.entries.map((e) => '${e.key}: ${e.value}').join('\n');
print('With environment:\n$environmentVariables\n');
}
}
return Process.start(command, args, mode: mode, environment: environment);
}
/// Prints messages if 'verbose' mode is enabled.
void _print(String message, {String? label}) {
if (options.verbose) {
final labelText = label == null ? '' : '($label)';
print('hot_reload_test$labelText: $message');
}
}
/// Prints messages if 'debug' mode is enabled.
void _debugPrint(String message, {String? label}) {
if (options.debug) {
final labelText = label == null ? '' : '($label)';
print('DEBUG$labelText: $message');
}
}
/// Returns the diff'd output between two files.
///
/// These diffs are appended at the end of updated file generations for better
/// test readability.
///
/// If [commented] is set, the output will be wrapped in multiline comments
/// and the diff separator.
///
/// If [trimHeaders] is set, the leading '+++' and '---' file headers will be
/// removed.
String _diffWithFileUris(Uri file1, Uri file2,
{String label = '', bool commented = true, bool trimHeaders = true}) {
final file1Path = file1.toFilePath();
final file2Path = file2.toFilePath();
final diffArgs = ['diff', '-u', file1Path, file2Path];
_debugPrint("Running diff with 'git diff ${diffArgs.join(' ')}'.",
label: label);
final diffProcess = Process.runSync('git', diffArgs);
final errOutput = diffProcess.stderr as String;
if (errOutput.isNotEmpty) {
throw Exception('git diff failed with:\n$errOutput');
}
var output = diffProcess.stdout as String;
if (trimHeaders) {
// Skip the diff header. 'git diff' has 5 lines in its header.
// TODO(markzipan): Add support for Windows-style line endings.
output = output.split('\n').skip(5).join('\n');
}
return commented ? '$testDiffSeparator\n/*\n$output*/' : output;
}
/// Returns the code and diff portions of [file] with all leading and trailing
/// whitespace trimmed.
(String, String) _splitTestByDiff(Uri file) {
final text = File.fromUri(file).readAsStringSync();
final diffIndex = text.indexOf(testDiffSeparator);
final diffSplitIndex = diffIndex == -1 ? text.length - 1 : diffIndex;
final codeText = text.substring(0, diffSplitIndex).trim();
final diffText = text.substring(diffSplitIndex, text.length - 1).trim();
return (codeText, diffText);
}
}
/// Hot reload test suite runner for DDC specific behavior that is agnostic to
/// the environment where the compiled code is eventually run.
abstract class DdcSuiteRunner extends HotReloadSuiteRunner {
late final String entrypointLibraryExportName =
ddc_names.libraryUriToJsIdentifier(snapshotEntrypointUri);
final Uri dartSdkJSUri =
buildRootUri.resolve('gen/utils/ddc/canary/sdk/ddc/dart_sdk.js');
final Uri ddcModuleLoaderJSUri =
sdkRoot.resolve('pkg/dev_compiler/lib/js/ddc/ddc_module_loader.js');
final String ddcPlatformDillFromSdkRoot = fe_shared.relativizeUri(
sdkRoot, buildRootUri.resolve('ddc_outline.dill'), fe_shared.isWindows);
final String entrypointModuleName = 'hot-reload-test:///main.dart';
DdcSuiteRunner(super.options);
@override
List<String> get platformFrontEndServerArgs => [
'--dartdevc-module-format=ddc',
'--dartdevc-canary',
'--platform=$ddcPlatformDillFromSdkRoot',
'--target=dartdevc',
];
@override
Future<bool> compileGeneration(
HotReloadTest test,
int generation,
Directory outputDirectory,
List<String> updatedFiles,
HotReloadFrontendServerController controller) async {
// The first generation calls `compile`, but subsequent ones call
// `recompile`.
// Likewise, use the incremental output file for `recompile` calls.
// TODO(nshahan): Sending compile/recompile instructions is likely
// the same across backends and should be shared code.
String outputDillPath;
_print('Compiling generation $generation with the Frontend Server.',
label: test.name);
CompilerOutput compilerOutput;
if (generation == 0) {
_debugPrint(
'Compiling snapshot entrypoint: $snapshotEntrypointWithScheme',
label: test.name);
outputDillPath = outputDillUri.toFilePath();
compilerOutput =
await controller.sendCompile(snapshotEntrypointWithScheme);
} else {
_debugPrint(