Changing test runner and platform to be browser independent (flutter/engine#13869)

* changes to add firefox as one of the browser options to test_platform and test_runner

* Creating a supported_browsers file to put all the different browser related maps and utilities

* Remove accidentaly forgotten commented out lines. Clear imports

* fix error in screenshot handler

* Addressing PR comments.

* addressing PR comments part 2:
This commit is contained in:
Nurhan Turgut
2019-11-19 12:18:10 -08:00
committed by GitHub
parent d4af7db522
commit 395ce7ae62
9 changed files with 263 additions and 71 deletions

View File

@@ -10,7 +10,9 @@ import 'package:pedantic/pedantic.dart';
import 'package:stack_trace/stack_trace.dart';
import 'package:typed_data/typed_buffers.dart';
import 'package:test_api/src/utils.dart'; // ignore: implementation_imports
import 'package:test_api/src/utils.dart';
import 'common.dart'; // ignore: implementation_imports
/// An interface for running browser instances.
///

View File

@@ -32,6 +32,8 @@ class Chrome extends Browser {
/// Starts a new instance of Chrome open to the given [url], which may be a
/// [Uri] or a [String].
factory Chrome(Uri url, {bool debug = false}) {
version = ChromeArgParser.instance.version;
assert(version != null);
var remoteDebuggerCompleter = Completer<Uri>.sync();
return Chrome._(() async {
@@ -50,13 +52,16 @@ class Chrome extends Browser {
// --disable-gpu
// --disallow-non-exact-resource-reuse
// --disable-font-subpixel-positioning
final bool isChromeNoSandbox = Platform.environment['CHROME_NO_SANDBOX'] == 'true';
final bool isChromeNoSandbox =
Platform.environment['CHROME_NO_SANDBOX'] == 'true';
var dir = createTempDir();
var args = [
'--user-data-dir=$dir',
url.toString(),
if (!debug) '--headless',
if (isChromeNoSandbox) '--no-sandbox',
if (!debug)
'--headless',
if (isChromeNoSandbox)
'--no-sandbox',
'--window-size=$kMaxScreenshotWidth,$kMaxScreenshotHeight', // When headless, this is the actual size of the viewport
'--disable-extensions',
'--disable-popup-blocking',
@@ -69,10 +74,11 @@ class Chrome extends Browser {
'--remote-debugging-port=$kDevtoolsPort',
];
final Process process = await Process.start(installation.executable, args);
final Process process =
await Process.start(installation.executable, args);
remoteDebuggerCompleter.complete(getRemoteDebuggerUrl(
Uri.parse('http://localhost:${kDevtoolsPort}')));
remoteDebuggerCompleter.complete(
getRemoteDebuggerUrl(Uri.parse('http://localhost:${kDevtoolsPort}')));
unawaited(process.exitCode
.then((_) => Directory(dir).deleteSync(recursive: true)));

View File

@@ -13,23 +13,42 @@ import 'package:yaml/yaml.dart';
import 'common.dart';
import 'environment.dart';
void addChromeVersionOption(ArgParser argParser) {
final io.File lockFile = io.File(
path.join(environment.webUiRootDir.path, 'dev', 'browser_lock.yaml'));
final YamlMap lock = loadYaml(lockFile.readAsStringSync());
final int pinnedChromeVersion = PlatformBinding.instance.getChromeBuild(lock);
class ChromeArgParser extends BrowserArgParser {
static final ChromeArgParser _singletonInstance = ChromeArgParser._();
argParser
..addOption(
'chrome-version',
defaultsTo: '$pinnedChromeVersion',
help: 'The Chrome version to use while running tests. If the requested '
'version has not been installed, it will be downloaded and installed '
'automatically. A specific Chrome build version number, such as 695653 '
'this use that version of Chrome. Value "latest" will use the latest '
'available build of Chrome, installing it if necessary. Value "system" '
'will use the manually installed version of Chrome on this computer.',
);
/// The [ChromeArgParser] singleton.
static ChromeArgParser get instance => _singletonInstance;
String _version;
ChromeArgParser._();
@override
void populateOptions(ArgParser argParser) {
final YamlMap browserLock = BrowserLock.instance.configuration;
final int pinnedChromeVersion =
PlatformBinding.instance.getChromeBuild(browserLock);
argParser
..addOption(
'chrome-version',
defaultsTo: '$pinnedChromeVersion',
help: 'The Chrome version to use while running tests. If the requested '
'version has not been installed, it will be downloaded and installed '
'automatically. A specific Chrome build version number, such as 695653, '
'will use that version of Chrome. Value "latest" will use the latest '
'available build of Chrome, installing it if necessary. Value "system" '
'will use the manually installed version of Chrome on this computer.',
);
}
@override
void parseOptions(ArgResults argResults) {
_version = argResults['chrome-version'];
}
@override
String get version => _version;
}
/// Returns the installation of Chrome, installing it if necessary.
@@ -180,6 +199,7 @@ class ChromeInstaller {
if (unzipResult.exitCode != 0) {
throw BrowserInstallerException(
'Failed to unzip the downloaded Chrome archive ${downloadedFile.path}.\n'
'With the version path ${versionDir.path}\n'
'The unzip process exited with code ${unzipResult.exitCode}.');
}

View File

@@ -4,10 +4,13 @@
import 'dart:io' as io;
import 'package:args/args.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart';
import 'environment.dart';
/// The port number for debugging.
const int kDevtoolsPort = 12345;
const int kMaxScreenshotWidth = 1024;
@@ -124,6 +127,36 @@ class BrowserInstallation {
final String executable;
}
abstract class BrowserArgParser {
const BrowserArgParser();
/// Populate options specific to a browser to the [ArgParser].
void populateOptions(ArgParser argParser);
/// Populate browser with results of the arguments passed.
void parseOptions(ArgResults argResults);
String get version;
}
/// Provides access to the contents of the `browser_lock.yaml` file.
class BrowserLock {
/// Initializes the [BrowserLock] singleton.
static final BrowserLock _singletonInstance = BrowserLock._();
/// The [Keyboard] singleton.
static BrowserLock get instance => _singletonInstance;
YamlMap _configuration = YamlMap();
YamlMap get configuration => _configuration;
BrowserLock._() {
final io.File lockFile = io.File(
path.join(environment.webUiRootDir.path, 'dev', 'browser_lock.yaml'));
this._configuration = loadYaml(lockFile.readAsStringSync());
}
}
/// A string sink that swallows all input.
class DevNull implements StringSink {
@override

View File

@@ -32,6 +32,8 @@ class Firefox extends Browser {
/// Starts a new instance of Firefox open to the given [url], which may be a
/// [Uri] or a [String].
factory Firefox(Uri url, {bool debug = false}) {
version = FirefoxArgParser.instance.version;
assert(version != null);
var remoteDebuggerCompleter = Completer<Uri>.sync();
return Firefox._(() async {

View File

@@ -3,13 +3,51 @@
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:args/args.dart';
import 'package:http/http.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart';
import 'common.dart';
import 'environment.dart';
class FirefoxArgParser extends BrowserArgParser {
static final FirefoxArgParser _singletonInstance = FirefoxArgParser._();
/// The [ChromeArgParser] singleton.
static FirefoxArgParser get instance => _singletonInstance;
String _version;
FirefoxArgParser._();
@override
void populateOptions(ArgParser argParser) {
final YamlMap browserLock = BrowserLock.instance.configuration;
String firefoxVersion = browserLock['firefox']['version'];
argParser
..addOption(
'firefox-version',
defaultsTo: '$firefoxVersion',
help: 'The Firefox version to use while running tests. If the requested '
'version has not been installed, it will be downloaded and installed '
'automatically. Value "latest" will use the latest '
'stable build of Firefox, installing it if necessary. Value "system" '
'will use the manually installed version of Firefox on this computer.',
);
}
@override
void parseOptions(ArgResults argResults) {
_version = argResults['firefox-version'];
}
@override
String get version => _version;
}
/// Returns the installation of Firefox, installing it if necessary.
///
/// If [requestedVersion] is null, uses the version specified on the
@@ -106,7 +144,7 @@ class FirefoxInstaller {
/// HTTP client used to download Firefox.
final Client client = Client();
/// Root directory that contains Chrome versions.
/// Root directory that contains Firefox versions.
final io.Directory firefoxInstallationDir;
/// Installation directory for Firefox of the requested [version].

View File

@@ -0,0 +1,49 @@
// 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 'package:test_api/src/backend/runtime.dart';
import 'browser.dart';
import 'chrome.dart';
import 'chrome_installer.dart';
import 'common.dart';
import 'firefox.dart';
import 'firefox_installer.dart'; // ignore: implementation_imports
/// Utilities for browsers, that tests are supported.
///
/// Extending [Browser] is not enough for supporting test.
///
/// Each new browser should be added to the [Runtime] map, to the [getBrowser]
/// method.
///
/// One should also implement [BrowserArgParser] and add it to the [argParsers].
class SupportedBrowsers {
final List<BrowserArgParser> argParsers =
List.of([ChromeArgParser.instance, FirefoxArgParser.instance]);
final List<String> supportedBrowserNames = ['chrome', 'firefox'];
final Map<String, Runtime> supportedBrowsersToRuntimes = {
'chrome': Runtime.chrome,
'firefox': Runtime.firefox
};
static final SupportedBrowsers _singletonInstance = SupportedBrowsers._();
/// The [SupportedBrowsers] singleton.
static SupportedBrowsers get instance => _singletonInstance;
SupportedBrowsers._();
Browser getBrowser(Runtime runtime, Uri url, {bool debug = false}) {
if (runtime == Runtime.chrome) {
return Chrome(url, debug: debug);
} else if (runtime == Runtime.firefox) {
return Firefox(url, debug: debug);
} else {
throw new UnsupportedError('The browser type not supported in tests');
}
}
}

View File

@@ -38,19 +38,22 @@ import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'
as wip;
import 'browser.dart';
import 'chrome.dart';
import 'common.dart';
import 'environment.dart' as env;
import 'goldens.dart';
import 'supported_browsers.dart';
class BrowserPlatform extends PlatformPlugin {
/// 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, bool doUpdateScreenshotGoldens: false}) async {
static Future<BrowserPlatform> start(String name,
{String root, bool doUpdateScreenshotGoldens: false}) async {
assert(SupportedBrowsers.instance.supportedBrowserNames.contains(name));
var server = shelf_io.IOServer(await HttpMultiServer.loopback(0));
return BrowserPlatform._(
name,
server,
Configuration.current,
p.fromUri(await Isolate.resolvePackageUri(
@@ -66,6 +69,9 @@ class BrowserPlatform extends PlatformPlugin {
/// The underlying server.
final shelf.Server _server;
/// Name for the running browser. Not final on purpose can be mutated later.
String browserName;
/// A randomly-generated secret.
///
/// This is used to ensure that other users on the same system can't snoop
@@ -97,9 +103,11 @@ class BrowserPlatform extends PlatformPlugin {
/// Whether to update screenshot golden files.
final bool doUpdateScreenshotGoldens;
BrowserPlatform._(this._server, Configuration config, String faviconPath,
BrowserPlatform._(
String name, this._server, Configuration config, String faviconPath,
{String root, this.doUpdateScreenshotGoldens})
: _config = config,
: this.browserName = name,
_config = config,
_root = root == null ? p.current : root,
_http = config.pubServeUrl == null ? null : HttpClient() {
var cascade = shelf.Cascade().add(_webSocketHandler.handler);
@@ -109,7 +117,6 @@ class BrowserPlatform extends PlatformPlugin {
final String staticFilePath =
config.suiteDefaults.precompiledPath ?? _root;
cascade = cascade
.add(_screeshotHandler)
.add(packagesDirHandler())
.add(_jsHandler.handler)
.add(createStaticHandler(staticFilePath,
@@ -117,6 +124,10 @@ class BrowserPlatform extends PlatformPlugin {
serveFilesOutsidePath:
config.suiteDefaults.precompiledPath != null))
.add(_wrapperHandler);
// Screenshot tests are only enabled in chrome for now.
if (name == 'chrome') {
cascade = cascade.add(_screeshotHandler);
}
}
var pipeline = shelf.Pipeline()
@@ -130,6 +141,10 @@ class BrowserPlatform extends PlatformPlugin {
}
Future<shelf.Response> _screeshotHandler(shelf.Request request) async {
if (browserName != 'chrome') {
throw Exception('Screenshots tests are only available in Chrome.');
}
if (!request.requestedUri.path.endsWith('/screenshot')) {
return shelf.Response.notFound(
'This request is not handled by the screenshot handler');
@@ -141,11 +156,14 @@ class BrowserPlatform extends PlatformPlugin {
final bool write = requestData['write'];
final double maxDiffRate = requestData['maxdiffrate'];
final Map<String, dynamic> region = requestData['region'];
final String result = await _diffScreenshot(filename, write, maxDiffRate ?? kMaxDiffRateFailure, region);
final String result = await _diffScreenshot(
filename, write, maxDiffRate ?? kMaxDiffRateFailure, region);
return shelf.Response.ok(json.encode(result));
}
Future<String> _diffScreenshot(String filename, bool write, double maxDiffRateFailure, [ Map<String, dynamic> region ]) async {
Future<String> _diffScreenshot(
String filename, bool write, double maxDiffRateFailure,
[Map<String, dynamic> region]) async {
if (doUpdateScreenshotGoldens) {
write = true;
}
@@ -195,7 +213,8 @@ To automatically create this file call matchGoldenFile('$filename', write: true)
'y': region['y'],
'width': region['width'],
'height': region['height'],
'scale': 1, // This is NOT the DPI of the page, instead it's the "zoom level".
'scale':
1, // This is NOT the DPI of the page, instead it's the "zoom level".
},
};
}
@@ -208,8 +227,8 @@ To automatically create this file call matchGoldenFile('$filename', write: true)
'deviceScaleFactor': 1,
'mobile': false,
});
final wip.WipResponse response =
await wipConnection.sendCommand('Page.captureScreenshot', captureScreenshotParameters);
final wip.WipResponse response = await wipConnection.sendCommand(
'Page.captureScreenshot', captureScreenshotParameters);
// Compare screenshots
final Image screenshot = decodePng(base64.decode(response.result['data']));
@@ -226,31 +245,37 @@ To automatically create this file call matchGoldenFile('$filename', write: true)
}
}
ImageDiff diff = ImageDiff(golden: decodeNamedImage(file.readAsBytesSync(), filename), other: screenshot);
ImageDiff diff = ImageDiff(
golden: decodeNamedImage(file.readAsBytesSync(), filename),
other: screenshot);
if (diff.rate > 0) { // Images are different, so produce some debug info
if (diff.rate > 0) {
// Images are different, so produce some debug info
final String testResultsPath = isCirrus
? p.join(
Platform.environment['CIRRUS_WORKING_DIR'],
'test_results',
)
: p.join(
env.environment.webUiDartToolDir.path,
'test_results',
);
? p.join(
Platform.environment['CIRRUS_WORKING_DIR'],
'test_results',
)
: p.join(
env.environment.webUiDartToolDir.path,
'test_results',
);
Directory(testResultsPath).createSync(recursive: true);
final String basename = p.basenameWithoutExtension(file.path);
final File actualFile = File(p.join(testResultsPath, '$basename.actual.png'));
final File actualFile =
File(p.join(testResultsPath, '$basename.actual.png'));
actualFile.writeAsBytesSync(encodePng(screenshot), flush: true);
final File diffFile = File(p.join(testResultsPath, '$basename.diff.png'));
diffFile.writeAsBytesSync(encodePng(diff.diff), flush:true);
diffFile.writeAsBytesSync(encodePng(diff.diff), flush: true);
final File expectedFile = File(p.join(testResultsPath, '$basename.expected.png'));
final File expectedFile =
File(p.join(testResultsPath, '$basename.expected.png'));
file.copySync(expectedFile.path);
final File reportFile = File(p.join(testResultsPath, '$basename.report.html'));
final File reportFile =
File(p.join(testResultsPath, '$basename.report.html'));
reportFile.writeAsStringSync('''
Golden file $filename did not match the image generated by the test.
@@ -275,16 +300,19 @@ Golden file $filename did not match the image generated by the test.
''');
final StringBuffer message = StringBuffer();
message.writeln('Golden file $filename did not match the image generated by the test.');
message.writeln(
'Golden file $filename did not match the image generated by the test.');
message.writeln(getPrintableDiffFilesInfo(diff.rate, maxDiffRateFailure));
message.writeln('You can view the test report in your browser by opening:');
message
.writeln('You can view the test report in your browser by opening:');
// Cirrus cannot serve HTML pages generated by build jobs, so we
// archive all the files so that they can be downloaded and inspected
// locally.
if (isCirrus) {
final String taskId = Platform.environment['CIRRUS_TASK_ID'];
final String baseArtifactsUrl = 'https://api.cirrus-ci.com/v1/artifact/task/$taskId/web_engine_test/test_results';
final String baseArtifactsUrl =
'https://api.cirrus-ci.com/v1/artifact/task/$taskId/web_engine_test/test_results';
final String cirrusReportUrl = '$baseArtifactsUrl/$basename.report.zip';
message.writeln(cirrusReportUrl);
@@ -304,7 +332,8 @@ Golden file $filename did not match the image generated by the test.
message.writeln(localReportPath);
}
message.writeln('To update the golden file call matchGoldenFile(\'$filename\', write: true).');
message.writeln(
'To update the golden file call matchGoldenFile(\'$filename\', write: true).');
message.writeln('Golden file: ${expectedFile.path}');
message.writeln('Actual file: ${actualFile.path}');
@@ -649,8 +678,9 @@ class BrowserManager {
/// Starts the browser identified by [browser] using [settings] and has it load [url].
///
/// If [debug] is true, starts the browser in debug mode.
static Browser _newBrowser(Uri url, Runtime browser, {bool debug = false}) {
return Chrome(url, debug: debug);
static Browser _newBrowser(Uri url, Runtime browser,
{bool debug = false}) {
return SupportedBrowsers.instance.getBrowser(browser, url, debug: debug);
}
/// Creates a new BrowserManager that communicates with [browser] over

View File

@@ -14,8 +14,7 @@ import 'package:test_api/src/backend/runtime.dart'; // ignore: implementation_im
import 'package:test_core/src/executable.dart'
as test; // ignore: implementation_imports
import 'chrome.dart';
import 'chrome_installer.dart';
import 'supported_browsers.dart';
import 'test_platform.dart';
import 'environment.dart';
import 'utils.dart';
@@ -32,12 +31,20 @@ class TestCommand extends Command<bool> {
..addFlag(
'update-screenshot-goldens',
defaultsTo: false,
help: 'When running screenshot tests writes them to the file system into '
help:
'When running screenshot tests writes them to the file system into '
'.dart_tool/goldens. Use this option to bulk-update all screenshots, '
'for example, when a new browser version affects pixels.',
)
..addOption(
'browser',
defaultsTo: 'chrome',
help: 'An option to choose a browser to run the tests. Tests only work '
' on Chrome for now.',
);
addChromeVersionOption(argParser);
SupportedBrowsers.instance.argParsers
.forEach((t) => t.populateOptions(argParser));
}
@override
@@ -48,7 +55,8 @@ class TestCommand extends Command<bool> {
@override
Future<bool> run() async {
Chrome.version = chromeVersion;
SupportedBrowsers.instance
..argParsers.forEach((t) => t.parseOptions(argResults));
_copyTestFontsIntoWebUi();
await _buildHostPage();
@@ -73,8 +81,7 @@ class TestCommand extends Command<bool> {
/// Paths to targets to run, e.g. a single test.
List<String> get targets => argResults.rest;
/// See [ChromeInstallerCommand.chromeVersion].
String get chromeVersion => argResults['chrome-version'];
String get browser => argResults['browser'];
/// When running screenshot tests writes them to the file system into
/// ".dart_tool/goldens".
@@ -161,7 +168,8 @@ class TestCommand extends Command<bool> {
'$hostDartPath.js.timestamp',
));
final String timestamp = hostDartFile.statSync().modified.millisecondsSinceEpoch.toString();
final String timestamp =
hostDartFile.statSync().modified.millisecondsSinceEpoch.toString();
if (timestampFile.existsSync()) {
final String lastBuildTimestamp = timestampFile.readAsStringSync();
if (lastBuildTimestamp == timestamp) {
@@ -195,7 +203,7 @@ class TestCommand extends Command<bool> {
timestampFile.writeAsStringSync(timestamp);
}
Future<void> _buildTests({ List<FilePath> targets }) async {
Future<void> _buildTests({List<FilePath> targets}) async {
final int exitCode = await runProcess(
environment.pubExecutable,
<String>[
@@ -206,11 +214,10 @@ class TestCommand extends Command<bool> {
'-o',
'build',
if (targets != null)
for (FilePath path in targets)
...[
'--build-filter=${path.relativeToWebUi}.js',
'--build-filter=${path.relativeToWebUi}.browser_test.dart.js',
],
for (FilePath path in targets) ...[
'--build-filter=${path.relativeToWebUi}.js',
'--build-filter=${path.relativeToWebUi}.browser_test.dart.js',
],
],
workingDirectory: environment.webUiRootDir.path,
);
@@ -234,13 +241,17 @@ class TestCommand extends Command<bool> {
...<String>['-r', 'compact'],
'--concurrency=$concurrency',
if (isDebug) '--pause-after-load',
'--platform=chrome',
'--platform=$browser',
'--precompiled=${environment.webUiRootDir.path}/build',
'--',
...testFiles.map((f) => f.relativeToWebUi).toList(),
];
hack.registerPlatformPlugin(<Runtime>[Runtime.chrome], () {
hack.registerPlatformPlugin(<Runtime>[
SupportedBrowsers.instance.supportedBrowsersToRuntimes[browser]
], () {
return BrowserPlatform.start(
browser,
root: io.Directory.current.path,
// It doesn't make sense to update a screenshot for a test that is expected to fail.
doUpdateScreenshotGoldens: !expectFailure && doUpdateScreenshotGoldens,
@@ -280,7 +291,8 @@ void _copyTestFontsIntoWebUi() {
for (String fontFile in _kTestFonts) {
final io.File sourceTtf = io.File(path.join(fontsPath, fontFile));
final String destinationTtfPath = path.join(environment.webUiRootDir.path, 'lib', 'assets', fontFile);
final String destinationTtfPath =
path.join(environment.webUiRootDir.path, 'lib', 'assets', fontFile);
sourceTtf.copySync(destinationTtfPath);
}
}