flutter test --wasm support (#145347)

* Adds support for `flutter test --wasm`.
  * The test compilation flow is a bit different now, so that it supports compilers other than DDC. Specifically, when we run a set of unit tests, we generate a "switchboard" main function that imports each unit test and runs the main function for a specific one based off of a value set by the JS bootstrapping code. This way, there is one compile step and the same compile output is invoked for each unit test file.
* Also, removes all references to `dart:html` from flutter/flutter.
* Adds CI steps for running the framework unit tests with dart2wasm+skwasm
  * These steps are marked as `bringup: true`, so we don't know what kind of failures they will result in. Any failures they have will not block the tree at all yet while we're still in `bringup: true`. Once this PR is merged, I plan on looking at any failures and either fixing them or disabling them so we can get these CI steps running on presubmit.

This fixes https://github.com/flutter/flutter/issues/126692
This commit is contained in:
Jackson Gardner
2024-03-21 13:08:07 -07:00
committed by GitHub
parent 98d10b6211
commit 31209d04ff
62 changed files with 953 additions and 365 deletions

View File

@@ -12,6 +12,7 @@ import '../build_info.dart';
import '../bundle_builder.dart';
import '../devfs.dart';
import '../device.dart';
import '../features.dart';
import '../globals.dart' as globals;
import '../native_assets.dart';
import '../project.dart';
@@ -23,6 +24,7 @@ import '../test/test_time_recorder.dart';
import '../test/test_wrapper.dart';
import '../test/watcher.dart';
import '../web/compile.dart';
import '../web/web_constants.dart';
/// The name of the directory where Integration Tests are placed.
///
@@ -233,7 +235,14 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
'in seconds (e.g. "60s"), '
'as a multiplier of the default timeout (e.g. "2x"), '
'or as the string "none" to disable the timeout entirely.',
)
..addFlag(
FlutterOptions.kWebWasmFlag,
help: 'Compile to WebAssembly rather than JavaScript.\n$kWasmMoreInfo',
negatable: false,
hide: !featureFlags.isFlutterWebWasmEnabled,
);
addDdsOptions(verboseHelp: verboseHelp);
addServeObservatoryOptions(verboseHelp: verboseHelp);
usesFatalWarningsOption(verboseHelp: verboseHelp);
@@ -256,6 +265,7 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
final Set<Uri> _testFileUris = <Uri>{};
bool get isWeb => stringArg('platform') == 'chrome';
bool get useWasm => boolArg(FlutterOptions.kWebWasmFlag);
@override
Future<Set<DevelopmentArtifact>> get requiredArtifacts async {
@@ -499,6 +509,10 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
watcher = collector;
}
if (!isWeb && useWasm) {
throwToolExit('--wasm is only supported on the web platform');
}
Device? integrationTestDevice;
if (_isIntegrationTest) {
integrationTestDevice = await findTargetDevice();
@@ -577,6 +591,7 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
testAssetDirectory: testAssetDirectory,
flutterProject: flutterProject,
web: isWeb,
useWasm: useWasm,
randomSeed: stringArg('test-randomize-ordering-seed'),
reporter: stringArg('reporter'),
fileReporter: stringArg('file-reporter'),

View File

@@ -37,7 +37,7 @@ import 'flutter_web_goldens.dart';
import 'test_compiler.dart';
import 'test_time_recorder.dart';
shelf.Handler createDirectoryHandler(Directory directory) {
shelf.Handler createDirectoryHandler(Directory directory, { required bool crossOriginIsolated} ) {
final mime.MimeTypeResolver resolver = mime.MimeTypeResolver();
final FileSystem fileSystem = directory.fileSystem;
return (shelf.Request request) async {
@@ -56,10 +56,16 @@ shelf.Handler createDirectoryHandler(Directory directory) {
return shelf.Response.notFound('Not Found');
}
final String? contentType = resolver.lookup(file.path);
final bool needsCrossOriginIsolated = crossOriginIsolated && uriPath.endsWith('.html');
return shelf.Response.ok(
file.openRead(),
headers: <String, String>{
if (contentType != null) 'Content-Type': contentType
if (contentType != null) 'Content-Type': contentType,
if (needsCrossOriginIsolated)
...<String, String>{
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
},
},
);
};
@@ -74,6 +80,7 @@ class FlutterWebPlatform extends PlatformPlugin {
required this.buildInfo,
required this.webMemoryFS,
required FileSystem fileSystem,
required Directory buildDirectory,
required File testDartJs,
required File testHostDartJs,
required ChromiumLauncher chromiumLauncher,
@@ -81,8 +88,10 @@ class FlutterWebPlatform extends PlatformPlugin {
required Artifacts? artifacts,
required ProcessManager processManager,
required this.webRenderer,
required this.useWasm,
TestTimeRecorder? testTimeRecorder,
}) : _fileSystem = fileSystem,
_buildDirectory = buildDirectory,
_testDartJs = testDartJs,
_testHostDartJs = testHostDartJs,
_chromiumLauncher = chromiumLauncher,
@@ -92,6 +101,7 @@ class FlutterWebPlatform extends PlatformPlugin {
.add(_webSocketHandler.handler)
.add(createDirectoryHandler(
fileSystem.directory(fileSystem.path.join(Cache.flutterRoot!, 'packages', 'flutter_tools')),
crossOriginIsolated: webRenderer == WebRendererMode.skwasm,
))
.add(_handleStaticArtifact)
.add(_localCanvasKitHandler)
@@ -99,7 +109,8 @@ class FlutterWebPlatform extends PlatformPlugin {
.add(_wrapperHandler)
.add(_handleTestRequest)
.add(createDirectoryHandler(
fileSystem.directory(fileSystem.path.join(fileSystem.currentDirectory.path, 'test'))
fileSystem.directory(fileSystem.path.join(fileSystem.currentDirectory.path, 'test')),
crossOriginIsolated: webRenderer == WebRendererMode.skwasm,
))
.add(_packageFilesHandler);
_server.mount(cascade.handler);
@@ -116,6 +127,7 @@ class FlutterWebPlatform extends PlatformPlugin {
final WebMemoryFS webMemoryFS;
final BuildInfo buildInfo;
final FileSystem _fileSystem;
final Directory _buildDirectory;
final File _testDartJs;
final File _testHostDartJs;
final ChromiumLauncher _chromiumLauncher;
@@ -127,6 +139,7 @@ class FlutterWebPlatform extends PlatformPlugin {
final AsyncMemoizer<void> _closeMemo = AsyncMemoizer<void>();
final String _root;
final WebRendererMode webRenderer;
final bool useWasm;
/// Allows only one test suite (typically one test file) to be loaded and run
/// at any given point in time. Loading more than one file at a time is known
@@ -149,11 +162,13 @@ class FlutterWebPlatform extends PlatformPlugin {
required BuildInfo buildInfo,
required WebMemoryFS webMemoryFS,
required FileSystem fileSystem,
required Directory buildDirectory,
required Logger logger,
required ChromiumLauncher chromiumLauncher,
required Artifacts? artifacts,
required ProcessManager processManager,
required WebRendererMode webRenderer,
required bool useWasm,
TestTimeRecorder? testTimeRecorder,
Uri? testPackageUri,
Future<shelf.Server> Function() serverFactory = defaultServerFactory,
@@ -196,12 +211,14 @@ class FlutterWebPlatform extends PlatformPlugin {
testDartJs: testDartJs,
testHostDartJs: testHostDartJs,
fileSystem: fileSystem,
buildDirectory: buildDirectory,
chromiumLauncher: chromiumLauncher,
artifacts: artifacts,
logger: logger,
nullAssertions: nullAssertions,
processManager: processManager,
webRenderer: webRenderer,
useWasm: useWasm,
testTimeRecorder: testTimeRecorder,
);
}
@@ -254,6 +271,11 @@ class FlutterWebPlatform extends PlatformPlugin {
'dart_stack_trace_mapper.js',
));
File get _flutterJs => _fileSystem.file(_fileSystem.path.join(
_artifacts!.getHostArtifact(HostArtifact.flutterJsDirectory).path,
'flutter.js',
));
File get _dartSdk {
final Map<WebRendererMode, Map<NullSafetyMode, HostArtifact>> dartSdkArtifactMap = buildInfo.ddcModuleFormat == DdcModuleFormat.ddc ? kDdcDartSdkJsArtifactMap : kAmdDartSdkJsArtifactMap;
return _fileSystem.file(_artifacts!.getHostArtifact(dartSdkArtifactMap[webRenderer]![_nullSafetyMode]!));
@@ -277,21 +299,20 @@ class FlutterWebPlatform extends PlatformPlugin {
}
Future<shelf.Response> _handleTestRequest(shelf.Request request) async {
if (request.url.path.endsWith('.dart.browser_test.dart.js')) {
final String leadingPath = request.url.path.split('.browser_test.dart.js')[0];
final String generatedFile = '${_fileSystem.path.split(leadingPath).join('_')}.bootstrap.js';
return shelf.Response.ok(generateTestBootstrapFileContents('/$generatedFile', 'require.js', 'dart_stack_trace_mapper.js'), headers: <String, String>{
HttpHeaders.contentTypeHeader: 'text/javascript',
});
if (request.url.path.endsWith('main.dart.browser_test.dart.js')) {
return shelf.Response.ok(generateTestBootstrapFileContents(
'/main.dart.bootstrap.js', 'require.js', 'dart_stack_trace_mapper.js'),
headers: <String, String>{
HttpHeaders.contentTypeHeader: 'text/javascript',
}
);
}
if (request.url.path.endsWith('.dart.bootstrap.js')) {
final String leadingPath = request.url.path.split('.dart.bootstrap.js')[0];
final String generatedFile = '${_fileSystem.path.split(leadingPath).join('_')}.dart.test.dart.js';
if (request.url.path.endsWith('main.dart.bootstrap.js')) {
return shelf.Response.ok(generateMainModule(
nullAssertions: nullAssertions!,
nativeNullAssertions: true,
bootstrapModule: '${_fileSystem.path.basename(leadingPath)}.dart.bootstrap',
entrypoint: '/$generatedFile'
bootstrapModule: 'main.dart.bootstrap',
entrypoint: '/main.dart.js'
), headers: <String, String>{
HttpHeaders.contentTypeHeader: 'text/javascript',
});
@@ -349,6 +370,21 @@ class FlutterWebPlatform extends PlatformPlugin {
_testHostDartJs.openRead(),
headers: <String, String>{'Content-Type': 'text/javascript'},
);
} else if (request.requestedUri.path.contains('flutter.js')) {
return shelf.Response.ok(
_flutterJs.openRead(),
headers: <String, String>{'Content-Type': 'text/javascript'},
);
} else if (request.requestedUri.path.contains('main.dart.mjs')) {
return shelf.Response.ok(
_buildDirectory.childFile('main.dart.mjs').openRead(),
headers: <String, String>{'Content-Type': 'text/javascript'},
);
} else if (request.requestedUri.path.contains('main.dart.wasm')) {
return shelf.Response.ok(
_buildDirectory.childFile('main.dart.wasm').openRead(),
headers: <String, String>{'Content-Type': 'application/wasm'},
);
} else {
return shelf.Response.notFound('Not Found');
}
@@ -363,7 +399,10 @@ class FlutterWebPlatform extends PlatformPlugin {
if (fileUri != null) {
final String dirname = _fileSystem.path.dirname(fileUri.toFilePath());
final String basename = _fileSystem.path.basename(fileUri.toFilePath());
final shelf.Handler handler = createDirectoryHandler(_fileSystem.directory(dirname));
final shelf.Handler handler = createDirectoryHandler(
_fileSystem.directory(dirname),
crossOriginIsolated: webRenderer == WebRendererMode.skwasm,
);
final shelf.Request modifiedRequest = shelf.Request(
request.method,
request.requestedUri.replace(path: basename),
@@ -452,36 +491,66 @@ class FlutterWebPlatform extends PlatformPlugin {
return shelf.Response.internalServerError(body: error);
}
final File canvasKitFile = _canvasKitFile(relativePath);
return shelf.Response.ok(
_canvasKitFile(relativePath).openRead(),
canvasKitFile.openRead(),
headers: <String, Object>{
HttpHeaders.contentTypeHeader: contentType,
},
);
}
String _makeBuildConfigString() {
return useWasm ? '''
{
compileTarget: "dart2wasm",
renderer: "${webRenderer.name}",
mainWasmPath: "main.dart.wasm",
jsSupportRuntimePath: "main.dart.mjs",
}
''' : '''
{
compileTarget: "dartdevc",
renderer: "${webRenderer.name}",
mainJsPath: "main.dart.browser_test.dart.js",
}
''';
}
// A handler that serves wrapper files used to bootstrap tests.
shelf.Response _wrapperHandler(shelf.Request request) {
final String path = _fileSystem.path.fromUri(request.url);
if (path.endsWith('.html')) {
final String test = '${_fileSystem.path.withoutExtension(path)}.dart';
final String scriptBase = htmlEscape.convert(_fileSystem.path.basename(test));
final String link = '<link rel="x-dart-test" href="$scriptBase">';
return shelf.Response.ok('''
<!DOCTYPE html>
<html>
<head>
<title>${htmlEscape.convert(test)} Test</title>
<script src="flutter.js"></script>
<script>
window.flutterConfiguration = {
canvasKitBaseUrl: "/canvaskit/"
};
_flutter.buildConfig = {
builds: [
${_makeBuildConfigString()}
]
}
window.testSelector = "$test";
_flutter.loader.load({
config: {
canvasKitBaseUrl: "/canvaskit/",
}
});
</script>
$link
<script src="static/dart.js"></script>
</head>
</html>
''', headers: <String, String>{'Content-Type': 'text/html'});
''', headers: <String, String>{
'Content-Type': 'text/html',
if (webRenderer == WebRendererMode.skwasm)
...<String, String>{
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
}
});
}
return shelf.Response.notFound('Not found.');
}

View File

@@ -52,6 +52,7 @@ abstract class FlutterTestRunner {
String? icudtlPath,
Directory? coverageDirectory,
bool web = false,
bool useWasm = false,
String? randomSeed,
String? reporter,
String? fileReporter,
@@ -117,6 +118,7 @@ class _FlutterTestRunnerImpl implements FlutterTestRunner {
String? icudtlPath,
Directory? coverageDirectory,
bool web = false,
bool useWasm = false,
String? randomSeed,
String? reporter,
String? fileReporter,
@@ -186,6 +188,7 @@ class _FlutterTestRunnerImpl implements FlutterTestRunner {
testFiles: testFiles.map((Uri uri) => uri.toFilePath()).toList(),
buildInfo: debuggingOptions.buildInfo,
webRenderer: debuggingOptions.webRenderer,
useWasm: useWasm,
);
testArgs
..add('--platform=chrome')
@@ -205,6 +208,7 @@ class _FlutterTestRunnerImpl implements FlutterTestRunner {
webMemoryFS: result,
logger: globals.logger,
fileSystem: globals.fs,
buildDirectory: globals.fs.directory(tempBuildDir),
artifacts: globals.artifacts,
processManager: globals.processManager,
chromiumLauncher: ChromiumLauncher(
@@ -217,6 +221,7 @@ class _FlutterTestRunnerImpl implements FlutterTestRunner {
),
testTimeRecorder: testTimeRecorder,
webRenderer: debuggingOptions.webRenderer,
useWasm: useWasm,
);
},
);

View File

@@ -3,6 +3,7 @@
// found in the LICENSE file.
import 'package:package_config/package_config.dart';
import 'package:package_config/package_config_types.dart';
import 'package:process/process.dart';
import '../artifacts.dart';
@@ -11,6 +12,7 @@ import '../base/config.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/platform.dart';
import '../base/process.dart';
import '../build_info.dart';
import '../bundle.dart';
import '../cache.dart';
@@ -44,12 +46,74 @@ class WebTestCompiler {
final ProcessManager _processManager;
final Config _config;
Future<File> _generateTestEntrypoint({
required List<String> testFiles,
required Directory projectDirectory,
required Directory outputDirectory,
required LanguageVersion languageVersion,
}) async {
final List<WebTestInfo> testInfos = testFiles.map((String testFilePath) {
final List<String> relativeTestSegments = _fileSystem.path.split(
_fileSystem.path.relative(
testFilePath,
from: projectDirectory.childDirectory('test').path
)
);
final File? testConfigFile = findTestConfigFile(_fileSystem.file(testFilePath), _logger);
String? testConfigPath;
if (testConfigFile != null) {
testConfigPath = _fileSystem.path.split(
_fileSystem.path.relative(
testConfigFile.path,
from: projectDirectory.childDirectory('test').path
)
).join('/');
}
return (
entryPoint: relativeTestSegments.join('/'),
configFile: testConfigPath,
goldensUri: Uri.file(testFilePath),
);
}).toList();
return _fileSystem.file(_fileSystem.path.join(outputDirectory.path, 'main.dart'))
..createSync(recursive: true)
..writeAsStringSync(generateTestEntrypoint(
testInfos: testInfos,
languageVersion: languageVersion
)
);
}
Future<WebMemoryFS> initialize({
required Directory projectDirectory,
required String testOutputDir,
required List<String> testFiles,
required BuildInfo buildInfo,
required WebRendererMode webRenderer,
required bool useWasm,
}) async {
return useWasm ? _compileWasm(
projectDirectory: projectDirectory,
testOutputDir: testOutputDir,
testFiles: testFiles,
buildInfo: buildInfo,
webRenderer: webRenderer,
) : _compileJS(
projectDirectory: projectDirectory,
testOutputDir: testOutputDir,
testFiles: testFiles,
buildInfo: buildInfo,
webRenderer: webRenderer,
);
}
Future<WebMemoryFS> _compileJS({
required Directory projectDirectory,
required String testOutputDir,
required List<String> testFiles,
required BuildInfo buildInfo,
required WebRendererMode webRenderer,
}) async {
LanguageVersion languageVersion = LanguageVersion(2, 8);
late final String platformDillName;
@@ -78,32 +142,12 @@ class WebTestCompiler {
final Directory outputDirectory = _fileSystem.directory(testOutputDir)
..createSync(recursive: true);
final List<File> generatedFiles = <File>[];
for (final String testFilePath in testFiles) {
final List<String> relativeTestSegments = _fileSystem.path.split(
_fileSystem.path.relative(testFilePath, from: projectDirectory.childDirectory('test').path));
final File generatedFile = _fileSystem.file(
_fileSystem.path.join(outputDirectory.path, '${relativeTestSegments.join('_')}.test.dart'));
generatedFile
..createSync(recursive: true)
..writeAsStringSync(generateTestEntrypoint(
relativeTestPath: relativeTestSegments.join('/'),
absolutePath: testFilePath,
testConfigPath: findTestConfigFile(_fileSystem.file(testFilePath), _logger)?.path,
languageVersion: languageVersion,
));
generatedFiles.add(generatedFile);
}
// Generate a fake main file that imports all tests to be executed. This will force
// each of them to be compiled.
final StringBuffer buffer = StringBuffer('// @dart=${languageVersion.major}.${languageVersion.minor}\n');
for (final File generatedFile in generatedFiles) {
buffer.writeln('import "${_fileSystem.path.basename(generatedFile.path)}";');
}
buffer.writeln('void main() {}');
_fileSystem.file(_fileSystem.path.join(outputDirectory.path, 'main.dart'))
..createSync()
..writeAsStringSync(buffer.toString());
final File testFile = await _generateTestEntrypoint(
testFiles: testFiles,
projectDirectory: projectDirectory,
outputDirectory: outputDirectory,
languageVersion: languageVersion
);
final String cachedKernelPath = getDefaultCachedKernelPath(
trackWidgetCreation: buildInfo.trackWidgetCreation,
@@ -139,7 +183,7 @@ class WebTestCompiler {
);
final CompilerOutput? output = await residentCompiler.recompile(
Uri.parse('org-dartlang-app:///main.dart'),
Uri.parse('org-dartlang-app:///${testFile.basename}'),
<Uri>[],
outputPath: outputDirectory.childFile('out').path,
packageConfig: buildInfo.packageConfig,
@@ -157,7 +201,67 @@ class WebTestCompiler {
final File manifestFile = outputDirectory.childFile('${output.outputFilename}.json');
final File sourcemapFile = outputDirectory.childFile('${output.outputFilename}.map');
final File metadataFile = outputDirectory.childFile('${output.outputFilename}.metadata');
return WebMemoryFS()
..write(codeFile, manifestFile, sourcemapFile, metadataFile);
}
Future<WebMemoryFS> _compileWasm({
required Directory projectDirectory,
required String testOutputDir,
required List<String> testFiles,
required BuildInfo buildInfo,
required WebRendererMode webRenderer,
}) async {
final Directory outputDirectory = _fileSystem.directory(testOutputDir)
..createSync(recursive: true);
final File testFile = await _generateTestEntrypoint(
testFiles: testFiles,
projectDirectory: projectDirectory,
outputDirectory: outputDirectory,
languageVersion: currentLanguageVersion(_fileSystem, Cache.flutterRoot!),
);
final String dartSdkPath = _artifacts.getArtifactPath(Artifact.engineDartSdkPath, platform: TargetPlatform.web_javascript);
final String platformBinariesPath = _artifacts.getHostArtifact(HostArtifact.webPlatformKernelFolder).path;
final String platformFilePath = _fileSystem.path.join(platformBinariesPath, 'dart2wasm_platform.dill');
final List<String> dartDefines = webRenderer.updateDartDefines(buildInfo.dartDefines);
final File outputWasmFile = outputDirectory.childFile('main.dart.wasm');
final List<String> compilationArgs = <String>[
_artifacts.getArtifactPath(Artifact.engineDartBinary, platform: TargetPlatform.web_javascript),
'compile',
'wasm',
'--packages=.dart_tool/package_config.json',
'--extra-compiler-option=--dart-sdk=$dartSdkPath',
'--extra-compiler-option=--platform=$platformFilePath',
'--extra-compiler-option=--multi-root-scheme=org-dartlang-app',
'--extra-compiler-option=--multi-root=${projectDirectory.childDirectory('test').path}',
'--extra-compiler-option=--multi-root=${outputDirectory.path}',
if (webRenderer == WebRendererMode.skwasm) ...<String>[
'--extra-compiler-option=--import-shared-memory',
'--extra-compiler-option=--shared-memory-max-pages=32768',
],
...buildInfo.extraFrontEndOptions,
for (final String dartDefine in dartDefines)
'-D$dartDefine',
'-O1',
'-o',
outputWasmFile.path,
testFile.path, // dartfile
];
final ProcessUtils processUtils = ProcessUtils(
logger: _logger,
processManager: _processManager,
);
await processUtils.run(
throwOnError: true,
compilationArgs,
);
return WebMemoryFS();
}
}

View File

@@ -387,59 +387,70 @@ define("$bootstrapModule", ["$entrypoint", "dart_sdk"], function(app, dart_sdk)
''';
}
/// Generates the bootstrap logic required for a flutter test running in a browser.
typedef WebTestInfo = ({
String entryPoint,
Uri goldensUri,
String? configFile,
});
/// Generates the bootstrap logic required for running a group of unit test
/// files in the browser.
///
/// This hard-codes the device pixel ratio to 3.0 and a 2400 x 1800 window size.
/// This creates one "switchboard" main function that imports all the main
/// functions of the unit test files that need to be run. The javascript code
/// that starts the test sets a `window.testSelector` that specifies which main
/// function to invoke. This allows us to compile all the unit test files as a
/// single web application and invoke that with a different selector for each
/// test.
String generateTestEntrypoint({
required String relativeTestPath,
required String absolutePath,
required String? testConfigPath,
required List<WebTestInfo> testInfos,
required LanguageVersion languageVersion,
}) {
final List<String> importMainStatements = <String>[];
final List<String> importTestConfigStatements = <String>[];
final List<String> webTestPairs = <String>[];
for (int index = 0; index < testInfos.length; index++) {
final WebTestInfo testInfo = testInfos[index];
final String entryPointPath = testInfo.entryPoint;
importMainStatements.add("import 'org-dartlang-app:///${Uri.file(entryPointPath)}' as test_$index show main;");
final String? testConfigPath = testInfo.configFile;
String? testConfigFunction = 'null';
if (testConfigPath != null) {
importTestConfigStatements.add(
"import 'org-dartlang-app:///${Uri.file(testConfigPath)}' as test_config_$index show testExecutable;"
);
testConfigFunction = 'test_config_$index.testExecutable';
}
webTestPairs.add('''
'$entryPointPath': (
entryPoint: test_$index.main,
entryPointRunner: $testConfigFunction,
goldensUri: Uri.parse('${testInfo.goldensUri}'),
),
''');
}
return '''
// @dart = ${languageVersion.major}.${languageVersion.minor}
import 'org-dartlang-app:///$relativeTestPath' as test;
import 'dart:ui' as ui;
import 'dart:ui_web' as ui_web;
import 'dart:html';
import 'dart:js';
${testConfigPath != null ? "import '${Uri.file(testConfigPath)}' as test_config;" : ""}
import 'package:stream_channel/stream_channel.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:test_api/backend.dart';
// @dart = ${languageVersion.major}.${languageVersion.minor}
Future<void> main() async {
ui_web.debugEmulateFlutterTesterEnvironment = true;
await ui_web.bootstrapEngine();
webGoldenComparator = DefaultWebGoldenComparator(Uri.parse('${Uri.file(absolutePath)}'));
ui_web.debugOverrideDevicePixelRatio(3.0);
ui.window.debugPhysicalSizeOverride = const ui.Size(2400, 1800);
${importMainStatements.join('\n')}
internalBootstrapBrowserTest(() {
return ${testConfigPath != null ? "() => test_config.testExecutable(test.main)" : "test.main"};
});
}
void internalBootstrapBrowserTest(Function getMain()) {
var channel = serializeSuite(getMain, hidePrints: false);
postMessageChannel().pipe(channel);
}
StreamChannel serializeSuite(Function getMain(), {bool hidePrints = true}) => RemoteListener.start(getMain, hidePrints: hidePrints);
StreamChannel postMessageChannel() {
var controller = StreamChannelController<Object?>(sync: true);
var channel = MessageChannel();
window.parent!.postMessage('port', window.location.origin, [channel.port2]);
var portSubscription = channel.port1.onMessage.listen((message) {
controller.local.sink.add(message.data);
});
controller.local.stream
.listen(channel.port1.postMessage, onDone: portSubscription.cancel);
return controller.foreign;
${importTestConfigStatements.join('\n')}
import 'package:flutter_test/flutter_test.dart';
Map<String, WebTest> webTestMap = <String, WebTest>{
${webTestPairs.join('\n')}
};
Future<void> main() {
final WebTest? webTest = webTestMap[testSelector];
if (webTest == null) {
throw Exception('Web test for \${testSelector} not found');
}
return runWebTest(webTest);
}
''';
}