-
Notifications
You must be signed in to change notification settings - Fork 216
/
Copy pathplatform.dart
269 lines (233 loc) · 10.3 KB
/
platform.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
// Copyright (c) 2016, 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:io';
import 'package:async/async.dart';
import 'package:path/path.dart' as p;
import 'package:test_api/backend.dart' show Compiler, Runtime, SuitePlatform;
import 'package:test_core/src/runner/configuration.dart'; // ignore: implementation_imports
import 'package:test_core/src/runner/load_exception.dart'; // ignore: implementation_imports
import 'package:test_core/src/runner/platform.dart'; // ignore: implementation_imports
import 'package:test_core/src/runner/plugin/customizable_platform.dart'; // ignore: implementation_imports
import 'package:test_core/src/runner/runner_suite.dart'; // ignore: implementation_imports
import 'package:test_core/src/runner/suite.dart'; // ignore: implementation_imports
import 'package:test_core/src/util/package_config.dart'; // ignore: implementation_imports
import 'package:yaml/yaml.dart';
import '../executable_settings.dart';
import 'browser_manager.dart';
import 'compilers/compiler_support.dart';
import 'compilers/dart2js.dart';
import 'compilers/dart2wasm.dart';
import 'compilers/precompiled.dart';
import 'default_settings.dart';
class BrowserPlatform extends PlatformPlugin
implements CustomizablePlatform<ExecutableSettings> {
/// Starts the server.
///
/// [root] is the root directory that the server should serve. It defaults to
/// the working directory.
static Future<BrowserPlatform> start({String? root}) async {
var packageConfig = await currentPackageConfig;
return BrowserPlatform._(
Configuration.current,
p.fromUri(packageConfig.resolve(
Uri.parse('package:test/src/runner/browser/static/favicon.ico'))),
p.fromUri(packageConfig.resolve(Uri.parse(
'package:test/src/runner/browser/static/default.html.tpl'))),
p.fromUri(packageConfig.resolve(Uri.parse(
'package:test/src/runner/browser/static/run_wasm_chrome.js'))),
root: root);
}
/// The test runner configuration.
final Configuration _config;
/// The cached [CompilerSupport] for each compiler.
final _compilerSupport = <Compiler, Future<CompilerSupport>>{};
/// The `package:test` side wrapper for the Dart2Wasm runtime.
final String _jsRuntimeWrapper;
/// The URL for this server and [compiler] combination.
///
/// Each compiler serves its tests under a different randomly-generated
/// secret URI to ensure that other users on the same system can't snoop
/// on data being served through this server, as well as distinguish tests
/// from different compilers from each other.
Future<CompilerSupport> compilerSupport(Compiler compiler) =>
_compilerSupport.putIfAbsent(compiler, () {
if (_config.suiteDefaults.precompiledPath != null) {
return PrecompiledSupport.start(
compiler: compiler,
config: _config,
defaultTemplatePath: _defaultTemplatePath,
root: _config.suiteDefaults.precompiledPath!,
faviconPath: _faviconPath);
}
return switch (compiler) {
Compiler.dart2js => Dart2JsSupport.start(
config: _config,
defaultTemplatePath: _defaultTemplatePath,
root: _root,
faviconPath: _faviconPath),
Compiler.dart2wasm => Dart2WasmSupport.start(
config: _config,
defaultTemplatePath: _defaultTemplatePath,
jsRuntimeWrapper: _jsRuntimeWrapper,
root: _root,
faviconPath: _faviconPath),
_ => throw StateError('Unexpected compiler $compiler'),
};
});
/// The root directory served statically by this server.
final String _root;
/// Whether [close] has been called.
bool get _closed => _closeMemo.hasRun;
/// A map from browser identifiers to futures that will complete to the
/// [BrowserManager]s for those browsers, or `null` if they failed to load.
///
/// This should only be accessed through [_browserManagerFor].
final _browserManagers = <(Runtime, Compiler), Future<BrowserManager?>>{};
/// Settings for invoking each browser.
///
/// This starts out with the default settings, which may be overridden by user settings.
final _browserSettings =
Map<Runtime, ExecutableSettings>.from(defaultSettings);
/// The default template for html tests.
final String _defaultTemplatePath;
final String _faviconPath;
BrowserPlatform._(Configuration config, this._faviconPath,
this._defaultTemplatePath, this._jsRuntimeWrapper,
{String? root})
: _config = config,
_root = root ?? p.current;
@override
ExecutableSettings parsePlatformSettings(YamlMap settings) =>
ExecutableSettings.parse(settings);
@override
ExecutableSettings mergePlatformSettings(
ExecutableSettings settings1, ExecutableSettings settings2) =>
settings1.merge(settings2);
@override
void customizePlatform(Runtime runtime, ExecutableSettings settings) {
var oldSettings =
_browserSettings[runtime] ?? _browserSettings[runtime.root];
if (oldSettings != null) settings = oldSettings.merge(settings);
_browserSettings[runtime] = settings;
}
/// Loads the test suite at [path] on the platform [platform].
///
/// This will start a browser to load the suite if one isn't already running.
/// Throws an [ArgumentError] if `platform.platform` isn't a browser.
@override
Future<RunnerSuite?> load(String path, SuitePlatform platform,
SuiteConfiguration suiteConfig, Map<String, Object?> message) async {
var browser = platform.runtime;
assert(suiteConfig.runtimes.contains(browser.identifier));
if (!browser.isBrowser) {
throw ArgumentError('$browser is not a browser.');
}
var compiler = platform.compiler;
var support = await compilerSupport(compiler);
var htmlPathFromTestPath = '${p.withoutExtension(path)}.html';
if (File(htmlPathFromTestPath).existsSync()) {
if (_config.customHtmlTemplatePath != null &&
p.basename(htmlPathFromTestPath) ==
p.basename(_config.customHtmlTemplatePath!)) {
throw LoadException(
path,
'template file "${p.basename(_config.customHtmlTemplatePath!)}" cannot be named '
'like the test file.');
}
_checkHtmlCorrectness(htmlPathFromTestPath, path);
} else if (_config.customHtmlTemplatePath != null) {
var htmlTemplatePath = _config.customHtmlTemplatePath!;
if (!File(htmlTemplatePath).existsSync()) {
throw LoadException(
path, '"$htmlTemplatePath" does not exist or is not readable');
}
final templateFileContents = File(htmlTemplatePath).readAsStringSync();
if ('{{testScript}}'.allMatches(templateFileContents).length != 1) {
throw LoadException(path,
'"$htmlTemplatePath" must contain exactly one {{testScript}} placeholder');
}
_checkHtmlCorrectness(htmlTemplatePath, path);
}
if (_closed) return null;
await support.compileSuite(path, suiteConfig, platform);
var suiteUrl = support.serverUrl.resolveUri(
p.toUri('${p.withoutExtension(p.relative(path, from: _root))}.html'));
if (_closed) return null;
var browserManager = await _browserManagerFor(browser, compiler);
if (_closed || browserManager == null) return null;
var timeout = const Duration(seconds: 30);
if (suiteConfig.metadata.timeout.apply(timeout) case final suiteTimeout?
when suiteTimeout > timeout) {
timeout = suiteTimeout;
}
var suite = await browserManager.load(
path, suiteUrl, suiteConfig, message, platform.compiler,
mapper: (await compilerSupport(compiler)).stackTraceMapperForPath(path),
timeout: timeout);
if (_closed) return null;
return suite;
}
void _checkHtmlCorrectness(String htmlPath, String path) {
if (!File(htmlPath).readAsStringSync().contains('packages/test/dart.js')) {
throw LoadException(
path,
'"$htmlPath" must contain <script src="packages/test/dart.js">'
'</script>.');
}
}
/// Returns the [BrowserManager] for [runtime], which should be a browser.
///
/// If no browser manager is running yet, starts one.
Future<BrowserManager?> _browserManagerFor(
Runtime browser, Compiler compiler) {
var managerFuture = _browserManagers[(browser, compiler)];
if (managerFuture != null) return managerFuture;
var future = _createBrowserManager(browser, compiler);
// Store null values for browsers that error out so we know not to load them
// again.
_browserManagers[(browser, compiler)] =
future.then<BrowserManager?>((value) => value).onError((_, __) => null);
return future;
}
Future<BrowserManager> _createBrowserManager(
Runtime browser, Compiler compiler) async {
var support = await compilerSupport(compiler);
var (webSocketUrl, socketFuture) = support.webSocket;
var hostUrl = support.serverUrl
.resolve('packages/test/src/runner/browser/static/index.html')
.replace(queryParameters: {
'managerUrl': webSocketUrl.toString(),
'debug': _config.debug.toString()
});
return BrowserManager.start(
browser, hostUrl, socketFuture, _browserSettings[browser]!, _config);
}
/// Close all the browsers that the server currently has open.
///
/// Note that this doesn't close the server itself. Browser tests can still be
/// loaded, they'll just spawn new browsers.
@override
Future<List<void>> closeEphemeral() {
var managers = _browserManagers.values.toList();
_browserManagers.clear();
return Future.wait(managers.map((manager) async {
var result = await manager;
if (result == null) return;
await result.close();
}));
}
/// Closes the server and releases all its resources.
///
/// Returns a [Future] that completes once the server is closed and its
/// resources have been fully released.
@override
Future<void> close() async => _closeMemo.runOnce(() => Future.wait([
for (var browser in _browserManagers.values)
browser.then((b) => b?.close()),
for (var support in _compilerSupport.values)
support.then((s) => s.close()),
]));
final _closeMemo = AsyncMemoizer<void>();
}