Implement Webdriver-based Safari test harness (flutter/engine#33757)
* WebDriver stuff. * Some refactoring and WebDriver improvements. * Add license comments. * TODO needs to have two slashes, not three. * Remove dependency on OS/Xcode * Revert "Remove dependency on OS/Xcode" This reverts commit 1d02dc7857f31b845a9e4f1ee4e9f1f6e4269111. * Disable golden tests for macOS Safari that were disabled for iOS Safari. * Don't run tests that didn't run on ios Safari on Desktop Safari. * Newline at end of file. * Fixes as per Mouad's comments. * Changes as per Yegor's comments. * Fix analyzer issue.
This commit is contained in:
@@ -3,18 +3,16 @@
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:image/image.dart';
|
||||
import 'package:pedantic/pedantic.dart';
|
||||
import 'package:stack_trace/stack_trace.dart';
|
||||
import 'package:test_api/src/backend/runtime.dart';
|
||||
import 'package:typed_data/typed_buffers.dart';
|
||||
|
||||
/// Provides the environment for a specific web browser.
|
||||
abstract class BrowserEnvironment {
|
||||
/// Name of the browser. Used in logging commands.
|
||||
String get name;
|
||||
|
||||
/// The [Runtime] used by `package:test` to identify this browser type.
|
||||
Runtime get packageTestRuntime;
|
||||
|
||||
@@ -33,6 +31,9 @@ abstract class BrowserEnvironment {
|
||||
/// browser instances.
|
||||
Future<void> prepare();
|
||||
|
||||
/// Perform any necessary teardown steps
|
||||
Future<void> cleanup();
|
||||
|
||||
/// Launches a browser instance.
|
||||
///
|
||||
/// The browser will be directed to open the provided [url].
|
||||
@@ -41,12 +42,7 @@ abstract class BrowserEnvironment {
|
||||
/// browser in debug mode by pausing test execution after the code is loaded
|
||||
/// but before calling the `main()` function of the test, giving the
|
||||
/// developer a chance to set breakpoints.
|
||||
Browser launchBrowserInstance(Uri url, {bool debug = false});
|
||||
|
||||
/// Returns the screenshot manager used by this browser.
|
||||
///
|
||||
/// If the browser does not support screenshots, returns null.
|
||||
ScreenshotManager? getScreenshotManager();
|
||||
Future<Browser> launchBrowserInstance(Uri url, {bool debug = false});
|
||||
}
|
||||
|
||||
/// An interface for running browser instances.
|
||||
@@ -58,8 +54,6 @@ abstract class BrowserEnvironment {
|
||||
/// Any errors starting or running the browser process are reported through
|
||||
/// [onExit].
|
||||
abstract class Browser {
|
||||
String get name;
|
||||
|
||||
/// The Observatory URL for this browser.
|
||||
///
|
||||
/// Returns `null` for browsers that aren't running the Dart VM, or
|
||||
@@ -72,131 +66,25 @@ abstract class Browser {
|
||||
/// or if the remote debugging URL can't be found.
|
||||
Future<Uri>? get remoteDebuggerUrl => null;
|
||||
|
||||
/// The underlying process.
|
||||
///
|
||||
/// This will fire once the process has started successfully.
|
||||
Future<Process> get _process => _processCompleter.future;
|
||||
final Completer<Process> _processCompleter = Completer<Process>();
|
||||
|
||||
/// Whether [close] has been called.
|
||||
bool _closed = false;
|
||||
|
||||
/// A future that completes when the browser exits.
|
||||
///
|
||||
/// If there's a problem starting or running the browser, this will complete
|
||||
/// with an error.
|
||||
Future<void> get onExit => _onExitCompleter.future;
|
||||
final Completer<void> _onExitCompleter = Completer<void>();
|
||||
Future<void> get onExit;
|
||||
|
||||
/// Standard IO streams for the underlying browser process.
|
||||
final List<StreamSubscription<void>> _ioSubscriptions = <StreamSubscription<void>>[];
|
||||
|
||||
/// Creates a new browser.
|
||||
///
|
||||
/// This is intended to be called by subclasses. They pass in [startBrowser],
|
||||
/// which asynchronously returns the browser process. Any errors in
|
||||
/// [startBrowser] (even those raised asynchronously after it returns) are
|
||||
/// piped to [onExit] and will cause the browser to be killed.
|
||||
Browser(Future<Process> Function() startBrowser) {
|
||||
// Don't return a Future here because there's no need for the caller to wait
|
||||
// for the process to actually start. They should just wait for the HTTP
|
||||
// request instead.
|
||||
runZonedGuarded(() async {
|
||||
final Process process = await startBrowser();
|
||||
_processCompleter.complete(process);
|
||||
|
||||
final Uint8Buffer output = Uint8Buffer();
|
||||
void drainOutput(Stream<List<int>> stream) {
|
||||
try {
|
||||
_ioSubscriptions
|
||||
.add(stream.listen(output.addAll, cancelOnError: true));
|
||||
} on StateError catch (_) {}
|
||||
}
|
||||
|
||||
// If we don't drain the stdout and stderr the process can hang.
|
||||
drainOutput(process.stdout);
|
||||
drainOutput(process.stderr);
|
||||
|
||||
final int exitCode = await process.exitCode;
|
||||
|
||||
// This hack dodges an otherwise intractable race condition. When the user
|
||||
// presses Control-C, the signal is sent to the browser and the test
|
||||
// runner at the same time. It's possible for the browser to exit before
|
||||
// the [Browser.close] is called, which would trigger the error below.
|
||||
//
|
||||
// A negative exit code signals that the process exited due to a signal.
|
||||
// However, it's possible that this signal didn't come from the user's
|
||||
// Control-C, in which case we do want to throw the error. The only way to
|
||||
// resolve the ambiguity is to wait a brief amount of time and see if this
|
||||
// browser is actually closed.
|
||||
if (!_closed && exitCode < 0) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
}
|
||||
|
||||
if (!_closed && exitCode != 0) {
|
||||
final String outputString = utf8.decode(output);
|
||||
String message = '$name failed with exit code $exitCode.';
|
||||
if (outputString.isNotEmpty) {
|
||||
message += '\nStandard output:\n$outputString';
|
||||
}
|
||||
|
||||
throw Exception(message);
|
||||
}
|
||||
|
||||
_onExitCompleter.complete();
|
||||
}, (dynamic error, StackTrace? stackTrace) {
|
||||
// Ignore any errors after the browser has been closed.
|
||||
if (_closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Make sure the process dies even if the error wasn't fatal.
|
||||
_process.then((Process process) => process.kill());
|
||||
|
||||
stackTrace ??= Trace.current();
|
||||
|
||||
if (_onExitCompleter.isCompleted) {
|
||||
return;
|
||||
}
|
||||
_onExitCompleter.completeError(
|
||||
Exception('Failed to run $name: $error.'),
|
||||
stackTrace,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Kills the browser process.
|
||||
/// Closes the browser
|
||||
///
|
||||
/// Returns the same [Future] as [onExit], except that it won't emit
|
||||
/// exceptions.
|
||||
Future<void> close() async {
|
||||
_closed = true;
|
||||
Future<void> close();
|
||||
|
||||
// If we don't manually close the stream the test runner can hang.
|
||||
// For example this happens with Chrome Headless.
|
||||
// See SDK issue: https://github.com/dart-lang/sdk/issues/31264
|
||||
for (final StreamSubscription<void> stream in _ioSubscriptions) {
|
||||
unawaited(stream.cancel());
|
||||
}
|
||||
/// Returns whether this browser supports taking screenshots
|
||||
bool get supportsScreenshots => false;
|
||||
|
||||
(await _process).kill();
|
||||
|
||||
// Swallow exceptions. The user should explicitly use [onExit] for these.
|
||||
return onExit.catchError((dynamic _) {});
|
||||
}
|
||||
}
|
||||
|
||||
/// Interface for capturing screenshots from a browser.
|
||||
abstract class ScreenshotManager {
|
||||
/// Capture a screenshot.
|
||||
///
|
||||
/// This will throw if the browser doesn't support screenshotting.
|
||||
/// Please read the details for the implementing classes.
|
||||
Future<Image> capture(math.Rectangle<num> region);
|
||||
|
||||
/// Suffix to be added to the end of the filename.
|
||||
///
|
||||
/// Example file names:
|
||||
/// - Chrome, no-suffix: backdrop_filter_clip_moved.actual.png
|
||||
/// - iOS Safari: backdrop_filter_clip_moved.iOS_Safari.actual.png
|
||||
String get filenameSuffix;
|
||||
Future<Image> captureScreenshot(math.Rectangle<num> region) =>
|
||||
throw Exception('This browser does not support screenshots');
|
||||
}
|
||||
|
||||
125
engine/src/flutter/lib/web_ui/dev/browser_process.dart
Normal file
125
engine/src/flutter/lib/web_ui/dev/browser_process.dart
Normal file
@@ -0,0 +1,125 @@
|
||||
// Copyright 2013 The Flutter Authors. 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:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:stack_trace/stack_trace.dart';
|
||||
import 'package:typed_data/typed_buffers.dart';
|
||||
|
||||
class BrowserProcess {
|
||||
/// The underlying process.
|
||||
///
|
||||
/// This will fire once the process has started successfully.
|
||||
Future<Process> get _process => _processCompleter.future;
|
||||
final Completer<Process> _processCompleter = Completer<Process>();
|
||||
|
||||
/// Whether [close] has been called.
|
||||
bool _closed = false;
|
||||
|
||||
/// A future that completes when the browser exits.
|
||||
///
|
||||
/// If there's a problem starting or running the browser, this will complete
|
||||
/// with an error.
|
||||
Future<void> get onExit => _onExitCompleter.future;
|
||||
final Completer<void> _onExitCompleter = Completer<void>();
|
||||
|
||||
/// Standard IO streams for the underlying browser process.
|
||||
final List<StreamSubscription<void>> _ioSubscriptions = <StreamSubscription<void>>[];
|
||||
|
||||
/// Creates a new browser.
|
||||
///
|
||||
/// Clients pass in [startBrowser], which asynchronously returns the browser
|
||||
/// process. Any errors in [startBrowser] (even those raised asynchronously
|
||||
/// after it returns) are piped to [onExit] and will cause the browser to be
|
||||
/// killed.
|
||||
BrowserProcess(Future<Process> Function() startBrowser) {
|
||||
// Don't return a Future here because there's no need for the caller to wait
|
||||
// for the process to actually start. They should just wait for the HTTP
|
||||
// request instead.
|
||||
runZonedGuarded(() async {
|
||||
final Process process = await startBrowser();
|
||||
_processCompleter.complete(process);
|
||||
|
||||
final Uint8Buffer output = Uint8Buffer();
|
||||
void drainOutput(Stream<List<int>> stream) {
|
||||
try {
|
||||
_ioSubscriptions
|
||||
.add(stream.listen(output.addAll, cancelOnError: true));
|
||||
} on StateError catch (_) {}
|
||||
}
|
||||
|
||||
// If we don't drain the stdout and stderr the process can hang.
|
||||
drainOutput(process.stdout);
|
||||
drainOutput(process.stderr);
|
||||
|
||||
final int exitCode = await process.exitCode;
|
||||
|
||||
// This hack dodges an otherwise intractable race condition. When the user
|
||||
// presses Control-C, the signal is sent to the browser and the test
|
||||
// runner at the same time. It's possible for the browser to exit before
|
||||
// the [Browser.close] is called, which would trigger the error below.
|
||||
//
|
||||
// A negative exit code signals that the process exited due to a signal.
|
||||
// However, it's possible that this signal didn't come from the user's
|
||||
// Control-C, in which case we do want to throw the error. The only way to
|
||||
// resolve the ambiguity is to wait a brief amount of time and see if this
|
||||
// browser is actually closed.
|
||||
if (!_closed && exitCode < 0) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
}
|
||||
|
||||
if (!_closed && exitCode != 0) {
|
||||
final String outputString = utf8.decode(output);
|
||||
String message = 'Browser process failed with exit code $exitCode.';
|
||||
if (outputString.isNotEmpty) {
|
||||
message += '\nStandard output:\n$outputString';
|
||||
}
|
||||
|
||||
throw Exception(message);
|
||||
}
|
||||
|
||||
_onExitCompleter.complete();
|
||||
}, (dynamic error, StackTrace? stackTrace) {
|
||||
// Ignore any errors after the browser has been closed.
|
||||
if (_closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Make sure the process dies even if the error wasn't fatal.
|
||||
_process.then((Process process) => process.kill());
|
||||
|
||||
stackTrace ??= Trace.current();
|
||||
|
||||
if (_onExitCompleter.isCompleted) {
|
||||
return;
|
||||
}
|
||||
_onExitCompleter.completeError(
|
||||
Exception('Failed to run browser process: $error.'),
|
||||
stackTrace,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Kills the browser process.
|
||||
///
|
||||
/// Returns the same [Future] as [onExit], except that it won't emit
|
||||
/// exceptions.
|
||||
Future<void> close() async {
|
||||
_closed = true;
|
||||
|
||||
// If we don't manually close the stream the test runner can hang.
|
||||
// For example this happens with Chrome Headless.
|
||||
// See SDK issue: https://github.com/dart-lang/sdk/issues/31264
|
||||
for (final StreamSubscription<void> stream in _ioSubscriptions) {
|
||||
unawaited(stream.cancel());
|
||||
}
|
||||
|
||||
(await _process).kill();
|
||||
|
||||
// Swallow exceptions. The user should explicitly use [onExit] for these.
|
||||
return onExit.catchError((dynamic _) {});
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'
|
||||
|
||||
import 'browser.dart';
|
||||
import 'browser_lock.dart';
|
||||
import 'browser_process.dart';
|
||||
import 'chrome_installer.dart';
|
||||
import 'common.dart';
|
||||
import 'environment.dart';
|
||||
@@ -24,7 +25,7 @@ class ChromeEnvironment implements BrowserEnvironment {
|
||||
late final BrowserInstallation _installation;
|
||||
|
||||
@override
|
||||
Browser launchBrowserInstance(Uri url, {bool debug = false}) {
|
||||
Future<Browser> launchBrowserInstance(Uri url, {bool debug = false}) async {
|
||||
return Chrome(url, _installation, debug: debug);
|
||||
}
|
||||
|
||||
@@ -41,17 +42,13 @@ class ChromeEnvironment implements BrowserEnvironment {
|
||||
}
|
||||
|
||||
@override
|
||||
ScreenshotManager? getScreenshotManager() {
|
||||
// Always compare screenshots when running tests locally. On CI only compare
|
||||
// on Linux.
|
||||
if (Platform.isLinux || !isLuci) {
|
||||
return ChromeScreenshotManager();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
Future<void> cleanup() async {}
|
||||
|
||||
@override
|
||||
String get packageTestConfigurationYamlFile => 'dart_test_chrome.yaml';
|
||||
|
||||
@override
|
||||
final String name = 'Chrome';
|
||||
}
|
||||
|
||||
/// Runs desktop Chrome.
|
||||
@@ -62,8 +59,7 @@ class ChromeEnvironment implements BrowserEnvironment {
|
||||
///
|
||||
/// Any errors starting or running the process are reported through [onExit].
|
||||
class Chrome extends Browser {
|
||||
@override
|
||||
final String name = 'Chrome';
|
||||
final BrowserProcess _process;
|
||||
|
||||
@override
|
||||
final Future<Uri> remoteDebuggerUrl;
|
||||
@@ -72,7 +68,7 @@ class Chrome extends Browser {
|
||||
/// [Uri] or a [String].
|
||||
factory Chrome(Uri url, BrowserInstallation installation, {bool debug = false}) {
|
||||
final Completer<Uri> remoteDebuggerCompleter = Completer<Uri>.sync();
|
||||
return Chrome._(() async {
|
||||
return Chrome._(BrowserProcess(() async {
|
||||
// A good source of various Chrome CLI options:
|
||||
// https://peter.sh/experiments/chromium-command-line-switches/
|
||||
//
|
||||
@@ -122,11 +118,79 @@ class Chrome extends Browser {
|
||||
.then((_) => Directory(dir).deleteSync(recursive: true)));
|
||||
|
||||
return process;
|
||||
}, remoteDebuggerCompleter.future);
|
||||
}), remoteDebuggerCompleter.future);
|
||||
}
|
||||
|
||||
Chrome._(this._process, this.remoteDebuggerUrl);
|
||||
|
||||
@override
|
||||
Future<void> get onExit => _process.onExit;
|
||||
|
||||
@override
|
||||
Future<void> close() => _process.close();
|
||||
|
||||
// Always compare screenshots when running tests locally. On CI only compare
|
||||
// on Linux.
|
||||
@override
|
||||
bool get supportsScreenshots => Platform.isLinux || !isLuci;
|
||||
|
||||
/// Capture a screenshot of the web content.
|
||||
///
|
||||
/// Uses Webkit Inspection Protocol server's `captureScreenshot` API.
|
||||
///
|
||||
/// [region] is used to decide which part of the web content will be used in
|
||||
/// test image. It includes starting coordinate x,y as well as height and
|
||||
/// width of the area to capture.
|
||||
///
|
||||
/// This method can be used for both macOS and Linux.
|
||||
// TODO(yjbanov): extends tests to Window, https://github.com/flutter/flutter/issues/65673
|
||||
@override
|
||||
Future<Image> captureScreenshot(math.Rectangle<num>? region) async {
|
||||
final wip.ChromeConnection chromeConnection =
|
||||
wip.ChromeConnection('localhost', kDevtoolsPort);
|
||||
final wip.ChromeTab? chromeTab = await chromeConnection.getTab(
|
||||
(wip.ChromeTab chromeTab) => chromeTab.url.contains('localhost'));
|
||||
if (chromeTab == null) {
|
||||
throw StateError(
|
||||
'Failed locate Chrome tab with the test page',
|
||||
);
|
||||
}
|
||||
final wip.WipConnection wipConnection = await chromeTab.connect();
|
||||
|
||||
Map<String, dynamic>? captureScreenshotParameters;
|
||||
if (region != null) {
|
||||
captureScreenshotParameters = <String, dynamic>{
|
||||
'format': 'png',
|
||||
'clip': <String, dynamic>{
|
||||
'x': region.left,
|
||||
'y': region.top,
|
||||
'width': region.width,
|
||||
'height': region.height,
|
||||
'scale':
|
||||
// This is NOT the DPI of the page, instead it's the "zoom level".
|
||||
1,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Setting hardware-independent screen parameters:
|
||||
// https://chromedevtools.github.io/devtools-protocol/tot/Emulation
|
||||
await wipConnection
|
||||
.sendCommand('Emulation.setDeviceMetricsOverride', <String, dynamic>{
|
||||
'width': kMaxScreenshotWidth,
|
||||
'height': kMaxScreenshotHeight,
|
||||
'deviceScaleFactor': 1,
|
||||
'mobile': false,
|
||||
});
|
||||
final wip.WipResponse response = await wipConnection.sendCommand(
|
||||
'Page.captureScreenshot', captureScreenshotParameters);
|
||||
|
||||
final Image screenshot =
|
||||
decodePng(base64.decode(response.result!['data'] as String))!;
|
||||
|
||||
return screenshot;
|
||||
}
|
||||
|
||||
Chrome._(Future<Process> Function() startBrowser, this.remoteDebuggerUrl)
|
||||
: super(startBrowser);
|
||||
}
|
||||
|
||||
/// Used by [Chrome] to detect a glibc bug and retry launching the
|
||||
@@ -223,66 +287,3 @@ Future<Uri> getRemoteDebuggerUrl(Uri base) async {
|
||||
return base;
|
||||
}
|
||||
}
|
||||
|
||||
/// [ScreenshotManager] implementation for Chrome.
|
||||
///
|
||||
/// This manager can be used for both macOS and Linux.
|
||||
// TODO(yjbanov): extends tests to Window, https://github.com/flutter/flutter/issues/65673
|
||||
class ChromeScreenshotManager extends ScreenshotManager {
|
||||
@override
|
||||
String get filenameSuffix => '';
|
||||
|
||||
/// Capture a screenshot of the web content.
|
||||
///
|
||||
/// Uses Webkit Inspection Protocol server's `captureScreenshot` API.
|
||||
///
|
||||
/// [region] is used to decide which part of the web content will be used in
|
||||
/// test image. It includes starting coordinate x,y as well as height and
|
||||
/// width of the area to capture.
|
||||
@override
|
||||
Future<Image> capture(math.Rectangle<num>? region) async {
|
||||
final wip.ChromeConnection chromeConnection =
|
||||
wip.ChromeConnection('localhost', kDevtoolsPort);
|
||||
final wip.ChromeTab? chromeTab = await chromeConnection.getTab(
|
||||
(wip.ChromeTab chromeTab) => chromeTab.url.contains('localhost'));
|
||||
if (chromeTab == null) {
|
||||
throw StateError(
|
||||
'Failed locate Chrome tab with the test page',
|
||||
);
|
||||
}
|
||||
final wip.WipConnection wipConnection = await chromeTab.connect();
|
||||
|
||||
Map<String, dynamic>? captureScreenshotParameters;
|
||||
if (region != null) {
|
||||
captureScreenshotParameters = <String, dynamic>{
|
||||
'format': 'png',
|
||||
'clip': <String, dynamic>{
|
||||
'x': region.left,
|
||||
'y': region.top,
|
||||
'width': region.width,
|
||||
'height': region.height,
|
||||
'scale':
|
||||
// This is NOT the DPI of the page, instead it's the "zoom level".
|
||||
1,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Setting hardware-independent screen parameters:
|
||||
// https://chromedevtools.github.io/devtools-protocol/tot/Emulation
|
||||
await wipConnection
|
||||
.sendCommand('Emulation.setDeviceMetricsOverride', <String, dynamic>{
|
||||
'width': kMaxScreenshotWidth,
|
||||
'height': kMaxScreenshotHeight,
|
||||
'deviceScaleFactor': 1,
|
||||
'mobile': false,
|
||||
});
|
||||
final wip.WipResponse response = await wipConnection.sendCommand(
|
||||
'Page.captureScreenshot', captureScreenshotParameters);
|
||||
|
||||
final Image screenshot =
|
||||
decodePng(base64.decode(response.result!['data'] as String))!;
|
||||
|
||||
return screenshot;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,13 +9,17 @@ import 'package:test_api/src/backend/runtime.dart';
|
||||
|
||||
import 'browser.dart';
|
||||
import 'browser_lock.dart';
|
||||
import 'browser_process.dart';
|
||||
import 'common.dart';
|
||||
import 'edge_installation.dart';
|
||||
|
||||
/// Provides an environment for the desktop Microsoft Edge (Chromium-based).
|
||||
class EdgeEnvironment implements BrowserEnvironment {
|
||||
@override
|
||||
Browser launchBrowserInstance(Uri url, {bool debug = false}) {
|
||||
final String name = 'Edge';
|
||||
|
||||
@override
|
||||
Future<Browser> launchBrowserInstance(Uri url, {bool debug = false}) async {
|
||||
return Edge(url);
|
||||
}
|
||||
|
||||
@@ -28,7 +32,7 @@ class EdgeEnvironment implements BrowserEnvironment {
|
||||
}
|
||||
|
||||
@override
|
||||
ScreenshotManager? getScreenshotManager() => null;
|
||||
Future<void> cleanup() async {}
|
||||
|
||||
@override
|
||||
String get packageTestConfigurationYamlFile => 'dart_test_edge.yaml';
|
||||
@@ -42,13 +46,12 @@ class EdgeEnvironment implements BrowserEnvironment {
|
||||
///
|
||||
/// Any errors starting or running the process are reported through [onExit].
|
||||
class Edge extends Browser {
|
||||
@override
|
||||
final String name = 'Edge';
|
||||
final BrowserProcess _process;
|
||||
|
||||
/// Starts a new instance of Safari open to the given [url], which may be a
|
||||
/// [Uri] or a [String].
|
||||
factory Edge(Uri url) {
|
||||
return Edge._(() async {
|
||||
return Edge._(BrowserProcess(() async {
|
||||
final BrowserInstallation installation = await getEdgeInstallation(
|
||||
browserLock.edgeLock.launcherVersion,
|
||||
infoLog: DevNull(),
|
||||
@@ -67,8 +70,14 @@ class Edge extends Browser {
|
||||
);
|
||||
|
||||
return process;
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
Edge._(Future<Process> Function() startBrowser) : super(startBrowser);
|
||||
Edge._(this._process);
|
||||
|
||||
@override
|
||||
Future<void> get onExit => _process.onExit;
|
||||
|
||||
@override
|
||||
Future<void> close() => _process.close();
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import 'package:test_core/src/util/io.dart';
|
||||
|
||||
import 'browser.dart';
|
||||
import 'browser_lock.dart';
|
||||
import 'browser_process.dart';
|
||||
import 'common.dart';
|
||||
import 'environment.dart';
|
||||
import 'firefox_installer.dart';
|
||||
@@ -21,7 +22,7 @@ class FirefoxEnvironment implements BrowserEnvironment {
|
||||
late final BrowserInstallation _installation;
|
||||
|
||||
@override
|
||||
Browser launchBrowserInstance(Uri url, {bool debug = false}) {
|
||||
Future<Browser> launchBrowserInstance(Uri url, {bool debug = false}) async {
|
||||
return Firefox(url, this, debug: debug);
|
||||
}
|
||||
|
||||
@@ -37,10 +38,13 @@ class FirefoxEnvironment implements BrowserEnvironment {
|
||||
}
|
||||
|
||||
@override
|
||||
String get packageTestConfigurationYamlFile => 'dart_test_firefox.yaml';
|
||||
Future<void> cleanup() async {}
|
||||
|
||||
@override
|
||||
ScreenshotManager? getScreenshotManager() => null;
|
||||
final String name = 'Firefox';
|
||||
|
||||
@override
|
||||
String get packageTestConfigurationYamlFile => 'dart_test_firefox.yaml';
|
||||
}
|
||||
|
||||
/// Runs desktop Firefox.
|
||||
@@ -51,8 +55,7 @@ class FirefoxEnvironment implements BrowserEnvironment {
|
||||
///
|
||||
/// Any errors starting or running the process are reported through [onExit].
|
||||
class Firefox extends Browser {
|
||||
@override
|
||||
final String name = 'Firefox';
|
||||
final BrowserProcess _process;
|
||||
|
||||
@override
|
||||
final Future<Uri> remoteDebuggerUrl;
|
||||
@@ -62,7 +65,7 @@ class Firefox extends Browser {
|
||||
factory Firefox(Uri url, FirefoxEnvironment firefoxEnvironment, {bool debug = false}) {
|
||||
final BrowserInstallation installation = firefoxEnvironment._installation;
|
||||
final Completer<Uri> remoteDebuggerCompleter = Completer<Uri>.sync();
|
||||
return Firefox._(() async {
|
||||
return Firefox._(BrowserProcess(() async {
|
||||
// Using a profile on opening will prevent popups related to profiles.
|
||||
const String _profile = '''
|
||||
user_pref("browser.shell.checkDefaultBrowser", false);
|
||||
@@ -109,9 +112,14 @@ user_pref("dom.max_script_run_time", 0);
|
||||
}));
|
||||
|
||||
return process;
|
||||
}, remoteDebuggerCompleter.future);
|
||||
}), remoteDebuggerCompleter.future);
|
||||
}
|
||||
|
||||
Firefox._(Future<Process> Function() startBrowser, this.remoteDebuggerUrl)
|
||||
: super(startBrowser);
|
||||
Firefox._(this._process, this.remoteDebuggerUrl);
|
||||
|
||||
@override
|
||||
Future<void> get onExit => _process.onExit;
|
||||
|
||||
@override
|
||||
Future<void> close() => _process.close();
|
||||
}
|
||||
|
||||
@@ -9,19 +9,37 @@ import 'dart:math' as math;
|
||||
import 'package:image/image.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:test_api/src/backend/runtime.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import 'browser.dart';
|
||||
import 'browser_lock.dart';
|
||||
import 'browser_process.dart';
|
||||
import 'environment.dart';
|
||||
import 'safari_installation.dart';
|
||||
import 'utils.dart';
|
||||
|
||||
/// Info about the screen layout for the current version of iOS Safari.
|
||||
///
|
||||
/// This is used to properly take screenshots of the browser.
|
||||
class SafariScreenInfo {
|
||||
final int heightOfHeader;
|
||||
final int heightOfFooter;
|
||||
final double scaleFactor;
|
||||
|
||||
SafariScreenInfo(this.heightOfHeader, this.heightOfFooter, this.scaleFactor);
|
||||
}
|
||||
|
||||
/// Provides an environment for the mobile variant of Safari running in an iOS
|
||||
/// simulator.
|
||||
class SafariIosEnvironment implements BrowserEnvironment {
|
||||
late final SafariScreenInfo _screenInfo;
|
||||
|
||||
@override
|
||||
Browser launchBrowserInstance(Uri url, {bool debug = false}) {
|
||||
return SafariIos(url);
|
||||
final String name = 'Safari iOS';
|
||||
|
||||
@override
|
||||
Future<Browser> launchBrowserInstance(Uri url, {bool debug = false}) async {
|
||||
return SafariIos(url, _screenInfo);
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -29,13 +47,24 @@ class SafariIosEnvironment implements BrowserEnvironment {
|
||||
|
||||
@override
|
||||
Future<void> prepare() async {
|
||||
final SafariIosLock lock = browserLock.safariIosLock;
|
||||
_screenInfo = SafariScreenInfo(
|
||||
lock.heightOfHeader, lock.heightOfFooter, lock.scaleFactor);
|
||||
|
||||
/// Create the directory to use for taking screenshots, if it does not
|
||||
/// exists.
|
||||
if (!environment.webUiSimulatorScreenshotsDirectory.existsSync()) {
|
||||
environment.webUiSimulatorScreenshotsDirectory.createSync();
|
||||
}
|
||||
// Temporary directories are deleted in the clenaup phase of after `felt`
|
||||
// runs the tests.
|
||||
temporaryDirectories.add(environment.webUiSimulatorScreenshotsDirectory);
|
||||
|
||||
await initIosSimulator();
|
||||
}
|
||||
|
||||
@override
|
||||
ScreenshotManager? getScreenshotManager() {
|
||||
return SafariIosScreenshotManager();
|
||||
}
|
||||
Future<void> cleanup() async {}
|
||||
|
||||
@override
|
||||
String get packageTestConfigurationYamlFile => 'dart_test_safari.yaml';
|
||||
@@ -49,13 +78,13 @@ class SafariIosEnvironment implements BrowserEnvironment {
|
||||
///
|
||||
/// Any errors starting or running the process are reported through [onExit].
|
||||
class SafariIos extends Browser {
|
||||
@override
|
||||
final String name = 'Safari iOS';
|
||||
final BrowserProcess _process;
|
||||
final SafariScreenInfo _screenInfo;
|
||||
|
||||
/// Starts a new instance of Safari open to the given [url], which may be a
|
||||
/// [Uri].
|
||||
factory SafariIos(Uri url) {
|
||||
return SafariIos._(() async {
|
||||
factory SafariIos(Uri url, SafariScreenInfo screenInfo) {
|
||||
return SafariIos._(BrowserProcess(() async {
|
||||
// iOS-Safari
|
||||
// Uses `xcrun simctl`. It is a command line utility to control the
|
||||
// Simulator. For more details on interacting with the simulator:
|
||||
@@ -68,57 +97,21 @@ class SafariIos extends Browser {
|
||||
]);
|
||||
|
||||
return process;
|
||||
});
|
||||
}), screenInfo);
|
||||
}
|
||||
|
||||
SafariIos._(Future<io.Process> Function() startBrowser) : super(startBrowser);
|
||||
}
|
||||
SafariIos._(this._process, this._screenInfo);
|
||||
|
||||
/// [ScreenshotManager] implementation for Safari.
|
||||
///
|
||||
/// This manager will only be created/used for macOS.
|
||||
class SafariIosScreenshotManager extends ScreenshotManager {
|
||||
@override
|
||||
String get filenameSuffix => '.iOS_Safari';
|
||||
Future<void> get onExit => _process.onExit;
|
||||
|
||||
SafariIosScreenshotManager() {
|
||||
final SafariIosLock lock = browserLock.safariIosLock;
|
||||
_heightOfHeader = lock.heightOfHeader;
|
||||
_heightOfFooter = lock.heightOfFooter;
|
||||
_scaleFactor = lock.scaleFactor;
|
||||
@override
|
||||
Future<void> close() => _process.close();
|
||||
|
||||
/// Create the directory to use for taking screenshots, if it does not
|
||||
/// exists.
|
||||
if (!environment.webUiSimulatorScreenshotsDirectory.existsSync()) {
|
||||
environment.webUiSimulatorScreenshotsDirectory.createSync();
|
||||
}
|
||||
// Temporary directories are deleted in the clenaup phase of after `felt`
|
||||
// runs the tests.
|
||||
temporaryDirectories.add(environment.webUiSimulatorScreenshotsDirectory);
|
||||
}
|
||||
@override
|
||||
bool get supportsScreenshots => true;
|
||||
|
||||
/// This scale factor is used to enlarge/shrink the screenshot region
|
||||
/// sent from the tests.
|
||||
/// For more details see [_scaleScreenshotRegion(region)].
|
||||
late final double _scaleFactor;
|
||||
|
||||
/// Height of the part to crop from the top of the image.
|
||||
///
|
||||
/// `xcrun simctl` command takes the screenshot of the entire simulator. We
|
||||
/// are cropping top bit from screenshot, otherwise due to the clock on top of
|
||||
/// the screen, the screenshot will differ between each run.
|
||||
/// Note that this gap can change per phone and per iOS version. For more
|
||||
/// details refer to `browser_lock.yaml` file.
|
||||
late final int _heightOfHeader;
|
||||
|
||||
/// Height of the part to crop from the bottom of the image.
|
||||
///
|
||||
/// This area is the footer navigation bar of the phone, it is not the area
|
||||
/// used by tests (which is inside the browser).
|
||||
late final int _heightOfFooter;
|
||||
|
||||
/// Used as a suffix for the temporary file names used for screenshots.
|
||||
int _fileNameCounter = 0;
|
||||
@override
|
||||
|
||||
/// Capture a screenshot of entire simulator.
|
||||
///
|
||||
@@ -155,20 +148,21 @@ class SafariIosScreenshotManager extends ScreenshotManager {
|
||||
///
|
||||
/// Uses simulator tool `xcrun simctl`'s 'screenshot' command.
|
||||
@override
|
||||
Future<Image> capture(math.Rectangle<num>? region) async {
|
||||
final String filename = 'screenshot$_fileNameCounter.png';
|
||||
_fileNameCounter++;
|
||||
Future<Image> captureScreenshot(math.Rectangle<num>? region) async {
|
||||
final String screenshotTag = const Uuid().v4();
|
||||
|
||||
final String filename = 'screenshot$screenshotTag.png';
|
||||
|
||||
await iosSimulator.takeScreenshot(
|
||||
filename, environment.webUiSimulatorScreenshotsDirectory,
|
||||
filename,
|
||||
environment.webUiSimulatorScreenshotsDirectory,
|
||||
);
|
||||
|
||||
final io.File file = io.File(path.join(
|
||||
environment.webUiSimulatorScreenshotsDirectory.path, filename));
|
||||
List<int> imageBytes;
|
||||
if (!file.existsSync()) {
|
||||
throw Exception('Failed to read the screenshot '
|
||||
'screenshot$_fileNameCounter.png.');
|
||||
throw Exception('Failed to read the screenshot $filename.');
|
||||
}
|
||||
imageBytes = await file.readAsBytes();
|
||||
file.deleteSync();
|
||||
@@ -180,9 +174,11 @@ class SafariIosScreenshotManager extends ScreenshotManager {
|
||||
final Image content = copyCrop(
|
||||
screenshot,
|
||||
0,
|
||||
_heightOfHeader,
|
||||
_screenInfo.heightOfHeader,
|
||||
screenshot.width,
|
||||
screenshot.height - _heightOfFooter - _heightOfHeader,
|
||||
screenshot.height -
|
||||
_screenInfo.heightOfFooter -
|
||||
_screenInfo.heightOfHeader,
|
||||
);
|
||||
|
||||
if (region == null) {
|
||||
@@ -204,10 +200,10 @@ class SafariIosScreenshotManager extends ScreenshotManager {
|
||||
/// This uniform/isotropic scaling is done using [_scaleFactor].
|
||||
math.Rectangle<num> _scaleScreenshotRegion(math.Rectangle<num> region) {
|
||||
return math.Rectangle<num>(
|
||||
region.left * _scaleFactor,
|
||||
region.top * _scaleFactor,
|
||||
region.width * _scaleFactor,
|
||||
region.height * _scaleFactor,
|
||||
region.left * _screenInfo.scaleFactor,
|
||||
region.top * _screenInfo.scaleFactor,
|
||||
region.width * _screenInfo.scaleFactor,
|
||||
region.height * _screenInfo.scaleFactor,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,91 +3,26 @@
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert' show json;
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path/path.dart' as pathlib;
|
||||
import 'package:test_api/src/backend/runtime.dart';
|
||||
|
||||
import 'browser.dart';
|
||||
import 'utils.dart';
|
||||
import 'webdriver_browser.dart';
|
||||
|
||||
/// Provides an environment for the desktop variant of Safari running on macOS.
|
||||
class SafariMacOsEnvironment implements BrowserEnvironment {
|
||||
class SafariMacOsEnvironment extends WebDriverBrowserEnvironment {
|
||||
@override
|
||||
Browser launchBrowserInstance(Uri url, {bool debug = false}) {
|
||||
return SafariMacOs(url);
|
||||
}
|
||||
final String name = 'Safari macOS';
|
||||
|
||||
@override
|
||||
Runtime get packageTestRuntime => Runtime.safari;
|
||||
|
||||
@override
|
||||
Future<void> prepare() async {
|
||||
// Nothing extra to prepare for desktop Safari.
|
||||
}
|
||||
|
||||
// We do not yet support screenshots on desktop Safari.
|
||||
@override
|
||||
ScreenshotManager? getScreenshotManager() => null;
|
||||
|
||||
@override
|
||||
String get packageTestConfigurationYamlFile => 'dart_test_safari.yaml';
|
||||
}
|
||||
|
||||
/// Runs an instance of Safari for macOS (i.e. desktop Safari).
|
||||
///
|
||||
/// Most of the communication with the browser is expected to happen via HTTP,
|
||||
/// so this exposes a bare-bones API. The browser starts as soon as the class is
|
||||
/// constructed, and is killed when [close] is called.
|
||||
///
|
||||
/// Any errors starting or running the process are reported through [onExit].
|
||||
class SafariMacOs extends Browser {
|
||||
@override
|
||||
final String name = 'Safari macOS';
|
||||
Uri get driverUri => Uri(scheme: 'http', host: 'localhost', port: portNumber);
|
||||
|
||||
/// Starts a new instance of Safari open to the given [url].
|
||||
factory SafariMacOs(Uri url) {
|
||||
return SafariMacOs._(() async {
|
||||
// This hack to programmatically launch a test in Safari is borrowed from
|
||||
// Karma: https://github.com/karma-runner/karma-safari-launcher/issues/29
|
||||
//
|
||||
// The issue is that opening an HTML file directly causes Safari to pop up
|
||||
// a UI prompt to confirm the opening of a file. However, files under
|
||||
// Library/Containers/com.apple.Safari/Data are exempt from this pop up.
|
||||
// We create a "trampoline" file in this directory. The trampoline
|
||||
// redirects the browser to the test URL in a <script>.
|
||||
final String homePath = Platform.environment['HOME']!;
|
||||
final Directory safariDataDirectory = Directory(pathlib.join(
|
||||
homePath,
|
||||
'Library/Containers/com.apple.Safari/Data',
|
||||
));
|
||||
final Directory trampolineDirectory = await safariDataDirectory.createTemp('web-engine-test-trampoline-');
|
||||
|
||||
// Clean up trampoline files/directories before exiting felt.
|
||||
cleanupCallbacks.add(() async {
|
||||
if (trampolineDirectory.existsSync()) {
|
||||
await trampolineDirectory.delete(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
final File trampoline = File(
|
||||
pathlib.join(trampolineDirectory.path, 'trampoline.html'),
|
||||
);
|
||||
await trampoline.writeAsString('''
|
||||
<script>
|
||||
location = ${json.encode(url.toString())};
|
||||
</script>
|
||||
''');
|
||||
|
||||
final Process process = await Process.start(
|
||||
'/Applications/Safari.app/Contents/MacOS/Safari',
|
||||
<String>[trampoline.path],
|
||||
);
|
||||
|
||||
return process;
|
||||
});
|
||||
}
|
||||
|
||||
SafariMacOs._(Future<Process> Function() startBrowser) : super(startBrowser);
|
||||
@override
|
||||
Future<Process> spawnDriverProcess() => Process.start('safaridriver', <String>['-p', portNumber.toString()]);
|
||||
}
|
||||
|
||||
@@ -78,6 +78,8 @@ class RunTestsStep implements PipelineStep {
|
||||
overridePathToCanvasKit: overridePathToCanvasKit,
|
||||
);
|
||||
|
||||
await _browserEnvironment.cleanup();
|
||||
|
||||
if (io.exitCode != 0) {
|
||||
throw ToolExit('Some tests failed');
|
||||
}
|
||||
|
||||
@@ -55,7 +55,8 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
required SkiaGoldClient? skiaClient,
|
||||
required String? overridePathToCanvasKit,
|
||||
}) async {
|
||||
final shelf_io.IOServer server = shelf_io.IOServer(await HttpMultiServer.loopback(0));
|
||||
final shelf_io.IOServer server =
|
||||
shelf_io.IOServer(await HttpMultiServer.loopback(0));
|
||||
return BrowserPlatform._(
|
||||
browserEnvironment: browserEnvironment,
|
||||
server: server,
|
||||
@@ -88,11 +89,6 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
/// WebSocket,
|
||||
final OneOffHandler _webSocketHandler = OneOffHandler();
|
||||
|
||||
/// Handles taking screenshots during tests.
|
||||
///
|
||||
/// Implementation will differ depending on the browser.
|
||||
final ScreenshotManager? _screenshotManager;
|
||||
|
||||
/// Whether [close] has been called.
|
||||
bool get _closed => _closeMemo.hasRun;
|
||||
|
||||
@@ -117,7 +113,7 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
required this.packageConfig,
|
||||
required this.skiaClient,
|
||||
required this.overridePathToCanvasKit,
|
||||
}) : _screenshotManager = browserEnvironment.getScreenshotManager() {
|
||||
}) {
|
||||
// The cascade of request handlers.
|
||||
final shelf.Cascade cascade = shelf.Cascade()
|
||||
// The web socket that carries the test channels for running tests and
|
||||
@@ -132,12 +128,10 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
// * Requests for Dart sources from source maps
|
||||
// * Assets that are part of the engine sources, such as Ahem.ttf
|
||||
.add(_packageUrlHandler)
|
||||
|
||||
.add(_canvasKitOverrideHandler)
|
||||
|
||||
// Serves files from the web_ui/build/ directory at the root (/) URL path.
|
||||
.add(buildDirectoryHandler)
|
||||
|
||||
.add(_testImageListingHandler)
|
||||
|
||||
// Serves the initial HTML for the test.
|
||||
@@ -156,7 +150,7 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
// Serves absolute package URLs (i.e. not /packages/* but /Users/user/*/hosted/pub.dartlang.org/*).
|
||||
// This handler goes last, after all more specific handlers failed to handle the request.
|
||||
.add(_createAbsolutePackageUrlHandler())
|
||||
.add(_screeshotHandler)
|
||||
.add(_screenshotHandler)
|
||||
.add(_fileNotFoundCatcher);
|
||||
|
||||
server.mount(cascade.handler);
|
||||
@@ -164,7 +158,8 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
|
||||
/// If a path to a custom local build of CanvasKit was specified, serve from
|
||||
/// there instead of serving the default CanvasKit in the build/ directory.
|
||||
Future<shelf.Response> _canvasKitOverrideHandler(shelf.Request request) async {
|
||||
Future<shelf.Response> _canvasKitOverrideHandler(
|
||||
shelf.Request request) async {
|
||||
final String? pathOverride = overridePathToCanvasKit;
|
||||
|
||||
if (pathOverride == null || !request.url.path.startsWith('canvaskit/')) {
|
||||
@@ -184,7 +179,8 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
final String? contentType = contentTypes[extension];
|
||||
|
||||
if (contentType == null) {
|
||||
final String error = 'Failed to determine Content-Type for "${request.url.path}".';
|
||||
final String error =
|
||||
'Failed to determine Content-Type for "${request.url.path}".';
|
||||
stderr.writeln(error);
|
||||
return shelf.Response.internalServerError(body: error);
|
||||
}
|
||||
@@ -218,11 +214,13 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
));
|
||||
|
||||
final List<String> testImageFiles = testImageDirectory
|
||||
.listSync(recursive: true)
|
||||
.whereType<File>()
|
||||
.map<String>((File file) => p.relative(file.path, from: testImageDirectory.path))
|
||||
.where((String path) => supportedImageTypes.containsKey(p.extension(path)))
|
||||
.toList();
|
||||
.listSync(recursive: true)
|
||||
.whereType<File>()
|
||||
.map<String>(
|
||||
(File file) => p.relative(file.path, from: testImageDirectory.path))
|
||||
.where(
|
||||
(String path) => supportedImageTypes.containsKey(p.extension(path)))
|
||||
.toList();
|
||||
|
||||
return shelf.Response.ok(
|
||||
json.encode(testImageFiles),
|
||||
@@ -278,7 +276,8 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
//
|
||||
// C:\Users\user\AppData => Users\user\AppData
|
||||
// /home/user/path.dart => home/user/path.dart
|
||||
final String rootRelativePath = p.relative(configPath, from: p.rootPrefix(configPath));
|
||||
final String rootRelativePath =
|
||||
p.relative(configPath, from: p.rootPrefix(configPath));
|
||||
urlToPackage[p.toUri(rootRelativePath).path] = package;
|
||||
}
|
||||
return (shelf.Request request) async {
|
||||
@@ -286,9 +285,9 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
// The cast is needed because keys are non-null String, so there's no way
|
||||
// to return null for a mismatch.
|
||||
final String? packagePath = urlToPackage.keys.cast<String?>().firstWhere(
|
||||
(String? packageUrl) => requestedPath.startsWith(packageUrl!),
|
||||
orElse: () => null,
|
||||
);
|
||||
(String? packageUrl) => requestedPath.startsWith(packageUrl!),
|
||||
orElse: () => null,
|
||||
);
|
||||
if (packagePath == null) {
|
||||
return shelf.Response.notFound('Not a pub.dartlang.org request');
|
||||
}
|
||||
@@ -311,7 +310,7 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
};
|
||||
}
|
||||
|
||||
Future<shelf.Response> _screeshotHandler(shelf.Request request) async {
|
||||
Future<shelf.Response> _screenshotHandler(shelf.Request request) async {
|
||||
if (!request.requestedUri.path.endsWith('/screenshot')) {
|
||||
return shelf.Response.notFound(
|
||||
'This request is not handled by the screenshot handler');
|
||||
@@ -322,7 +321,7 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
json.decode(payload) as Map<String, dynamic>;
|
||||
final String filename = requestData['filename'] as String;
|
||||
|
||||
if (_screenshotManager == null) {
|
||||
if (!(await browserManager).supportsScreenshots) {
|
||||
print(
|
||||
'INFO: Skipping screenshot check for $filename. Current browser/OS '
|
||||
'combination does not support screenshots.',
|
||||
@@ -338,7 +337,8 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
final Map<String, dynamic> region =
|
||||
requestData['region'] as Map<String, dynamic>;
|
||||
final PixelComparison pixelComparison = PixelComparison.values.firstWhere(
|
||||
(PixelComparison value) => value.toString() == requestData['pixelComparison']);
|
||||
(PixelComparison value) =>
|
||||
value.toString() == requestData['pixelComparison']);
|
||||
final bool isCanvaskitTest = requestData['isCanvaskitTest'] as bool;
|
||||
final String result = await _diffScreenshot(
|
||||
filename, write, maxDiffRate, region, pixelComparison, isCanvaskitTest);
|
||||
@@ -365,7 +365,8 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
);
|
||||
|
||||
// Take screenshot.
|
||||
final Image screenshot = await _screenshotManager!.capture(regionAsRectange);
|
||||
final Image screenshot =
|
||||
await (await browserManager).captureScreenshot(regionAsRectange);
|
||||
|
||||
return compareImage(
|
||||
screenshot,
|
||||
@@ -416,7 +417,8 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
final String? contentType = contentTypes[extension];
|
||||
|
||||
if (contentType == null) {
|
||||
final String error = 'Failed to determine Content-Type for "${request.url.path}".';
|
||||
final String error =
|
||||
'Failed to determine Content-Type for "${request.url.path}".';
|
||||
stderr.writeln(error);
|
||||
return shelf.Response.internalServerError(body: error);
|
||||
}
|
||||
@@ -486,17 +488,20 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
}
|
||||
_checkNotClosed();
|
||||
|
||||
final Uri suiteUrl = url.resolveUri(
|
||||
p.toUri(p.withoutExtension(p.relative(path, from: env.environment.webUiBuildDir.path)) + '.html'));
|
||||
final Uri suiteUrl = url.resolveUri(p.toUri(p.withoutExtension(
|
||||
p.relative(path, from: env.environment.webUiBuildDir.path)) +
|
||||
'.html'));
|
||||
_checkNotClosed();
|
||||
|
||||
final BrowserManager? browserManager = await _startBrowserManager();
|
||||
if (browserManager == null) {
|
||||
throw StateError('Failed to initialize browser manager for ${browser.name}');
|
||||
throw StateError(
|
||||
'Failed to initialize browser manager for ${browserEnvironment.name}');
|
||||
}
|
||||
_checkNotClosed();
|
||||
|
||||
final RunnerSuite suite = await browserManager.load(path, suiteUrl, suiteConfig, message);
|
||||
final RunnerSuite suite =
|
||||
await browserManager.load(path, suiteUrl, suiteConfig, message);
|
||||
_checkNotClosed();
|
||||
return suite;
|
||||
}
|
||||
@@ -506,6 +511,7 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
throw UnimplementedError();
|
||||
|
||||
Future<BrowserManager?>? _browserManager;
|
||||
Future<BrowserManager> get browserManager async => (await _browserManager!)!;
|
||||
|
||||
/// Starts a browser manager for the browser provided by [browserEnvironment];
|
||||
///
|
||||
@@ -515,15 +521,16 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
return _browserManager!;
|
||||
}
|
||||
|
||||
final Completer<WebSocketChannel> completer = Completer<WebSocketChannel>.sync();
|
||||
final String path = _webSocketHandler.create(webSocketHandler(completer.complete));
|
||||
final Completer<WebSocketChannel> completer =
|
||||
Completer<WebSocketChannel>.sync();
|
||||
final String path =
|
||||
_webSocketHandler.create(webSocketHandler(completer.complete));
|
||||
final Uri webSocketUrl = url.replace(scheme: 'ws').resolve(path);
|
||||
final Uri hostUrl = url
|
||||
.resolve('host/index.html')
|
||||
.replace(queryParameters: <String, dynamic>{
|
||||
'managerUrl': webSocketUrl.toString(),
|
||||
'debug': isDebug.toString()
|
||||
});
|
||||
final Uri hostUrl = url.resolve('host/index.html').replace(
|
||||
queryParameters: <String, dynamic>{
|
||||
'managerUrl': webSocketUrl.toString(),
|
||||
'debug': isDebug.toString()
|
||||
});
|
||||
|
||||
final Future<BrowserManager?> future = BrowserManager.start(
|
||||
browserEnvironment: browserEnvironment,
|
||||
@@ -661,7 +668,8 @@ class BrowserManager {
|
||||
CancelableCompleter<void>? _pauseCompleter;
|
||||
|
||||
/// The controller for [_BrowserEnvironment.onRestart].
|
||||
final StreamController<dynamic> _onRestartController = StreamController<dynamic>.broadcast();
|
||||
final StreamController<dynamic> _onRestartController =
|
||||
StreamController<dynamic>.broadcast();
|
||||
|
||||
/// The environment to attach to each suite.
|
||||
late final Future<_BrowserEnvironment> _environment;
|
||||
@@ -695,9 +703,26 @@ class BrowserManager {
|
||||
required Future<WebSocketChannel> future,
|
||||
required PackageConfig packageConfig,
|
||||
bool debug = false,
|
||||
}) {
|
||||
final Browser browser = _newBrowser(url, browserEnvironment, debug: debug);
|
||||
}) async {
|
||||
final Browser browser =
|
||||
await _newBrowser(url, browserEnvironment, debug: debug);
|
||||
return _startBrowserManager(
|
||||
browserEnvironment: browserEnvironment,
|
||||
url: url,
|
||||
future: future,
|
||||
packageConfig: packageConfig,
|
||||
browser: browser,
|
||||
debug: debug);
|
||||
}
|
||||
|
||||
static Future<BrowserManager?> _startBrowserManager({
|
||||
required BrowserEnvironment browserEnvironment,
|
||||
required Uri url,
|
||||
required Future<WebSocketChannel> future,
|
||||
required PackageConfig packageConfig,
|
||||
required Browser browser,
|
||||
bool debug = false,
|
||||
}) {
|
||||
final Completer<BrowserManager> completer = Completer<BrowserManager>();
|
||||
|
||||
// For the cases where we use a delegator such as `adb` (for Android) or
|
||||
@@ -716,7 +741,8 @@ class BrowserManager {
|
||||
if (completer.isCompleted) {
|
||||
return;
|
||||
}
|
||||
completer.complete(BrowserManager._(packageConfig, browser, browserEnvironment, webSocket));
|
||||
completer.complete(BrowserManager._(
|
||||
packageConfig, browser, browserEnvironment, webSocket));
|
||||
}).catchError((Object error, StackTrace stackTrace) {
|
||||
browser.close();
|
||||
if (completer.isCompleted) {
|
||||
@@ -731,13 +757,16 @@ class BrowserManager {
|
||||
/// Starts the browser and requests that it load the test page at [url].
|
||||
///
|
||||
/// If [debug] is true, starts the browser in debug mode.
|
||||
static Browser _newBrowser(Uri url, BrowserEnvironment browserEnvironment, {bool debug = false}) {
|
||||
static Future<Browser> _newBrowser(
|
||||
Uri url, BrowserEnvironment browserEnvironment,
|
||||
{bool debug = false}) {
|
||||
return browserEnvironment.launchBrowserInstance(url, debug: debug);
|
||||
}
|
||||
|
||||
/// Creates a new BrowserManager that communicates with the browser over
|
||||
/// [webSocket].
|
||||
BrowserManager._(this.packageConfig, this._browser, this._browserEnvironment, WebSocketChannel webSocket) {
|
||||
BrowserManager._(this.packageConfig, this._browser, this._browserEnvironment,
|
||||
WebSocketChannel webSocket) {
|
||||
// The duration should be short enough that the debugging console is open as
|
||||
// soon as the user is done setting breakpoints, but long enough that a test
|
||||
// doing a lot of synchronous work doesn't trigger a false positive.
|
||||
@@ -753,8 +782,10 @@ class BrowserManager {
|
||||
|
||||
// Whenever we get a message, no matter which child channel it's for, we the
|
||||
// know browser is still running code which means the user isn't debugging.
|
||||
_channel = MultiChannel<dynamic>(
|
||||
webSocket.cast<String>().transform(jsonDocument).changeStream((Stream<Object?> stream) {
|
||||
_channel = MultiChannel<dynamic>(webSocket
|
||||
.cast<String>()
|
||||
.transform(jsonDocument)
|
||||
.changeStream((Stream<Object?> stream) {
|
||||
return stream.map((Object? message) {
|
||||
if (!_closed) {
|
||||
_timer.reset();
|
||||
@@ -768,8 +799,9 @@ class BrowserManager {
|
||||
}));
|
||||
|
||||
_environment = _loadBrowserEnvironment();
|
||||
_channel.stream
|
||||
.listen((dynamic message) => _onMessage(message as Map<dynamic, dynamic>), onDone: close);
|
||||
_channel.stream.listen(
|
||||
(dynamic message) => _onMessage(message as Map<dynamic, dynamic>),
|
||||
onDone: close);
|
||||
}
|
||||
|
||||
/// Loads [_BrowserEnvironment].
|
||||
@@ -798,7 +830,8 @@ class BrowserManager {
|
||||
return;
|
||||
}
|
||||
_controllers.remove(controller);
|
||||
_channel.sink.add(<String, dynamic>{'command': 'closeSuite', 'id': suiteID});
|
||||
_channel.sink
|
||||
.add(<String, dynamic>{'command': 'closeSuite', 'id': suiteID});
|
||||
}
|
||||
|
||||
// The virtual channel will be closed when the suite is closed, in which
|
||||
@@ -806,7 +839,8 @@ class BrowserManager {
|
||||
final VirtualChannel<dynamic> virtualChannel = _channel.virtualChannel();
|
||||
final int suiteChannelID = virtualChannel.id;
|
||||
final StreamChannel<dynamic> suiteChannel = virtualChannel.transformStream(
|
||||
StreamTransformer<dynamic, dynamic>.fromHandlers(handleDone: (EventSink<dynamic> sink) {
|
||||
StreamTransformer<dynamic, dynamic>.fromHandlers(
|
||||
handleDone: (EventSink<dynamic> sink) {
|
||||
closeIframe();
|
||||
sink.close();
|
||||
}));
|
||||
@@ -820,8 +854,13 @@ class BrowserManager {
|
||||
});
|
||||
|
||||
try {
|
||||
controller = deserializeSuite(path, currentPlatform(_browserEnvironment.packageTestRuntime),
|
||||
suiteConfig, await _environment, suiteChannel, message);
|
||||
controller = deserializeSuite(
|
||||
path,
|
||||
currentPlatform(_browserEnvironment.packageTestRuntime),
|
||||
suiteConfig,
|
||||
await _environment,
|
||||
suiteChannel,
|
||||
message);
|
||||
|
||||
final String sourceMapFileName =
|
||||
'${p.basename(path)}.browser_test.dart.js.map';
|
||||
@@ -894,6 +933,11 @@ class BrowserManager {
|
||||
}
|
||||
}
|
||||
|
||||
bool get supportsScreenshots => _browser.supportsScreenshots;
|
||||
|
||||
Future<Image> captureScreenshot(Rectangle<num> region) =>
|
||||
_browser.captureScreenshot(region);
|
||||
|
||||
/// Closes the manager and releases any resources it owns, including closing
|
||||
/// the browser.
|
||||
Future<void> close() => _closeMemoizer.runOnce(() {
|
||||
|
||||
110
engine/src/flutter/lib/web_ui/dev/webdriver_browser.dart
Normal file
110
engine/src/flutter/lib/web_ui/dev/webdriver_browser.dart
Normal file
@@ -0,0 +1,110 @@
|
||||
// Copyright 2013 The Flutter Authors. 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:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:image/image.dart';
|
||||
import 'package:webdriver/io.dart' show createDriver, WebDriver;
|
||||
|
||||
import 'browser.dart';
|
||||
|
||||
abstract class WebDriverBrowserEnvironment extends BrowserEnvironment {
|
||||
late final int portNumber;
|
||||
late final Process _driverProcess;
|
||||
|
||||
Future<Process> spawnDriverProcess();
|
||||
Uri get driverUri;
|
||||
|
||||
/// Finds and returns an unused port on the test host in the local port range.
|
||||
Future<int> _pickUnusedPort() async {
|
||||
// Use bind to allocate an unused port, then unbind from that port to
|
||||
// make it available for use.
|
||||
final ServerSocket socket = await ServerSocket.bind('localhost', 0);
|
||||
final int port = socket.port;
|
||||
await socket.close();
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
Future<void> prepare() async {
|
||||
portNumber = await _pickUnusedPort();
|
||||
|
||||
_driverProcess = await spawnDriverProcess();
|
||||
|
||||
_driverProcess.stderr
|
||||
.transform(utf8.decoder)
|
||||
.transform(const LineSplitter())
|
||||
.listen((String error) {
|
||||
print('[Webdriver][Error] $error');
|
||||
});
|
||||
|
||||
_driverProcess.stdout
|
||||
.transform(utf8.decoder)
|
||||
.transform(const LineSplitter())
|
||||
.listen((String log) {
|
||||
print('[Webdriver] $log');
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> cleanup() async {
|
||||
_driverProcess.kill();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Browser> launchBrowserInstance(Uri url, {bool debug = false}) async {
|
||||
while (true) {
|
||||
try {
|
||||
final WebDriver driver = await createDriver(
|
||||
uri: driverUri, desired: <String, dynamic>{'browserName': packageTestRuntime.identifier});
|
||||
return WebDriverBrowser(driver, url);
|
||||
} on SocketException {
|
||||
// Sometimes we may try to connect before the web driver port is ready.
|
||||
// So we should retry here. Note that if there was some issue with the
|
||||
// webdriver process, we may loop infinitely here, so we're relying on
|
||||
// the test timeout to kill us if it takes too long to connect.
|
||||
print('Failed to connect to webdriver process. Retrying in 100 ms');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
} catch (exception) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class WebDriverBrowser extends Browser {
|
||||
final WebDriver _driver;
|
||||
final Uri _url;
|
||||
final Completer<void> _onExitCompleter = Completer<void>();
|
||||
|
||||
WebDriverBrowser(this._driver, this._url) {
|
||||
_driver.get(_url);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() async {
|
||||
await (await _driver.window).close();
|
||||
if (!_onExitCompleter.isCompleted) {
|
||||
_onExitCompleter.complete();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> get onExit => _onExitCompleter.future;
|
||||
|
||||
@override
|
||||
bool get supportsScreenshots => true;
|
||||
|
||||
@override
|
||||
Future<Image> captureScreenshot(Rectangle<num> region) async {
|
||||
final Image image = decodePng(await _driver.captureScreenshotAsList())!;
|
||||
return copyCrop(image, region.left.round(), region.top.round(),
|
||||
region.width.round(), region.height.round());
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,10 @@ dev_dependencies:
|
||||
path: 1.8.0
|
||||
quiver: 3.0.0
|
||||
test: 1.17.7
|
||||
uuid: 3.0.6
|
||||
yaml: 3.0.0
|
||||
watcher: 1.0.0
|
||||
webdriver: 3.0.0
|
||||
web_test_utils:
|
||||
path: ../../web_sdk/web_test_utils
|
||||
web_engine_tester:
|
||||
|
||||
@@ -56,5 +56,5 @@ void testMain() {
|
||||
});
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520
|
||||
}, skip: isIosSafari || isFirefox);
|
||||
}, skip: isSafari || isFirefox);
|
||||
}
|
||||
|
||||
@@ -816,7 +816,7 @@ void testMain() {
|
||||
});
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520
|
||||
}, skip: isIosSafari || isFirefox);
|
||||
}, skip: isSafari || isFirefox);
|
||||
}
|
||||
|
||||
Future<void> testSampleText(String language, String text,
|
||||
|
||||
@@ -138,5 +138,5 @@ void testMain() {
|
||||
});
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520
|
||||
}, skip: isIosSafari || isFirefox);
|
||||
}, skip: isSafari || isFirefox);
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ void testMain() {
|
||||
);
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520
|
||||
}, skip: isIosSafari || isFirefox);
|
||||
}, skip: isSafari || isFirefox);
|
||||
|
||||
test('will put the Noto Emoji font before other fallback fonts in the list',
|
||||
() async {
|
||||
@@ -203,7 +203,7 @@ void testMain() {
|
||||
);
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520
|
||||
}, skip: isIosSafari || isFirefox);
|
||||
}, skip: isSafari || isFirefox);
|
||||
|
||||
test('will gracefully fail if we cannot parse the Google Fonts CSS',
|
||||
() async {
|
||||
@@ -357,7 +357,7 @@ void testMain() {
|
||||
}
|
||||
});
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
|
||||
}, skip: isIosSafari);
|
||||
}, skip: isSafari);
|
||||
}
|
||||
|
||||
class TestDownloader extends NotoDownloader {
|
||||
|
||||
@@ -114,5 +114,5 @@ void testMain() {
|
||||
});
|
||||
// TODO(yjbanov): https://github.com/flutter/flutter/issues/60040
|
||||
// TODO(yjbanov): https://github.com/flutter/flutter/issues/71520
|
||||
}, skip: isIosSafari || isFirefox);
|
||||
}, skip: isSafari || isFirefox);
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ void testMain() {
|
||||
);
|
||||
});
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
|
||||
}, skip: isIosSafari);
|
||||
}, skip: isSafari);
|
||||
}
|
||||
|
||||
void _testForImageCodecs({required bool useBrowserImageDecoder}) {
|
||||
|
||||
@@ -103,5 +103,5 @@ void testMain() {
|
||||
});
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520
|
||||
}, skip: isIosSafari || isFirefox);
|
||||
}, skip: isSafari || isFirefox);
|
||||
}
|
||||
|
||||
@@ -160,5 +160,5 @@ void testMain() {
|
||||
});
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520
|
||||
}, skip: isIosSafari || isFirefox);
|
||||
}, skip: isSafari || isFirefox);
|
||||
}
|
||||
|
||||
@@ -70,5 +70,5 @@ void testMain() {
|
||||
});
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
|
||||
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520
|
||||
}, skip: isIosSafari || isFirefox);
|
||||
}, skip: isSafari || isFirefox);
|
||||
}
|
||||
|
||||
@@ -92,8 +92,7 @@ Future<void> testMain() async {
|
||||
await canvasScreenshot(rc, 'canvas_image_blend_group$blendGroup',
|
||||
maxDiffRatePercent: 8.0, region: screenRect);
|
||||
},
|
||||
skip: browserEngine == BrowserEngine.webkit &&
|
||||
operatingSystem == OperatingSystem.iOs);
|
||||
skip: isSafari);
|
||||
}
|
||||
|
||||
// Regression test for https://github.com/flutter/flutter/issues/56971
|
||||
|
||||
Reference in New Issue
Block a user