[web] separate tests into build + test steps; add run command (flutter/engine#27495)

This commit is contained in:
Yegor
2021-08-03 16:22:21 -07:00
committed by GitHub
parent 585e87a395
commit b09afa1c05
34 changed files with 1030 additions and 1149 deletions

View File

@@ -31,9 +31,16 @@ If you don't want to add `felt` to your path, you can still invoke it using a re
## Speeding up your builds and tests
If you are a Google employee, you can use an internal instance of Goma to parallelize your builds. Because Goma compiles code on remote servers, this option is effective even on low-powered laptops.
If you are a Google employee, you can use an internal instance of Goma (go/ma)
to parallelize your builds. Because Goma compiles code on remote servers, this
option is particularly effective for building on low-powered laptops.
By default, when compiling Dart code to JavaScript, we use 8 `dart2js` workers.
Concurrency of various build steps can be configured via environment variables:
- `FELT_DART2JS_CONCURRENCY` specifies the number of concurrent `dart2js`
processes used to compile tests. Default value is 8.
- `FELT_TEST_CONCURRENCY` specifies the number of tests run concurrently.
Default value is 10.
## Running web engine tests

View File

@@ -0,0 +1,86 @@
// 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:io' as io;
import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart';
import 'common.dart';
import 'environment.dart';
/// Returns the browser configuration based on the `browser_lock.yaml` file in
/// the current engine workspace.
final BrowserLock browserLock = BrowserLock();
/// Provides access to the contents of the `browser_lock.yaml` file.
class BrowserLock {
factory BrowserLock() {
final io.File lockFile = io.File(
path.join(environment.webUiRootDir.path, 'dev', 'browser_lock.yaml'),
);
final YamlMap yaml = loadYaml(lockFile.readAsStringSync()) as YamlMap;
return BrowserLock._fromYaml(yaml);
}
BrowserLock._fromYaml(YamlMap yaml) :
chromeLock = ChromeLock._fromYaml(yaml['chrome'] as YamlMap),
firefoxLock = FirefoxLock._fromYaml(yaml['firefox'] as YamlMap),
edgeLock = EdgeLock._fromYaml(yaml['edge'] as YamlMap),
safariIosLock = SafariIosLock._fromYaml(yaml['safari_ios'] as YamlMap);
final ChromeLock chromeLock;
final FirefoxLock firefoxLock;
final EdgeLock edgeLock;
final SafariIosLock safariIosLock;
}
class ChromeLock {
ChromeLock._fromYaml(YamlMap yaml) :
linux = (yaml['Linux'] as int).toString(),
mac = (yaml['Mac'] as int).toString(),
windows = (yaml['Win'] as int).toString();
final String linux;
final String mac;
final String windows;
/// Return the version of Chromium to use for the current operating system.
String get versionForCurrentPlatform {
return PlatformBinding.instance.getChromeBuild(this);
}
}
class FirefoxLock {
FirefoxLock._fromYaml(YamlMap yaml) :
version = yaml['version'] as String;
final String version;
}
class EdgeLock {
EdgeLock._fromYaml(YamlMap yaml) :
launcherVersion = yaml['launcher_version'] as String;
final String launcherVersion;
}
class SafariIosLock {
SafariIosLock._fromYaml(YamlMap yaml) :
majorVersion = yaml['major_version'] as int,
minorVersion = yaml['minor_version'] as int,
device = yaml['device'] as String,
heightOfHeader = yaml['height_of_header'] as int,
heightOfFooter = yaml['height_of_footer'] as int,
scaleFactor = yaml['scale_factor'] as double;
final int majorVersion;
final int minorVersion;
final String device;
final int heightOfHeader;
final int heightOfFooter;
final double scaleFactor;
String get simulatorDescription => '$device with iOS $majorVersion.$minorVersion';
}

View File

@@ -3,6 +3,11 @@
chrome:
# It seems Chrome can't always release from the same build for all operating
# systems, so we specify per-OS build number.
#
# The OS names here must match what recipe Python expression
# `self.m.platform.name.capitalize()` evaluates to. See:
#
# recipe_modules/web_util/api.py
Linux: 768968 # Major version 84
Mac: 768985 # Major version 84
Win: 768975 # Major version 84
@@ -15,12 +20,12 @@ firefox:
edge:
launcher_version: '1.2.0.0'
ios-safari:
safari_ios:
# Make sure this version is the same version supported by LUCI macOS bots.
# XCode on these bots will be updated once a year, do not forget to update
# `heightOfHeader` during this time.
majorVersion: 13
minorVersion: 0
major_version: 13
minor_version: 0
device: 'iPhone 11'
# `xcrun simctl` command is used to take screenshots. It takes the screenshot
# of the entire simulator. Therefore we need to crop all the parts other than
@@ -29,10 +34,10 @@ ios-safari:
# `heightOfHeader` is the number of pixels taken by the phone's header menu
# and the browsers address bar.
# TODO: https://github.com/flutter/flutter/issues/65672
heightOfHeader: 189
height_of_header: 189
# `heightOfFooter` is the number of pixels taken by the phone's navigation
# menu.
heightOfFooter: 250
height_of_footer: 250
# Most of the time tests use a portion of the screen to compare goldens
# instead of the entire screen. This area is reprented by a rectangle
# when taking screenshots. However the rectangle dimensions are in logical
@@ -41,4 +46,4 @@ ios-safari:
# transformation by a scale_factor (a.k.a. we perform isotropic scaling).
# This value will be differ depending on the phone.
# For iOS 13.0 iPhone 11 Pro, this number is 1.15.
scaleFactor: 1.00
scale_factor: 1.00

View File

@@ -30,7 +30,7 @@ class BuildCommand extends Command<bool> with ArgUtils<bool> {
@override
String get description => 'Build the Flutter web engine.';
bool get isWatchMode => boolArg('watch')!;
bool get isWatchMode => boolArg('watch');
@override
FutureOr<bool> run() async {
@@ -61,7 +61,7 @@ class BuildCommand extends Command<bool> with ArgUtils<bool> {
/// state. GN is pretty quick though, so it's OK to not support interruption.
class GnPipelineStep extends ProcessStep {
@override
String get name => 'gn';
String get description => 'gn';
@override
bool get isSafeToInterrupt => false;
@@ -85,7 +85,7 @@ class GnPipelineStep extends ProcessStep {
/// Can be safely interrupted.
class NinjaPipelineStep extends ProcessStep {
@override
String get name => 'ninja';
String get description => 'ninja';
@override
bool get isSafeToInterrupt => true;

View File

@@ -14,6 +14,7 @@ import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'
as wip;
import 'browser.dart';
import 'browser_lock.dart';
import 'chrome_installer.dart';
import 'common.dart';
import 'environment.dart';
@@ -35,7 +36,12 @@ class ChromeEnvironment implements BrowserEnvironment {
@override
ScreenshotManager? getScreenshotManager() {
return ChromeScreenshotManager();
// Always compare screenshots when running tests locally. On CI only compare
// on Linux.
if (Platform.isLinux || !isLuci) {
return ChromeScreenshotManager();
}
return null;
}
@override
@@ -59,7 +65,7 @@ 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}) {
final String version = ChromeArgParser.instance.version;
final String version = browserLock.chromeLock.versionForCurrentPlatform;
final Completer<Uri> remoteDebuggerCompleter = Completer<Uri>.sync();
return Chrome._(() async {
final BrowserInstallation installation = await getOrInstallChrome(

View File

@@ -8,55 +8,14 @@ import 'dart:typed_data';
import 'package:archive/archive.dart';
import 'package:archive/archive_io.dart';
import 'package:args/args.dart';
import 'package:http/http.dart';
import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart';
import 'browser_lock.dart';
import 'common.dart';
import 'environment.dart';
import 'exceptions.dart';
class ChromeArgParser extends BrowserArgParser {
static final ChromeArgParser _singletonInstance = ChromeArgParser._();
/// The [ChromeArgParser] singleton.
static ChromeArgParser get instance => _singletonInstance;
late String _version;
late int _pinnedChromeBuildNumber;
ChromeArgParser._();
@override
void populateOptions(ArgParser argParser) {
final YamlMap browserLock = BrowserLock.instance.configuration;
_pinnedChromeBuildNumber =
PlatformBinding.instance.getChromeBuild(browserLock);
argParser.addOption(
'chrome-version',
defaultsTo: pinnedChromeBuildNumber,
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'] as String;
}
@override
String get version => _version;
String get pinnedChromeBuildNumber => _pinnedChromeBuildNumber.toString();
}
/// Returns the installation of Chrome, installing it if necessary.
///
/// If [requestedVersion] is null, uses the version specified on the
@@ -287,7 +246,7 @@ Future<String> fetchLatestChromeVersion() async {
String preinstalledChromeExecutable() {
// Note that build number and major version is different for Chrome.
// For example for a build number `753189`, major version is 83.
final String buildNumber = ChromeArgParser.instance.pinnedChromeBuildNumber;
final String buildNumber = browserLock.chromeLock.versionForCurrentPlatform;
final ChromeInstaller chromeInstaller = ChromeInstaller(version: buildNumber);
if (chromeInstaller.isInstalled) {
final String executable = chromeInstaller.getInstallation()!.executable;

View File

@@ -29,9 +29,9 @@ class CleanCommand extends Command<bool> with ArgUtils<bool> {
@override
String get name => 'clean';
bool get _alsoCleanNinja => boolArg('ninja')!;
bool get _alsoCleanNinja => boolArg('ninja');
bool get _alsoCleanFlutterRepo => boolArg('flutter')!;
bool get _alsoCleanFlutterRepo => boolArg('flutter');
@override
String get description => 'Deletes build caches and artifacts.';

View File

@@ -4,11 +4,15 @@
import 'dart:io' as io;
import 'package:args/args.dart';
import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart';
import 'environment.dart';
import 'browser.dart';
import 'browser_lock.dart';
import 'chrome.dart';
import 'edge.dart';
import 'firefox.dart';
import 'safari_ios.dart';
import 'safari_macos.dart';
/// The port number for debugging.
const int kDevtoolsPort = 12345;
@@ -35,7 +39,7 @@ abstract class PlatformBinding {
throw '${io.Platform.operatingSystem} is not supported';
}
int getChromeBuild(YamlMap chromeLock);
String getChromeBuild(ChromeLock chromeLock);
String getChromeDownloadUrl(String version);
String getFirefoxDownloadUrl(String version);
String getFirefoxDownloadFilename(String version);
@@ -51,9 +55,8 @@ const String _kBaseDownloadUrl =
class _WindowsBinding implements PlatformBinding {
@override
int getChromeBuild(YamlMap browserLock) {
final YamlMap chromeMap = browserLock['chrome'] as YamlMap;
return chromeMap['Win'] as int;
String getChromeBuild(ChromeLock chromeLock) {
return chromeLock.windows;
}
@override
@@ -90,9 +93,8 @@ class _WindowsBinding implements PlatformBinding {
class _LinuxBinding implements PlatformBinding {
@override
int getChromeBuild(YamlMap browserLock) {
final YamlMap chromeMap = browserLock['chrome'] as YamlMap;
return chromeMap['Linux'] as int;
String getChromeBuild(ChromeLock chromeLock) {
return chromeLock.linux;
}
@override
@@ -131,9 +133,8 @@ class _LinuxBinding implements PlatformBinding {
class _MacBinding implements PlatformBinding {
@override
int getChromeBuild(YamlMap browserLock) {
final YamlMap chromeMap = browserLock['chrome'] as YamlMap;
return chromeMap['Mac'] as int;
String getChromeBuild(ChromeLock chromeLock) {
return chromeLock.mac;
}
@override
@@ -186,36 +187,6 @@ 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'));
_configuration = loadYaml(lockFile.readAsStringSync()) as YamlMap;
}
}
/// A string sink that swallows all input.
class DevNull implements StringSink {
@override
@@ -240,3 +211,31 @@ bool get isLuci => io.Platform.environment['LUCI_CONTEXT'] != null;
/// Whether the felt command is running on one of the Continuous Integration
/// environements.
bool get isCi => isCirrus || isLuci;
const String kChrome = 'chrome';
const String kEdge = 'edge';
const String kFirefox = 'firefox';
const String kSafari = 'safari';
const String kSafariIos = 'ios-safari';
const List<String> kAllBrowserNames = <String>[
kChrome,
kEdge,
kFirefox,
kSafari,
kSafariIos,
];
/// Creates an environment for a browser.
///
/// The [browserName] matches the browser name passed as the `--browser` option.
BrowserEnvironment getBrowserEnvironment(String browserName) {
switch (browserName) {
case kChrome: return ChromeEnvironment();
case kEdge: return EdgeEnvironment();
case kFirefox: return FirefoxEnvironment();
case kSafari: return SafariMacOsEnvironment();
case kSafariIos: return SafariIosEnvironment();
}
throw UnsupportedError('Browser $browserName is not supported.');
}

View File

@@ -7,25 +7,10 @@ import 'dart:async';
import 'package:args/command_runner.dart';
import 'package:simulators/simulator_manager.dart';
import 'safari_installation.dart';
import 'browser_lock.dart';
import 'utils.dart';
class CreateSimulatorCommand extends Command<bool> with ArgUtils<bool> {
CreateSimulatorCommand() {
IosSafariArgParser.instance.populateOptions(argParser);
argParser
.addOption(
'type',
defaultsTo: _defaultType,
help: 'Type of the mobile simulator. Currently the only iOS '
'Simulators are supported. Android will be added soon. This option '
'is not case sensitive, ios, iOS, IOS are all valid.',
);
}
/// Currently the only iOS Simulators are supported.
static const String _defaultType = 'iOS';
@override
String get name => 'create_simulator';
@@ -34,17 +19,14 @@ class CreateSimulatorCommand extends Command<bool> with ArgUtils<bool> {
@override
FutureOr<bool> run() async {
IosSafariArgParser.instance.parseOptions(argResults!);
final String simulatorType = argResults!['type'] as String;
if (simulatorType.toUpperCase() != 'IOS') {
throw Exception('Currently the only iOS Simulators are supported');
}
final IosSimulatorManager iosSimulatorManager = IosSimulatorManager();
try {
final SafariIosLock lock = browserLock.safariIosLock;
final IosSimulator simulator = await iosSimulatorManager.createSimulator(
IosSafariArgParser.instance.iosMajorVersion,
IosSafariArgParser.instance.iosMinorVersion,
IosSafariArgParser.instance.iosDevice);
lock.majorVersion,
lock.minorVersion,
lock.device,
);
print('INFO: Simulator created ${simulator.toString()}');
} catch (e) {
throw Exception('Error creating requested simulator. You can use Xcode '

View File

@@ -8,6 +8,7 @@ import 'dart:io';
import 'package:test_api/src/backend/runtime.dart';
import 'browser.dart';
import 'browser_lock.dart';
import 'common.dart';
import 'edge_installation.dart';
@@ -47,12 +48,9 @@ class Edge extends Browser {
/// Starts a new instance of Safari open to the given [url], which may be a
/// [Uri] or a [String].
factory Edge(Uri url) {
final String version = EdgeArgParser.instance.version;
return Edge._(() async {
// TODO(yjbanov): Configure info log for LUCI.
final BrowserInstallation installation = await getEdgeInstallation(
version,
browserLock.edgeLock.launcherVersion,
infoLog: DevNull(),
);

View File

@@ -5,43 +5,13 @@
import 'dart:async';
import 'dart:io' as io;
import 'package:args/args.dart';
import 'package:http/http.dart';
import 'package:path/path.dart' as path;
import 'browser_lock.dart';
import 'common.dart';
import 'environment.dart';
class EdgeArgParser extends BrowserArgParser {
static final EdgeArgParser _singletonInstance = EdgeArgParser._();
/// The [EdgeArgParser] singleton.
static EdgeArgParser get instance => _singletonInstance;
late String _version;
EdgeArgParser._();
@override
void populateOptions(ArgParser argParser) {
argParser.addOption(
'edge-version',
defaultsTo: 'system',
help: 'The Edge version to use while running tests. The Edge '
'browser installed on the system is used as the only option now.',
);
}
@override
void parseOptions(ArgResults argResults) {
_version = argResults['edge-version'] as String;
assert(_version == 'system');
}
@override
String get version => _version;
}
/// Returns the installation of Edge.
///
/// Currently uses the Edge version installed on the operating system.
@@ -112,7 +82,7 @@ class EdgeLauncher {
bool get isInstalled => executable.existsSync();
/// Version number launcher executable `MicrosoftEdgeLauncher`.
final String version;
String get version => browserLock.edgeLock.launcherVersion;
/// Url for downloading `MicrosoftEdgeLauncher`.
///
@@ -120,9 +90,7 @@ class EdgeLauncher {
String get windowsEdgeLauncherDownloadUrl =>
'https://github.com/MicrosoftEdge/edge-launcher/releases/download/$version/MicrosoftEdgeLauncher.exe';
EdgeLauncher()
: version =
BrowserLock.instance.configuration['edge']['launcher_version'] as String;
EdgeLauncher();
/// Install the launcher if it does not exist in this system.
Future<void> install() async {

View File

@@ -38,7 +38,7 @@ class Environment {
webUiRootDir
]) {
if (!expectedDirectory.existsSync()) {
throw ToolException('$expectedDirectory does not exist.');
throw ToolExit('$expectedDirectory does not exist.');
}
}

View File

@@ -11,10 +11,13 @@ class BrowserInstallerException implements Exception {
String toString() => message;
}
class ToolException implements Exception {
ToolException(this.message);
/// Throw this exception in felt command to exit felt with a message and a
/// non-zero exit code.
class ToolExit implements Exception {
ToolExit(this.message, { this.exitCode = 1 });
final String message;
final int exitCode;
@override
String toString() => message;

View File

@@ -11,6 +11,7 @@ import 'clean.dart';
import 'create_simulator.dart';
import 'exceptions.dart';
import 'licenses.dart';
import 'run.dart';
import 'test_runner.dart';
import 'utils.dart';
@@ -18,11 +19,12 @@ CommandRunner<bool> runner = CommandRunner<bool>(
'felt',
'Command-line utility for building and testing Flutter web engine.',
)
..addCommand(BuildCommand())
..addCommand(CleanCommand())
..addCommand(CreateSimulatorCommand())
..addCommand(LicensesCommand())
..addCommand(TestCommand())
..addCommand(BuildCommand());
..addCommand(RunCommand())
..addCommand(TestCommand());
Future<void> main(List<String> rawArgs) async {
// Remove --clean from the list as that's processed by the wrapper script.
@@ -38,17 +40,17 @@ Future<void> main(List<String> rawArgs) async {
int exitCode = -1;
try {
final bool result = (await runner.run(args))!;
if (result == false) {
final bool? result = await runner.run(args);
if (result != true) {
print('Sub-command failed: `${args.join(' ')}`');
exitCode = 1;
}
} on UsageException catch (e) {
print(e);
exitCode = 64; // Exit code 64 indicates a usage error.
} on ToolException catch (e) {
io.stderr.writeln(e.message);
exitCode = 1;
} on ToolExit catch (exception) {
io.stderr.writeln(exception.message);
exitCode = exception.exitCode;
} on ProcessException catch (e) {
io.stderr.writeln('description: ${e.description}'
'executable: ${e.executable} '

View File

@@ -11,6 +11,7 @@ import 'package:test_api/src/backend/runtime.dart';
import 'package:test_core/src/util/io.dart';
import 'browser.dart';
import 'browser_lock.dart';
import 'common.dart';
import 'environment.dart';
import 'firefox_installer.dart';
@@ -54,11 +55,10 @@ 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}) {
final String version = FirefoxArgParser.instance.version;
final Completer<Uri> remoteDebuggerCompleter = Completer<Uri>.sync();
return Firefox._(() async {
final BrowserInstallation installation = await getOrInstallFirefox(
version,
browserLock.firefoxLock.version,
infoLog: isCirrus ? stdout : DevNull(),
);

View File

@@ -4,50 +4,13 @@
import 'dart:io' as io;
import 'package:args/args.dart';
import 'package:http/http.dart';
import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart';
import 'common.dart';
import 'environment.dart';
import 'exceptions.dart';
class FirefoxArgParser extends BrowserArgParser {
static final FirefoxArgParser _singletonInstance = FirefoxArgParser._();
/// The [FirefoxArgParser] singleton.
static FirefoxArgParser get instance => _singletonInstance;
late final String _version;
FirefoxArgParser._();
@override
void populateOptions(ArgParser argParser) {
final YamlMap browserLock = BrowserLock.instance.configuration;
final String firefoxVersion = browserLock['firefox']['version'] as String;
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'] as String;
}
@override
String get version => _version;
}
/// Returns the installation of Firefox, installing it if necessary.
///
/// If [requestedVersion] is null, uses the version specified on the

View File

@@ -0,0 +1,94 @@
// 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:io' as io;
import 'package:args/command_runner.dart';
import 'common.dart';
import 'steps/compile_tests_step.dart';
import 'steps/run_tests_step.dart';
import 'utils.dart';
import 'watcher.dart';
/// Runs build and test steps.
///
/// This command is designed to be invoked by the LUCI build graph. However, it
/// is also usable locally.
///
/// Usage:
///
/// felt run name_of_build_step
class RunCommand extends Command<bool> with ArgUtils<bool> {
RunCommand() {
argParser.addFlag(
'list',
abbr: 'l',
defaultsTo: false,
help: 'Lists all available build steps.',
);
}
@override
String get name => 'run';
bool get isListSteps => boolArg('list');
@override
String get description => 'Runs a build step.';
/// Build steps to run, in order specified.
List<String> get stepNames => argResults!.rest;
@override
FutureOr<bool> run() async {
// All available build steps.
final Map<String, PipelineStep> buildSteps = <String, PipelineStep>{
'compile_tests': CompileTestsStep(),
for (final String browserName in kAllBrowserNames)
'run_tests_$browserName': RunTestsStep(
browserEnvironment: getBrowserEnvironment(browserName),
isDebug: false,
doUpdateScreenshotGoldens: false,
),
};
if (isListSteps) {
buildSteps.keys.forEach(print);
return true;
}
if (stepNames.isEmpty) {
throw UsageException('No build steps specified.', argParser.usage);
}
final List<String> unrecognizedStepNames = <String>[];
for (final String stepName in stepNames) {
if (!buildSteps.containsKey(stepName)) {
unrecognizedStepNames.add(stepName);
}
}
if (unrecognizedStepNames.isNotEmpty) {
io.stderr.writeln(
'Unknown build steps specified: ${unrecognizedStepNames.join(', ')}',
);
return false;
}
final List<PipelineStep> steps = <PipelineStep>[];
print('Running steps ${steps.join(', ')}');
for (final String stepName in stepNames) {
steps.add(buildSteps[stepName]!);
}
final Stopwatch stopwatch = Stopwatch()..start();
final Pipeline pipeline = Pipeline(steps: steps);
await pipeline.run();
stopwatch.stop();
print('Finished running steps in ${stopwatch.elapsedMilliseconds / 1000} seconds.');
return true;
}
}

View File

@@ -5,172 +5,60 @@
import 'dart:async';
import 'dart:io' as io;
import 'package:args/args.dart';
import 'package:simulators/simulator_manager.dart';
import 'package:yaml/yaml.dart';
import 'browser_lock.dart';
import 'common.dart';
import 'utils.dart';
class SafariArgParser extends BrowserArgParser {
static final SafariArgParser _singletonInstance = SafariArgParser._();
/// The [SafariArgParser] singleton.
static SafariArgParser get instance => _singletonInstance;
SafariArgParser._();
@override
void populateOptions(ArgParser argParser) {
argParser.addOption(
'safari-version',
defaultsTo: 'system',
help: 'The Safari version to use while running tests. The Safari '
'browser installed on the system is used as the only option now.'
'Soon we will add support for using different versions using the '
'tech previews.',
);
// Populate options for Ios Safari.
IosSafariArgParser.instance.populateOptions(argParser);
/// Returns [IosSimulator] if the [Platform] is `macOS` and simulator
/// is started.
///
/// Throws an [StateError] if these two conditions are not met.
IosSimulator get iosSimulator {
if (!io.Platform.isMacOS) {
throw StateError('iOS Simulator is only available on macOS machines.');
}
@override
void parseOptions(ArgResults argResults) {
_version = argResults['safari-version'] as String;
assert(_version == 'system');
final String browser = argResults['browser'] as String;
_isMobileBrowser = browser == 'ios-safari';
}
@override
String get version => _version;
late String _version;
bool get isMobileBrowser => _isMobileBrowser;
late bool _isMobileBrowser;
}
class IosSafariArgParser extends BrowserArgParser {
static final IosSafariArgParser _singletonInstance = () {
final YamlMap browserLock = BrowserLock.instance.configuration;
return IosSafariArgParser._(
pinnedIosMajorVersion: browserLock['ios-safari']['majorVersion'] as int,
pinnedIosMinorVersion: browserLock['ios-safari']['minorVersion'] as int,
pinnedIosDevice: browserLock['ios-safari']['device'] as String,
if (_iosSimulator == null) {
throw StateError(
'iOS Simulator not started. Please first call initIOSSimulator method',
);
}();
/// The [IosSafariArgParser] singleton.
static IosSafariArgParser get instance => _singletonInstance;
@override
String get version => 'iOS $iosMajorVersion.$iosMinorVersion';
final int _pinnedIosMajorVersion;
int? _iosMajorVersion;
int get iosMajorVersion => _iosMajorVersion ?? _pinnedIosMajorVersion;
final int _pinnedIosMinorVersion;
int? _iosMinorVersion;
int get iosMinorVersion => _iosMinorVersion ?? _pinnedIosMinorVersion;
final String _pinnedIosDevice;
String? _iosDevice;
String get iosDevice => _iosDevice ?? _pinnedIosDevice;
IosSafariArgParser._({
required int pinnedIosMajorVersion,
required int pinnedIosMinorVersion,
required String pinnedIosDevice,
}) :
_pinnedIosMajorVersion = pinnedIosMajorVersion,
_pinnedIosMinorVersion = pinnedIosMinorVersion,
_pinnedIosDevice = pinnedIosDevice;
/// Returns [IosSimulator] if the [Platform] is `macOS` and simulator
/// is started.
///
/// Throws an [StateError] if these two conditions are not met.
IosSimulator get iosSimulator {
if (!io.Platform.isMacOS) {
throw StateError('iOS Simulator is only available on macOS machines.');
}
if (_iosSimulator == null) {
throw StateError(
'iOS Simulator not started. Please first call initIOSSimulator method',
);
}
return _iosSimulator!;
}
IosSimulator? _iosSimulator;
return _iosSimulator!;
}
IosSimulator? _iosSimulator;
/// Inializes and boots an [IosSimulator] using the [iosMajorVersion],
/// [iosMinorVersion] and [iosDevice] arguments.
Future<void> initIosSimulator() async {
if (_iosSimulator != null) {
throw StateError('_iosSimulator can only be initialized once');
}
final IosSimulatorManager iosSimulatorManager = IosSimulatorManager();
final IosSimulator simulator;
try {
simulator = await iosSimulatorManager.getSimulator(
iosMajorVersion,
iosMinorVersion,
iosDevice,
);
_iosSimulator = simulator;
} catch (e) {
throw Exception('Error getting requested simulator. Try running '
'`felt create` command first before running the tests. Exception: '
'$e');
}
if (!simulator.booted) {
await simulator.boot();
print('INFO: Simulator ${simulator.id} booted.');
cleanupCallbacks.add(() async {
await simulator.shutdown();
print('INFO: Simulator ${simulator.id} shutdown.');
});
}
/// Inializes and boots an [IosSimulator] using the [iosMajorVersion],
/// [iosMinorVersion] and [iosDevice] arguments.
Future<void> initIosSimulator() async {
if (_iosSimulator != null) {
throw StateError('_iosSimulator can only be initialized once');
}
final IosSimulatorManager iosSimulatorManager = IosSimulatorManager();
final IosSimulator simulator;
final SafariIosLock lock = browserLock.safariIosLock;
try {
simulator = await iosSimulatorManager.getSimulator(
lock.majorVersion,
lock.minorVersion,
lock.device,
);
_iosSimulator = simulator;
} catch (e) {
io.stderr.writeln(
'Error getting iOS Simulator for ${lock.simulatorDescription}.\n'
'Try running `felt create` command before running tests.',
);
rethrow;
}
@override
void populateOptions(ArgParser argParser) {
final String pinnedIosVersion =
'$_pinnedIosMajorVersion.$_pinnedIosMinorVersion';
argParser
..addOption('version',
defaultsTo: pinnedIosVersion,
help: 'The version for the iOS operating system the iOS Simulator '
'will use for tests. For example for testing with iOS 13.2, '
'use `13.2`. Use command: '
'`xcrun simctl list runtimes` to list available versions. Use '
'XCode to install more versions: Xcode > Preferences > Components'
'If this value is not filled version locked in the '
'browser_lock.yaml file will be user.')
..addOption('device',
defaultsTo: _pinnedIosDevice,
help: 'The device to be used for the iOS Simulator during the tests. '
'Use `.` instead of space for separating the words. '
'Common examples: iPhone.8, iPhone.8.Plus, iPhone.11, '
'iPhone 11 Pro. Use command: '
'`xcrun simctl list devices` for listing the available '
'devices. If this value is not filled device locked in the '
'browser_lock.yaml file will be user.');
}
@override
void parseOptions(ArgResults argResults) {
final String iosVersion = argResults['version'] as String;
// The version will contain major and minor version separated by a comma,
// for example: 13.1, 12.2
assert(iosVersion.split('.').length == 2,
'The version should be in format 13.5');
_iosMajorVersion = int.parse(iosVersion.split('.')[0]);
_iosMinorVersion = int.parse(iosVersion.split('.')[1]);
_iosDevice = (argResults['device'] as String).replaceAll('.', ' ');
if (!simulator.booted) {
await simulator.boot();
print('INFO: Simulator ${simulator.id} booted.');
cleanupCallbacks.add(() async {
await simulator.shutdown();
print('INFO: Simulator ${simulator.id} shutdown.');
});
}
}
@@ -181,10 +69,7 @@ class IosSafariArgParser extends BrowserArgParser {
/// Latest Safari version for Catalina, Mojave, High Siera is 13.
///
/// Latest Safari version for Sierra is 12.
// TODO(yjbanov): user latest version to download and install the latest
// technology preview.
Future<BrowserInstallation> getOrInstallSafari(
String requestedVersion, {
Future<BrowserInstallation> getOrInstallSafari({
StringSink? infoLog,
}) async {
// These tests are aimed to run only on macOS machines local or on LUCI.
@@ -195,16 +80,11 @@ Future<BrowserInstallation> getOrInstallSafari(
infoLog ??= io.stdout;
if (requestedVersion == 'system') {
// Since Safari is included in macOS, always assume there will be one on the
// system.
infoLog.writeln('Using the system version that is already installed.');
return BrowserInstallation(
version: 'system',
executable: PlatformBinding.instance.getMacApplicationLauncher(),
);
} else {
infoLog.writeln('Unsupported version $requestedVersion.');
throw UnimplementedError();
}
// Since Safari is included in macOS, always assume there will be one on the
// system.
infoLog.writeln('Using the system version that is already installed.');
return BrowserInstallation(
version: 'system',
executable: PlatformBinding.instance.getMacApplicationLauncher(),
);
}

View File

@@ -9,10 +9,9 @@ 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:yaml/yaml.dart';
import 'browser.dart';
import 'common.dart';
import 'browser_lock.dart';
import 'environment.dart';
import 'safari_installation.dart';
import 'utils.dart';
@@ -30,7 +29,7 @@ class SafariIosEnvironment implements BrowserEnvironment {
@override
Future<void> prepareEnvironment() async {
await IosSafariArgParser.instance.initIosSimulator();
await initIosSimulator();
}
@override
@@ -83,10 +82,10 @@ class SafariIosScreenshotManager extends ScreenshotManager {
String get filenameSuffix => '.iOS_Safari';
SafariIosScreenshotManager() {
final YamlMap browserLock = BrowserLock.instance.configuration;
_heightOfHeader = browserLock['ios-safari']['heightOfHeader'] as int;
_heightOfFooter = browserLock['ios-safari']['heightOfFooter'] as int;
_scaleFactor = browserLock['ios-safari']['scaleFactor'] as double;
final SafariIosLock lock = browserLock.safariIosLock;
_heightOfHeader = lock.heightOfHeader;
_heightOfFooter = lock.heightOfFooter;
_scaleFactor = lock.scaleFactor;
/// Create the directory to use for taking screenshots, if it does not
/// exists.
@@ -160,8 +159,9 @@ class SafariIosScreenshotManager extends ScreenshotManager {
final String filename = 'screenshot$_fileNameCounter.png';
_fileNameCounter++;
await IosSafariArgParser.instance.iosSimulator.takeScreenshot(
filename, environment.webUiSimulatorScreenshotsDirectory);
await iosSimulator.takeScreenshot(
filename, environment.webUiSimulatorScreenshotsDirectory,
);
final io.File file = io.File(path.join(
environment.webUiSimulatorScreenshotsDirectory.path, filename));

View File

@@ -0,0 +1,226 @@
// 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:io' as io;
import 'package:path/path.dart' as pathlib;
import 'package:pool/pool.dart';
import 'package:web_test_utils/goldens.dart';
import '../environment.dart';
import '../exceptions.dart';
import '../utils.dart';
import '../watcher.dart';
/// Compiles web tests and their dependencies.
///
/// Includes:
/// * compile the test code itself
/// * compile the page that hosts the tests
/// * fetch the golden repo for screenshot comparison
class CompileTestsStep implements PipelineStep {
CompileTestsStep({
this.skipGoldensRepoFetch = false,
this.testFiles,
});
final bool skipGoldensRepoFetch;
final List<FilePath>? testFiles;
@override
String get description => 'compile_tests';
@override
bool get isSafeToInterrupt => true;
@override
Future<void> interrupt() async {
await cleanup();
}
@override
Future<void> run() async {
if (!skipGoldensRepoFetch) {
await fetchGoldensRepo();
}
await buildHostPage();
await compileTests(testFiles ?? findAllTests());
}
}
/// Compiles the specified unit tests.
Future<void> compileTests(List<FilePath> testFiles) async {
final Stopwatch stopwatch = Stopwatch()..start();
// Separate HTML targets from CanvasKit targets because the two use
// different dart2js options.
final List<FilePath> htmlTargets = <FilePath>[];
final List<FilePath> canvasKitTargets = <FilePath>[];
final String canvasKitTestDirectory =
pathlib.join(environment.webUiTestDir.path, 'canvaskit');
for (final FilePath testFile in testFiles) {
if (pathlib.isWithin(canvasKitTestDirectory, testFile.absolute)) {
canvasKitTargets.add(testFile);
} else {
htmlTargets.add(testFile);
}
}
await Future.wait(<Future<void>>[
if (htmlTargets.isNotEmpty)
_compileTestsInParallel(targets: htmlTargets, forCanvasKit: false),
if (canvasKitTargets.isNotEmpty)
_compileTestsInParallel(targets: canvasKitTargets, forCanvasKit: true),
]);
stopwatch.stop();
final int targetCount = htmlTargets.length + canvasKitTargets.length;
print(
'Built $targetCount tests in ${stopwatch.elapsedMilliseconds ~/ 1000} '
'seconds using $_dart2jsConcurrency concurrent dart2js processes.',
);
}
// Maximum number of concurrent dart2js processes to use.
const int _dart2jsConcurrency = int.fromEnvironment('FELT_DART2JS_CONCURRENCY', defaultValue: 8);
final Pool _dart2jsPool = Pool(_dart2jsConcurrency);
/// Spawns multiple dart2js processes to compile [targets] in parallel.
Future<void> _compileTestsInParallel({
required List<FilePath> targets,
required bool forCanvasKit,
}) async {
final Stream<bool> results = _dart2jsPool.forEach(
targets,
(FilePath file) => compileUnitTest(file, forCanvasKit: forCanvasKit),
);
await for (final bool isSuccess in results) {
if (!isSuccess) {
throw ToolExit('Failed to compile tests.');
}
}
}
/// Compiles one unit test using `dart2js`.
///
/// When building for CanvasKit we have to use extra argument
/// `DFLUTTER_WEB_USE_SKIA=true`.
///
/// Dart2js creates the following outputs:
/// - target.browser_test.dart.js
/// - target.browser_test.dart.js.deps
/// - target.browser_test.dart.js.maps
/// under the same directory with test file. If all these files are not in
/// the same directory, Chrome dev tools cannot load the source code during
/// debug.
///
/// All the files under test already copied from /test directory to /build
/// directory before test are build. See [_copyFilesFromTestToBuild].
///
/// Later the extra files will be deleted in [_cleanupExtraFilesUnderTestDir].
Future<bool> compileUnitTest(FilePath input, { required bool forCanvasKit }) async {
final String targetFileName = pathlib.join(
environment.webUiBuildDir.path,
'${input.relativeToWebUi}.browser_test.dart.js',
);
final io.Directory directoryToTarget = io.Directory(pathlib.join(
environment.webUiBuildDir.path,
pathlib.dirname(input.relativeToWebUi)));
if (!directoryToTarget.existsSync()) {
directoryToTarget.createSync(recursive: true);
}
final List<String> arguments = <String>[
'--no-minify',
'--disable-inlining',
'--enable-asserts',
'--enable-experiment=non-nullable',
'--no-sound-null-safety',
// We do not want to auto-select a renderer in tests. As of today, tests
// are designed to run in one specific mode. So instead, we specify the
// renderer explicitly.
'-DFLUTTER_WEB_AUTO_DETECT=false',
'-DFLUTTER_WEB_USE_SKIA=$forCanvasKit',
'-O2',
'-o',
targetFileName, // target path.
input.relativeToWebUi, // current path.
];
final int exitCode = await runProcess(
environment.dart2jsExecutable,
arguments,
workingDirectory: environment.webUiRootDir.path,
);
if (exitCode != 0) {
io.stderr.writeln('ERROR: Failed to compile test $input. '
'Dart2js exited with exit code $exitCode');
return false;
} else {
return true;
}
}
Future<void> buildHostPage() async {
final String hostDartPath = pathlib.join('lib', 'static', 'host.dart');
final io.File hostDartFile = io.File(pathlib.join(
environment.webEngineTesterRootDir.path,
hostDartPath,
));
final io.File timestampFile = io.File(pathlib.join(
environment.webEngineTesterRootDir.path,
'$hostDartPath.js.timestamp',
));
final String timestamp =
hostDartFile.statSync().modified.millisecondsSinceEpoch.toString();
if (timestampFile.existsSync()) {
final String lastBuildTimestamp = timestampFile.readAsStringSync();
if (lastBuildTimestamp == timestamp) {
// The file is still fresh. No need to rebuild.
return;
} else {
// Record new timestamp, but don't return. We need to rebuild.
print('${hostDartFile.path} timestamp changed. Rebuilding.');
}
} else {
print('Building ${hostDartFile.path}.');
}
final int exitCode = await runProcess(
environment.dart2jsExecutable,
<String>[
hostDartPath,
'-o',
'$hostDartPath.js',
],
workingDirectory: environment.webEngineTesterRootDir.path,
);
if (exitCode != 0) {
throw ToolExit(
'Failed to compile ${hostDartFile.path}. Compiler '
'exited with exit code $exitCode',
exitCode: exitCode,
);
}
// Record the timestamp to avoid rebuilding unless the file changes.
timestampFile.writeAsStringSync(timestamp);
}
Future<void> fetchGoldensRepo() async {
print('INFO: Fetching goldens repo');
final GoldensRepoFetcher goldensRepoFetcher = GoldensRepoFetcher(
environment.webUiGoldensRepositoryDirectory,
pathlib.join(environment.webUiDevDir.path, 'goldens_lock.yaml'));
await goldensRepoFetcher.fetch();
}

View File

@@ -0,0 +1,291 @@
// 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:io' as io;
import 'package:path/path.dart' as pathlib;
// TODO(yjbanov): remove hacks when this is fixed:
// https://github.com/dart-lang/test/issues/1521
import 'package:test_api/src/backend/group.dart' as hack;
import 'package:test_api/src/backend/live_test.dart' as hack;
import 'package:test_api/src/backend/runtime.dart' as hack;
import 'package:test_core/src/executable.dart' as test;
import 'package:test_core/src/runner/configuration/reporters.dart' as hack;
import 'package:test_core/src/runner/engine.dart' as hack;
import 'package:test_core/src/runner/hack_register_platform.dart' as hack;
import 'package:test_core/src/runner/reporter.dart' as hack;
import '../browser.dart';
import '../environment.dart';
import '../exceptions.dart';
import '../test_platform.dart';
import '../utils.dart';
import '../watcher.dart';
// Maximum number of tests that run concurrently.
const int _testConcurrency = int.fromEnvironment('FELT_TEST_CONCURRENCY', defaultValue: 10);
/// Runs web tests.
///
/// Assumes the artifacts from [CompileTestsStep] are available, either from
/// running it prior to this step locally, or by having the build graph copy
/// them from another bot.
class RunTestsStep implements PipelineStep {
RunTestsStep({
required this.browserEnvironment,
required this.isDebug,
required this.doUpdateScreenshotGoldens,
this.testFiles,
});
final BrowserEnvironment browserEnvironment;
final List<FilePath>? testFiles;
final bool isDebug;
final bool doUpdateScreenshotGoldens;
/// Global list of shards that failed.
///
/// This is used to make sure that when there's a test failure anywhere we
/// exit with a non-zero exit code.
///
/// Shards must never be removed from this list, only added.
List<String> failedShards = <String>[];
/// Whether all test shards succeeded.
bool get allShardsPassed => failedShards.isEmpty;
@override
String get description => 'run_tests';
@override
bool get isSafeToInterrupt => true;
@override
Future<void> interrupt() async {}
@override
Future<void> run() async {
_copyTestFontsIntoWebUi();
await _prepareTestResultsDirectory();
await browserEnvironment.prepareEnvironment();
final List<FilePath> testFiles = this.testFiles ?? findAllTests();
// Separate screenshot tests from unit-tests. Screenshot tests must run
// one at a time. Otherwise, they will end up screenshotting each other.
// This is not an issue for unit-tests.
final FilePath failureSmokeTestPath = FilePath.fromWebUi(
'test/golden_tests/golden_failure_smoke_test.dart',
);
final List<FilePath> screenshotTestFiles = <FilePath>[];
final List<FilePath> unitTestFiles = <FilePath>[];
for (final FilePath testFilePath in testFiles) {
if (!testFilePath.absolute.endsWith('_test.dart')) {
// Not a test file at all. Skip.
continue;
}
if (testFilePath == failureSmokeTestPath) {
// A smoke test that fails on purpose. Skip.
continue;
}
// All files under test/golden_tests are considered golden tests.
final bool isUnderGoldenTestsDirectory =
pathlib.split(testFilePath.relativeToWebUi).contains('golden_tests');
// Any file whose name ends with "_golden_test.dart" is run as a golden test.
final bool isGoldenTestFile = pathlib
.basename(testFilePath.relativeToWebUi)
.endsWith('_golden_test.dart');
if (isUnderGoldenTestsDirectory || isGoldenTestFile) {
screenshotTestFiles.add(testFilePath);
} else {
unitTestFiles.add(testFilePath);
}
}
// This test returns a non-zero exit code on purpose. Run it separately.
if (testFiles.contains(failureSmokeTestPath)) {
await _runTestBatch(
testFiles: <FilePath>[failureSmokeTestPath],
browserEnvironment: browserEnvironment,
concurrency: 1,
expectFailure: true,
isDebug: isDebug,
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
);
}
// Run all unit-tests as a single batch and with high concurrency.
if (unitTestFiles.isNotEmpty) {
await _runTestBatch(
testFiles: unitTestFiles,
browserEnvironment: browserEnvironment,
concurrency: _testConcurrency,
expectFailure: false,
isDebug: isDebug,
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
);
_checkExitCode('Unit tests');
}
// Run screenshot tests one at a time. Otherwise, tests end up
// screenshotting each other.
for (final FilePath screenshotTestFilePath in screenshotTestFiles) {
await _runTestBatch(
testFiles: <FilePath>[screenshotTestFilePath],
browserEnvironment: browserEnvironment,
concurrency: 1,
expectFailure: false,
isDebug: isDebug,
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
);
_checkExitCode('Golden tests');
}
if (!allShardsPassed) {
throw ToolExit(_createFailedShardsMessage());
}
}
void _checkExitCode(String shard) {
if (io.exitCode != 0) {
failedShards.add(shard);
}
}
String _createFailedShardsMessage() {
final StringBuffer message = StringBuffer(
'The following test shards failed:\n',
);
for (final String failedShard in failedShards) {
message.writeln(' - $failedShard');
}
return message.toString();
}
}
Future<void> _prepareTestResultsDirectory() async {
if (environment.webUiTestResultsDirectory.existsSync()) {
environment.webUiTestResultsDirectory.deleteSync(recursive: true);
}
environment.webUiTestResultsDirectory.createSync(recursive: true);
}
const List<String> _kTestFonts = <String>[
'ahem.ttf',
'Roboto-Regular.ttf',
'NotoNaskhArabic-Regular.ttf',
'NotoColorEmoji.ttf',
];
void _copyTestFontsIntoWebUi() {
final String fontsPath = pathlib.join(
environment.flutterDirectory.path,
'third_party',
'txt',
'third_party',
'fonts',
);
for (final String fontFile in _kTestFonts) {
final io.File sourceTtf = io.File(pathlib.join(fontsPath, fontFile));
final String destinationTtfPath =
pathlib.join(environment.webUiRootDir.path, 'lib', 'assets', fontFile);
sourceTtf.copySync(destinationTtfPath);
}
}
/// Runs a batch of tests.
///
/// Unless [expectFailure] is set to false, sets [io.exitCode] to a non-zero
/// value if any tests fail.
Future<void> _runTestBatch({
required List<FilePath> testFiles,
required bool isDebug,
required BrowserEnvironment browserEnvironment,
required bool doUpdateScreenshotGoldens,
required int concurrency,
required bool expectFailure,
}) async {
final String configurationFilePath = pathlib.join(
environment.webUiRootDir.path,
browserEnvironment.packageTestConfigurationYamlFile,
);
final List<String> testArgs = <String>[
...<String>['-r', 'compact'],
'--concurrency=$concurrency',
if (isDebug) '--pause-after-load',
// Don't pollute logs with output from tests that are expected to fail.
if (expectFailure)
'--reporter=name-only',
'--platform=${browserEnvironment.packageTestRuntime.identifier}',
'--precompiled=${environment.webUiBuildDir.path}',
'--configuration=$configurationFilePath',
'--',
...testFiles.map((FilePath f) => f.relativeToWebUi).toList(),
];
if (expectFailure) {
hack.registerReporter(
'name-only',
hack.ReporterDetails(
'Prints the name of the test, but suppresses all other test output.',
(_, hack.Engine engine, __) => NameOnlyReporter(engine)),
);
}
hack.registerPlatformPlugin(<hack.Runtime>[
browserEnvironment.packageTestRuntime,
], () {
return BrowserPlatform.start(
browserEnvironment: browserEnvironment,
// It doesn't make sense to update a screenshot for a test that is
// expected to fail.
doUpdateScreenshotGoldens: !expectFailure && doUpdateScreenshotGoldens,
);
});
// We want to run tests with `web_ui` as a working directory.
final dynamic originalCwd = io.Directory.current;
io.Directory.current = environment.webUiRootDir.path;
try {
await test.main(testArgs);
} finally {
io.Directory.current = originalCwd;
}
if (expectFailure) {
if (io.exitCode != 0) {
// It failed, as expected.
print('Test successfully failed, as expected.');
io.exitCode = 0;
} else {
io.stderr.writeln(
'Tests ${testFiles.join(', ')} did not fail. Expected failure.',
);
io.exitCode = 1;
}
}
}
/// Prints the name of the test, but suppresses all other test output.
///
/// This is useful to prevent pollution of logs by tests that are expected to
/// fail.
class NameOnlyReporter implements hack.Reporter {
NameOnlyReporter(hack.Engine testEngine) {
testEngine.onTestStarted.listen(_printTestName);
}
void _printTestName(hack.LiveTest test) {
print('Running ${test.groups.map((hack.Group group) => group.name).join(' ')} ${test.individualName}');
}
@override
void pause() {}
@override
void resume() {}
}

View File

@@ -88,7 +88,7 @@ class BrowserPlatform extends PlatformPlugin {
/// Handles taking screenshots during tests.
///
/// Implementation will differ depending on the browser.
ScreenshotManager? _screenshotManager;
final ScreenshotManager? _screenshotManager;
/// Whether [close] has been called.
bool get _closed => _closeMemo.hasRun;
@@ -107,9 +107,9 @@ class BrowserPlatform extends PlatformPlugin {
required String faviconPath,
required this.doUpdateScreenshotGoldens,
required this.packageConfig,
}) {
}) : _screenshotManager = browserEnvironment.getScreenshotManager() {
// The cascade of request handlers.
shelf.Cascade cascade = shelf.Cascade()
final shelf.Cascade cascade = shelf.Cascade()
// The web socket that carries the test channels for running tests and
// reporting restuls. See [_browserManagerFor] and [BrowserManager.start]
// for details on how the channels are established.
@@ -148,12 +148,8 @@ 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());
_screenshotManager = browserEnvironment.getScreenshotManager();
if (_screenshotManager != null) {
cascade = cascade.add(_screeshotHandler);
}
.add(_createAbsolutePackageUrlHandler())
.add(_screeshotHandler);
server.mount(cascade.handler);
}
@@ -242,6 +238,15 @@ class BrowserPlatform extends PlatformPlugin {
final Map<String, dynamic> requestData =
json.decode(payload) as Map<String, dynamic>;
final String filename = requestData['filename'] as String;
if (_screenshotManager == null) {
print(
'INFO: Skipping screenshot check for $filename. Current browser/OS '
'combination does not support screenshots.',
);
return shelf.Response.ok(json.encode('OK'));
}
final bool write = requestData['write'] as bool;
final double maxDiffRate = requestData.containsKey('maxdiffrate')
? (requestData['maxdiffrate'] as num)

View File

@@ -7,78 +7,16 @@ import 'dart:io' as io;
import 'package:args/command_runner.dart';
import 'package:path/path.dart' as path;
import 'package:pool/pool.dart';
// TODO(yjbanov): remove hacks when this is fixed:
// https://github.com/dart-lang/test/issues/1521
import 'package:test_api/src/backend/group.dart'
as hack;
import 'package:test_api/src/backend/live_test.dart'
as hack;
import 'package:test_api/src/backend/runtime.dart';
import 'package:test_core/src/executable.dart'
as test;
import 'package:test_core/src/runner/configuration/reporters.dart'
as hack;
import 'package:test_core/src/runner/engine.dart'
as hack;
import 'package:test_core/src/runner/hack_register_platform.dart'
as hack;
import 'package:test_core/src/runner/reporter.dart'
as hack;
import 'package:watcher/src/watch_event.dart';
import 'package:web_test_utils/goldens.dart';
import 'browser.dart';
import 'chrome.dart';
import 'chrome_installer.dart';
import 'common.dart';
import 'edge.dart';
import 'edge_installation.dart';
import 'environment.dart';
import 'exceptions.dart';
import 'firefox.dart';
import 'firefox_installer.dart';
import 'safari_installation.dart';
import 'safari_ios.dart';
import 'safari_macos.dart';
import 'test_platform.dart';
import 'steps/compile_tests_step.dart';
import 'steps/run_tests_step.dart';
import 'utils.dart';
import 'watcher.dart';
/// Global list of shards that failed.
///
/// This is used to make sure that when there's a test failure anywhere we
/// exit with a non-zero exit code.
///
/// Shards must never be removed from this list, only added.
List<String> failedShards = <String>[];
/// Whether all test shards succeeded.
bool get allShardsPassed => failedShards.isEmpty;
/// Command-line argument parsers that parse browser-specific options.
final List<BrowserArgParser> _browserArgParsers = <BrowserArgParser>[
ChromeArgParser.instance,
EdgeArgParser.instance,
FirefoxArgParser.instance,
SafariArgParser.instance,
];
/// Creates an environment for a browser.
///
/// The [browserName] matches the browser name passed as the `--browser` option.
BrowserEnvironment _createBrowserEnvironment(String browserName) {
switch (browserName) {
case 'chrome': return ChromeEnvironment();
case 'edge': return EdgeEnvironment();
case 'firefox': return FirefoxEnvironment();
case 'safari': return SafariMacOsEnvironment();
case 'ios-safari': return SafariIosEnvironment();
}
throw UnsupportedError('Browser $browserName is not supported.');
}
/// Runs tests.
class TestCommand extends Command<bool> with ArgUtils<bool> {
TestCommand() {
@@ -145,11 +83,6 @@ class TestCommand extends Command<bool> with ArgUtils<bool> {
'test despite failures and will report them after all tests '
'finish.',
);
for (final BrowserArgParser browserArgParser in _browserArgParsers) {
browserArgParser.populateOptions(argParser);
}
GeneralTestsArgumentParser.instance.populateOptions(argParser);
}
@override
@@ -158,30 +91,55 @@ class TestCommand extends Command<bool> with ArgUtils<bool> {
@override
final String description = 'Run tests.';
bool get isWatchMode => boolArg('watch')!;
bool get isWatchMode => boolArg('watch');
bool get failEarly => boolArg('fail-early')!;
bool get failEarly => boolArg('fail-early');
/// How many dart2js build tasks are running at the same time.
final Pool _pool = Pool(8);
/// Whether test harness preparation (such as fetching the goldens,
/// creating test_results directory or starting ios-simulator) has been done.
/// Whether to start the browser in debug mode.
///
/// If unit tests already did these steps, integration tests do not have to
/// repeat them.
bool _testPreparationReady = false;
/// In this mode the browser pauses before running the test to allow
/// you set breakpoints or inspect the code.
bool get isDebug => boolArg('debug');
/// Paths to targets to run, e.g. a single test.
List<String> get targets => argResults!.rest;
/// The target test files to run.
List<FilePath> get targetFiles => targets.map((String t) => FilePath.fromCwd(t)).toList();
/// Whether all tests should run.
bool get runAllTests => targets.isEmpty;
/// The name of the browser to run tests in.
String get browser => stringArg('browser');
/// When running screenshot tests writes them to the file system into
/// ".dart_tool/goldens".
bool get doUpdateScreenshotGoldens => boolArg('update-screenshot-goldens');
/// Whether to fetch the goldens repo prior to running tests.
bool get skipGoldensRepoFetch => boolArg('skip-goldens-repo-fetch');
@override
Future<bool> run() async {
for (final BrowserArgParser browserArgParser in _browserArgParsers) {
browserArgParser.parseOptions(argResults!);
}
GeneralTestsArgumentParser.instance.parseOptions(argResults!);
final BrowserEnvironment browserEnvironment = getBrowserEnvironment(browser);
final List<FilePath> testFiles = runAllTests
? findAllTests()
: targetFiles;
final Pipeline testPipeline = Pipeline(steps: <PipelineStep>[
if (isWatchMode) ClearTerminalScreenStep(),
TestRunnerStep(this),
CompileTestsStep(
skipGoldensRepoFetch: skipGoldensRepoFetch,
testFiles: testFiles,
),
RunTestsStep(
browserEnvironment: browserEnvironment,
testFiles: testFiles,
isDebug: isDebug,
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
),
]);
await testPipeline.run();
@@ -212,551 +170,9 @@ class TestCommand extends Command<bool> with ArgUtils<bool> {
// Ignore anything else.
return true;
}).start();
return true;
} else {
if (!allShardsPassed) {
io.stderr.writeln(_createFailedShardsMessage());
}
return allShardsPassed;
}
return true;
}
String _createFailedShardsMessage() {
final StringBuffer message = StringBuffer(
'The following test shards failed:\n',
);
for (final String failedShard in failedShards) {
message.writeln(' - $failedShard');
}
return message.toString();
}
Future<void> runUnitTests() async {
_copyTestFontsIntoWebUi();
await _buildHostPage();
await _prepare();
await _buildTargets();
if (runAllTests) {
await _runAllTestsForCurrentPlatform();
} else {
await _runSpecificTests(targetFiles);
}
}
/// Preparations before running the tests such as booting simulators or
/// creating directories.
Future<void> _prepare() async {
if (_testPreparationReady) {
return;
}
if (environment.webUiTestResultsDirectory.existsSync()) {
environment.webUiTestResultsDirectory.deleteSync(recursive: true);
}
environment.webUiTestResultsDirectory.createSync(recursive: true);
// If screenshot tests are available, fetch the screenshot goldens.
if (isScreenshotTestsAvailable && !skipGoldensRepoFetch) {
if (isVerboseLoggingEnabled) {
print('INFO: Fetching goldens repo');
}
final GoldensRepoFetcher goldensRepoFetcher = GoldensRepoFetcher(
environment.webUiGoldensRepositoryDirectory,
path.join(environment.webUiDevDir.path, 'goldens_lock.yaml'));
await goldensRepoFetcher.fetch();
}
await browserEnvironment.prepareEnvironment();
_testPreparationReady = true;
}
/// Builds all test targets that will be run.
Future<void> _buildTargets() async {
final Stopwatch stopwatch = Stopwatch()..start();
List<FilePath> allTargets;
if (runAllTests) {
allTargets = environment.webUiTestDir
.listSync(recursive: true)
.whereType<io.File>()
.where((io.File f) => f.path.endsWith('_test.dart'))
.map<FilePath>((io.File f) => FilePath.fromWebUi(
path.relative(f.path, from: environment.webUiRootDir.path)))
.toList();
} else {
allTargets = targetFiles;
}
// Separate HTML targets from CanvasKit targets because the two use
// different dart2js options.
final List<FilePath> htmlTargets = <FilePath>[];
final List<FilePath> canvasKitTargets = <FilePath>[];
final String canvasKitTestDirectory =
path.join(environment.webUiTestDir.path, 'canvaskit');
for (final FilePath target in allTargets) {
if (path.isWithin(canvasKitTestDirectory, target.absolute)) {
canvasKitTargets.add(target);
} else {
htmlTargets.add(target);
}
}
if (htmlTargets.isNotEmpty) {
await _buildTestsInParallel(targets: htmlTargets, forCanvasKit: false);
}
// Currently iOS Safari tests are running on simulator, which does not
// support canvaskit backend.
if (canvasKitTargets.isNotEmpty) {
await _buildTestsInParallel(
targets: canvasKitTargets, forCanvasKit: true);
}
stopwatch.stop();
print('The build took ${stopwatch.elapsedMilliseconds ~/ 1000} seconds.');
}
/// Whether to start the browser in debug mode.
///
/// In this mode the browser pauses before running the test to allow
/// you set breakpoints or inspect the code.
bool get isDebug => boolArg('debug')!;
/// Paths to targets to run, e.g. a single test.
List<String> get targets => argResults!.rest;
/// The target test files to run.
List<FilePath> get targetFiles => targets.map((String t) => FilePath.fromCwd(t)).toList();
/// Whether all tests should run.
bool get runAllTests => targets.isEmpty;
/// The name of the browser to run tests in.
String get browser => stringArg('browser')!;
/// The browser environment for the [browser].
BrowserEnvironment get browserEnvironment => _browserEnvironment ??= _createBrowserEnvironment(browser);
BrowserEnvironment? _browserEnvironment;
/// Whether [browser] is set to "chrome".
bool get isChrome => browser == 'chrome';
/// Whether [browser] is set to "firefox".
bool get isFirefox => browser == 'firefox';
/// Whether [browser] is set to "safari".
bool get isSafariOnMacOS => browser == 'safari' && io.Platform.isMacOS;
/// Whether [browser] is set to "ios-safari".
bool get isSafariIOS => browser == 'ios-safari' && io.Platform.isMacOS;
/// Due to lack of resources Chrome integration tests only run on Linux on
/// LUCI.
///
/// They run on all platforms for local.
bool get isChromeIntegrationTestAvailable =>
(isChrome && isLuci && io.Platform.isLinux) || (isChrome && !isLuci);
/// Due to efficiency constraints, Firefox integration tests only run on
/// Linux on LUCI.
///
/// For now Firefox integration tests only run on Linux and Mac on local.
///
// TODO(yjbanov): https://github.com/flutter/flutter/issues/63832
bool get isFirefoxIntegrationTestAvailable =>
(isFirefox && isLuci && io.Platform.isLinux) ||
(isFirefox && !isLuci && !io.Platform.isWindows);
/// Latest versions of Safari Desktop are only available on macOS.
///
/// Integration testing on LUCI is not supported at the moment.
// TODO(yjbanov): https://github.com/flutter/flutter/issues/63710
bool get isSafariIntegrationTestAvailable => isSafariOnMacOS && !isLuci;
/// Due to various factors integration tests might be missing on a given
/// platform and given environment.
/// See: [isChromeIntegrationTestAvailable]
/// See: [isSafariIntegrationTestAvailable]
/// See: [isFirefoxIntegrationTestAvailable]
bool get isIntegrationTestsAvailable =>
isChromeIntegrationTestAvailable ||
isFirefoxIntegrationTestAvailable ||
isSafariIntegrationTestAvailable;
// Whether the tests will do screenshot testing.
bool get isScreenshotTestsAvailable =>
isIntegrationTestsAvailable || isUnitTestsScreenshotsAvailable;
// For unit tests screenshot tests and smoke tests only run on:
// "Chrome/iOS" for LUCI/local.
bool get isUnitTestsScreenshotsAvailable =>
isChrome && (io.Platform.isLinux || !isLuci) || isSafariIOS;
/// Use system flutter instead of cloning the repository.
///
/// Read the flag help for more details. Uses PATH to locate flutter.
bool get useSystemFlutter => boolArg('use-system-flutter')!;
/// When running screenshot tests writes them to the file system into
/// ".dart_tool/goldens".
bool get doUpdateScreenshotGoldens => boolArg('update-screenshot-goldens')!;
/// Whether to fetch the goldens repo prior to running tests.
bool get skipGoldensRepoFetch => boolArg('skip-goldens-repo-fetch')!;
/// Runs all tests specified in [targets].
///
/// Unlike [_runAllTestsForCurrentPlatform], this does not filter targets
/// by platform/browser capabilities, and instead attempts to run all of
/// them.
Future<void> _runSpecificTests(List<FilePath> targets) async {
await _runTestBatch(targets, concurrency: 1, expectFailure: false);
_checkExitCode(
'Some of the following tests: ' +
targets.map((FilePath path) => path.relativeToWebUi).join(', '),
);
}
/// Runs as many tests as possible on the current OS/browser combination.
Future<void> _runAllTestsForCurrentPlatform() async {
final io.Directory testDir = io.Directory(path.join(
environment.webUiRootDir.path,
'test',
));
// Separate screenshot tests from unit-tests. Screenshot tests must run
// one at a time. Otherwise, they will end up screenshotting each other.
// This is not an issue for unit-tests.
final FilePath failureSmokeTestPath = FilePath.fromWebUi(
'test/golden_tests/golden_failure_smoke_test.dart',
);
final List<FilePath> screenshotTestFiles = <FilePath>[];
final List<FilePath> unitTestFiles = <FilePath>[];
for (final io.File testFile
in testDir.listSync(recursive: true).whereType<io.File>()) {
final FilePath testFilePath = FilePath.fromCwd(testFile.path);
if (!testFilePath.absolute.endsWith('_test.dart')) {
// Not a test file at all. Skip.
continue;
}
if (testFilePath == failureSmokeTestPath) {
// A smoke test that fails on purpose. Skip.
continue;
}
// All files under test/golden_tests are considered golden tests.
final bool isUnderGoldenTestsDirectory =
path.split(testFilePath.relativeToWebUi).contains('golden_tests');
// Any file whose name ends with "_golden_test.dart" is run as a golden test.
final bool isGoldenTestFile = path
.basename(testFilePath.relativeToWebUi)
.endsWith('_golden_test.dart');
if (isUnderGoldenTestsDirectory || isGoldenTestFile) {
screenshotTestFiles.add(testFilePath);
} else {
unitTestFiles.add(testFilePath);
}
}
if (isUnitTestsScreenshotsAvailable) {
// This test returns a non-zero exit code on purpose. Run it separately.
if (io.Platform.environment['CIRRUS_CI'] != 'true') {
await _runTestBatch(
<FilePath>[failureSmokeTestPath],
concurrency: 1,
expectFailure: true,
);
_checkExitCode('Smoke test');
}
}
// Run all unit-tests as a single batch.
await _runTestBatch(unitTestFiles, concurrency: 10, expectFailure: false);
_checkExitCode('Unit tests');
if (isUnitTestsScreenshotsAvailable) {
// Run screenshot tests one at a time.
for (final FilePath testFilePath in screenshotTestFiles) {
await _runTestBatch(
<FilePath>[testFilePath],
concurrency: 1,
expectFailure: false,
);
_checkExitCode('Golden tests');
}
}
}
void _checkExitCode(String shard) {
if (io.exitCode != 0) {
if (isWatchMode) {
io.exitCode = 0;
throw TestFailureException();
} else {
failedShards.add(shard);
if (failEarly) {
throw ToolException(_createFailedShardsMessage());
}
}
}
}
Future<void> _buildHostPage() async {
final String hostDartPath = path.join('lib', 'static', 'host.dart');
final io.File hostDartFile = io.File(path.join(
environment.webEngineTesterRootDir.path,
hostDartPath,
));
final io.File timestampFile = io.File(path.join(
environment.webEngineTesterRootDir.path,
'$hostDartPath.js.timestamp',
));
final String timestamp =
hostDartFile.statSync().modified.millisecondsSinceEpoch.toString();
if (timestampFile.existsSync()) {
final String lastBuildTimestamp = timestampFile.readAsStringSync();
if (lastBuildTimestamp == timestamp) {
// The file is still fresh. No need to rebuild.
return;
} else {
// Record new timestamp, but don't return. We need to rebuild.
print('${hostDartFile.path} timestamp changed. Rebuilding.');
}
} else {
print('Building ${hostDartFile.path}.');
}
final int exitCode = await runProcess(
environment.dart2jsExecutable,
<String>[
hostDartPath,
'-o',
'$hostDartPath.js',
],
workingDirectory: environment.webEngineTesterRootDir.path,
);
if (exitCode != 0) {
throw ToolException('Failed to compile ${hostDartFile.path}. Compiler '
'exited with exit code $exitCode');
}
// Record the timestamp to avoid rebuilding unless the file changes.
timestampFile.writeAsStringSync(timestamp);
}
Future<void> _buildTestsInParallel({
required List<FilePath> targets,
bool forCanvasKit = false,
}) async {
final List<TestBuildInput> buildInputs = targets
.map((FilePath f) => TestBuildInput(f, forCanvasKit: forCanvasKit))
.toList();
final Stream<bool> results = _pool.forEach(
buildInputs,
_buildTest,
);
await for (final bool isSuccess in results) {
if (!isSuccess) {
throw ToolException('Failed to compile tests.');
}
}
}
/// Compiles one test using `dart2js`.
///
/// When building for CanvasKit we have to use extra argument
/// `DFLUTTER_WEB_USE_SKIA=true`.
///
/// Dart2js creates the following outputs:
/// - target.browser_test.dart.js
/// - target.browser_test.dart.js.deps
/// - target.browser_test.dart.js.maps
/// under the same directory with test file. If all these files are not in
/// the same directory, Chrome dev tools cannot load the source code during
/// debug.
///
/// All the files under test already copied from /test directory to /build
/// directory before test are build. See [_copyFilesFromTestToBuild].
///
/// Later the extra files will be deleted in [_cleanupExtraFilesUnderTestDir].
Future<bool> _buildTest(TestBuildInput input) async {
final String targetFileName = path.join(
environment.webUiBuildDir.path,
'${input.path.relativeToWebUi}.browser_test.dart.js',
);
final io.Directory directoryToTarget = io.Directory(path.join(
environment.webUiBuildDir.path,
path.dirname(input.path.relativeToWebUi)));
if (!directoryToTarget.existsSync()) {
directoryToTarget.createSync(recursive: true);
}
final List<String> arguments = <String>[
'--no-minify',
'--disable-inlining',
'--enable-asserts',
'--no-sound-null-safety',
// We do not want to auto-select a renderer in tests. As of today, tests
// are designed to run in one specific mode. So instead, we specify the
// renderer explicitly.
'-DFLUTTER_WEB_AUTO_DETECT=false',
'-DFLUTTER_WEB_USE_SKIA=${input.forCanvasKit}',
'-O2',
'-o',
targetFileName, // target path.
input.path.relativeToWebUi, // current path.
];
final int exitCode = await runProcess(
environment.dart2jsExecutable,
arguments,
workingDirectory: environment.webUiRootDir.path,
);
if (exitCode != 0) {
io.stderr.writeln('ERROR: Failed to compile test ${input.path}. '
'Dart2js exited with exit code $exitCode');
return false;
} else {
return true;
}
}
/// Runs a batch of tests.
///
/// Unless [expectFailure] is set to false, sets [io.exitCode] to a non-zero
/// value if any tests fail.
Future<void> _runTestBatch(
List<FilePath> testFiles, {
required int concurrency,
required bool expectFailure,
}) async {
final String configurationFilePath = path.join(
environment.webUiRootDir.path,
browserEnvironment.packageTestConfigurationYamlFile,
);
final List<String> testArgs = <String>[
...<String>['-r', 'compact'],
'--concurrency=$concurrency',
if (isDebug) '--pause-after-load',
// Don't pollute logs with output from tests that are expected to fail.
if (expectFailure)
'--reporter=name-only',
'--platform=${browserEnvironment.packageTestRuntime.identifier}',
'--precompiled=${environment.webUiBuildDir.path}',
'--configuration=$configurationFilePath',
'--',
...testFiles.map((FilePath f) => f.relativeToWebUi).toList(),
];
if (expectFailure) {
hack.registerReporter(
'name-only',
hack.ReporterDetails(
'Prints the name of the test, but suppresses all other test output.',
(_, hack.Engine engine, __) => NameOnlyReporter(engine)),
);
}
hack.registerPlatformPlugin(<Runtime>[
browserEnvironment.packageTestRuntime,
], () {
return BrowserPlatform.start(
browserEnvironment: browserEnvironment,
// It doesn't make sense to update a screenshot for a test that is
// expected to fail.
doUpdateScreenshotGoldens: !expectFailure && doUpdateScreenshotGoldens,
);
});
// We want to run tests with `web_ui` as a working directory.
final dynamic originalCwd = io.Directory.current;
io.Directory.current = environment.webUiRootDir.path;
try {
await test.main(testArgs);
} finally {
io.Directory.current = originalCwd;
}
if (expectFailure) {
if (io.exitCode != 0) {
// It failed, as expected.
print('Test successfully failed, as expected.');
io.exitCode = 0;
} else {
io.stderr.writeln(
'Tests ${testFiles.join(', ')} did not fail. Expected failure.',
);
io.exitCode = 1;
}
}
}
}
const List<String> _kTestFonts = <String>[
'ahem.ttf',
'Roboto-Regular.ttf',
'NotoNaskhArabic-Regular.ttf',
'NotoColorEmoji.ttf',
];
void _copyTestFontsIntoWebUi() {
final String fontsPath = path.join(
environment.flutterDirectory.path,
'third_party',
'txt',
'third_party',
'fonts',
);
for (final 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);
sourceTtf.copySync(destinationTtfPath);
}
}
/// Used as an input message to the PoolResources that are building a test.
class TestBuildInput {
/// Test to build.
final FilePath path;
/// Whether these tests should be build for CanvasKit.
///
/// `-DFLUTTER_WEB_USE_SKIA=true` is passed to dart2js for CanvasKit.
final bool forCanvasKit;
TestBuildInput(this.path, {this.forCanvasKit = false});
}
class TestFailureException implements Exception {}
/// Prints the name of the test, but suppresses all other test output.
///
/// This is useful to prevent pollution of logs by tests that are expected to
/// fail.
class NameOnlyReporter implements hack.Reporter {
NameOnlyReporter(hack.Engine testEngine) {
testEngine.onTestStarted.listen(_printTestName);
}
void _printTestName(hack.LiveTest test) {
print('Running ${test.groups.map((hack.Group group) => group.name).join(' ')} ${test.individualName}');
}
@override
void pause() {}
@override
void resume() {}
}
/// Clears the terminal screen and places the cursor at the top left corner.
@@ -764,7 +180,7 @@ class NameOnlyReporter implements hack.Reporter {
/// This works on Linux and Mac. On Windows, it's a no-op.
class ClearTerminalScreenStep implements PipelineStep {
@override
String get name => 'clearing terminal screen';
String get description => 'clearing terminal screen';
@override
bool get isSafeToInterrupt => false;
@@ -780,27 +196,3 @@ class ClearTerminalScreenStep implements PipelineStep {
}
}
}
/// Runs tests by calling [TestCommand.runTests].
class TestRunnerStep implements PipelineStep {
TestRunnerStep(this.testCommand);
TestCommand testCommand;
@override
String get name => 'test runner';
@override
Future<void> interrupt() async {
// Interrupt this step by killing all spawned processes (browsers, web drivers, etc).
cleanup();
}
@override
bool get isSafeToInterrupt => true;
@override
Future<void> run() async {
await testCommand.runUnitTests();
}
}

View File

@@ -6,7 +6,6 @@ import 'dart:async';
import 'dart:convert' show utf8, LineSplitter;
import 'dart:io' as io;
import 'package:args/args.dart';
import 'package:args/command_runner.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
@@ -254,8 +253,11 @@ Future<void> runFlutter(
);
if (exitCode != 0) {
throw ToolException('ERROR: Failed to run $executable with '
'arguments ${arguments.toString()}. Exited with exit code $exitCode');
throw ToolExit(
'ERROR: Failed to run $executable with '
'arguments ${arguments.toString()}. Exited with exit code $exitCode',
exitCode: exitCode,
);
}
}
@@ -299,59 +301,12 @@ class ProcessException implements Exception {
/// Adds utility methods
mixin ArgUtils<T> on Command<T> {
/// Extracts a boolean argument from [argResults].
bool? boolArg(String name) => argResults?[name] as bool?;
bool boolArg(String name) => argResults![name] as bool;
/// Extracts a string argument from [argResults].
String? stringArg(String name) => argResults?[name] as String?;
/// Extracts a integer argument from [argResults].
///
/// If the argument value cannot be parsed as [int] throws an [ArgumentError].
int? intArg(String name) {
final String? rawValue = stringArg(name);
if (rawValue == null) {
return null;
}
final int? value = int.tryParse(rawValue);
if (value == null) {
throw ArgumentError(
'Argument $name should be an integer value but was "$rawValue"',
);
}
return value;
}
String stringArg(String name) => argResults![name] as String;
}
/// Parses additional options that can be used for all tests.
class GeneralTestsArgumentParser {
static final GeneralTestsArgumentParser _singletonInstance =
GeneralTestsArgumentParser._();
/// The [GeneralTestsArgumentParser] singleton.
static GeneralTestsArgumentParser get instance => _singletonInstance;
GeneralTestsArgumentParser._();
/// If target name is provided integration tests can run that one test
/// instead of running all the tests.
bool verbose = false;
void populateOptions(ArgParser argParser) {
argParser.addFlag(
'verbose',
defaultsTo: false,
help: 'Flag to indicate extra logs should also be printed.',
);
}
/// Populate results of the arguments passed.
void parseOptions(ArgResults argResults) {
verbose = argResults['verbose'] as bool;
}
}
bool get isVerboseLoggingEnabled => GeneralTestsArgumentParser.instance.verbose;
/// There might be proccesses started during the tests.
///
/// Use this list to store those Processes, for cleaning up before shutdown.
@@ -392,3 +347,14 @@ Future<void> cleanup() async {
await callback();
}
}
/// Scans the test/ directory for test files and returns them.
List<FilePath> findAllTests() {
return environment.webUiTestDir
.listSync(recursive: true)
.whereType<io.File>()
.where((io.File f) => f.path.endsWith('_test.dart'))
.map<FilePath>((io.File f) => FilePath.fromWebUi(
path.relative(f.path, from: environment.webUiRootDir.path)))
.toList();
}

View File

@@ -38,7 +38,7 @@ abstract class PipelineStep {
/// The name of this step.
///
/// This value appears in logs, so it should be descriptive and human-readable.
String get name;
String get description;
/// Whether it is safe to interrupt this step while it's running.
bool get isSafeToInterrupt;
@@ -146,12 +146,12 @@ class Pipeline {
return;
}
if (step.isSafeToInterrupt) {
print('Interrupting ${step.name}');
print('Interrupting ${step.description}');
await step.interrupt();
_status = PipelineStatus.interrupted;
return;
}
print('${step.name} cannot be interrupted. Waiting for it to complete.');
print('${step.description} cannot be interrupted. Waiting for it to complete.');
await _currentStepFuture;
_status = PipelineStatus.interrupted;
}

View File

@@ -64,7 +64,10 @@ void testMain() {
drawTestPicture(canvas);
await matchPictureGolden(
'canvaskit_picture.png', recorder.endRecording());
});
// Safari does not support weak refs (FinalizationRegistry).
// This test should be revisited when Safari ships weak refs.
// TODO(yjbanov): skip Firefox due to a crash: https://github.com/flutter/flutter/issues/86632
}, skip: isSafari || isFirefox);
test('renders using a recording canvas if weak refs are not supported',
() async {

View File

@@ -7,15 +7,7 @@ import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
/// Whether the current browser is Safari.
bool get isSafari => browserEngine == BrowserEngine.webkit;
/// Whether the current browser is Safari on iOS.
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
bool get isIosSafari => isSafari && operatingSystem == OperatingSystem.iOs;
/// Whether the current browser is Firefox.
bool get isFirefox => browserEngine == BrowserEngine.firefox;
export '../common.dart';
/// Used in tests instead of [ProductionCollector] to control Skia object
/// collection explicitly, and to prevent leaks across tests.

View File

@@ -0,0 +1,15 @@
// 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:ui/src/engine.dart';
/// Whether the current browser is Safari.
bool get isSafari => browserEngine == BrowserEngine.webkit;
/// Whether the current browser is Safari on iOS.
// TODO(yjbanov): https://github.com/flutter/flutter/issues/60040
bool get isIosSafari => isSafari && operatingSystem == OperatingSystem.iOs;
/// Whether the current browser is Firefox.
bool get isFirefox => browserEngine == BrowserEngine.firefox;

View File

@@ -14,6 +14,8 @@ import 'package:ui/ui.dart' hide TextStyle, ImageShader;
import 'package:web_engine_tester/golden_tester.dart';
import '../../common.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
@@ -171,7 +173,9 @@ Future<void> testMain() async {
Paint()
..style = PaintingStyle.fill
..color = const Color(0xFF00FF00));
});
},
// TODO(yjbanov): https://github.com/flutter/flutter/issues/86623
skip: isFirefox);
test('Should draw hairline triangleFan.', () async {
final Vertices vertices = Vertices.raw(
@@ -245,7 +249,9 @@ Future<void> testMain() async {
await _testVertices('draw_vertices_triangles', vertices, BlendMode.srcOver,
Paint()..color = const Color.fromARGB(255, 0, 128, 0));
});
},
// TODO(yjbanov): https://github.com/flutter/flutter/issues/86623
skip: isFirefox);
test('Should draw triangles with colors and indices.', () async {
final Int32List colors = Int32List.fromList(
@@ -276,7 +282,9 @@ Future<void> testMain() async {
vertices as SurfaceVertices, BlendMode.srcOver, SurfacePaint());
await _checkScreenshot(rc, 'draw_vertices_triangles_indexed');
});
},
// TODO(yjbanov): https://github.com/flutter/flutter/issues/86623
skip: isFirefox);
test('Should draw triangleFan with colors.', () async {
final Int32List colors = Int32List.fromList(<int>[
@@ -307,7 +315,9 @@ Future<void> testMain() async {
await _testVertices('draw_vertices_triangle_fan', vertices,
BlendMode.srcOver, Paint()..color = const Color.fromARGB(255, 0, 128, 0));
});
},
// TODO(yjbanov): https://github.com/flutter/flutter/issues/86623
skip: isFirefox);
test('Should draw triangleStrip with colors.', () async {
final Int32List colors = Int32List.fromList(<int>[
@@ -337,7 +347,9 @@ Future<void> testMain() async {
colors: colors);
await _testVertices('draw_vertices_triangle_strip', vertices,
BlendMode.srcOver, Paint()..color = const Color.fromARGB(255, 0, 128, 0));
});
},
// TODO(yjbanov): https://github.com/flutter/flutter/issues/86623
skip: isFirefox);
Future<void> testTexture(TileMode tileMode, String filename) async {
final Uint16List indices = Uint16List.fromList(<int>[0, 1, 2, 3, 4, 0]);
@@ -377,15 +389,21 @@ Future<void> testMain() async {
test('Should draw triangle with texture and indices', () async {
await testTexture(TileMode.clamp, 'draw_vertices_texture');
});
},
// TODO(yjbanov): https://github.com/flutter/flutter/issues/86623
skip: isFirefox);
test('Should draw triangle with texture and indices', () async {
await testTexture(TileMode.mirror, 'draw_vertices_texture_mirror');
});
},
// TODO(yjbanov): https://github.com/flutter/flutter/issues/86623
skip: isFirefox);
test('Should draw triangle with texture and indices', () async {
await testTexture(TileMode.repeated, 'draw_vertices_texture_repeated');
});
},
// TODO(yjbanov): https://github.com/flutter/flutter/issues/86623
skip: isFirefox);
}
Future<HtmlImage> createTestImage({int width = 50, int height = 40}) {

View File

@@ -13,8 +13,12 @@ import 'package:ui/ui.dart';
import 'package:web_engine_tester/golden_tester.dart';
import '../../common.dart';
import '../paragraph/text_scuba.dart';
// TODO(yjbanov): unskip Firefox tests when Firefox implements WebGL in headless mode.
// https://github.com/flutter/flutter/issues/86623
void main() {
internalBootstrapBrowserTest(() => testMain);
}
@@ -131,7 +135,7 @@ Future<void> testMain() async {
canvas.restore();
await _checkScreenshot(canvas, 'sweep_gradient_rect');
});
}, skip: isFirefox);
test('Paints sweep gradient ovals', () async {
final RecordingCanvas canvas =
@@ -210,7 +214,7 @@ Future<void> testMain() async {
canvas.restore();
await _checkScreenshot(canvas, 'sweep_gradient_oval');
});
}, skip: isFirefox);
test('Paints sweep gradient paths', () async {
final RecordingCanvas canvas =
@@ -294,7 +298,7 @@ Future<void> testMain() async {
canvas.restore();
await _checkScreenshot(canvas, 'sweep_gradient_path');
});
}, skip: isFirefox);
/// Regression test for https://github.com/flutter/flutter/issues/74137.
test('Paints rotated and shifted linear gradient', () async {
@@ -342,7 +346,7 @@ Future<void> testMain() async {
canvas.restore();
await _checkScreenshot(canvas, 'linear_gradient_rect_shifted');
});
}, skip: isFirefox);
/// Regression test for https://github.com/flutter/flutter/issues/82748.
test('Paints gradient with gradient stop outside range', () async {

View File

@@ -10,8 +10,12 @@ import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide TextStyle;
import '../../common.dart';
import '../screenshot.dart';
// TODO(yjbanov): unskip Firefox tests when Firefox implements WebGL in headless mode.
// https://github.com/flutter/flutter/issues/86623
void main() {
internalBootstrapBrowserTest(() => testMain);
}
@@ -109,18 +113,19 @@ Future<void> testMain() async {
await testImageShader(
TileMode.clamp, TileMode.repeated, 'image_shader_clamp_horiz',
maxDiffRatePercent: 13.0);
});
}, skip: isFirefox);
test('Should draw with vertical clamp imageshader.', () async {
await testImageShader(
TileMode.repeated, TileMode.clamp, 'image_shader_clamp_vertical',
maxDiffRatePercent: 1.0);
});
}, skip: isFirefox);
test('Should draw with clamp imageshader.', () async {
await testImageShader(
TileMode.clamp, TileMode.clamp, 'image_shader_clamp',
maxDiffRatePercent: 1.0);
});
}, skip: isFirefox);
}
HtmlImage createTestImage() {

View File

@@ -8,8 +8,12 @@ import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide TextStyle;
import '../../common.dart';
import '../screenshot.dart';
// TODO(yjbanov): unskip Firefox tests when Firefox implements WebGL in headless mode.
// https://github.com/flutter/flutter/issues/86623
void main() {
internalBootstrapBrowserTest(() => testMain);
}
@@ -115,7 +119,7 @@ Future<void> testMain() async {
expect(rc.renderStrategy.hasArbitraryPaint, isTrue);
await canvasScreenshot(rc, 'linear_gradient_tiled_repeated_rect',
region: screenRect);
});
}, skip: isFirefox);
test('Should draw tiled mirrored linear gradient with transform.', () async {
final RecordingCanvas rc =
@@ -142,5 +146,5 @@ Future<void> testMain() async {
expect(rc.renderStrategy.hasArbitraryPaint, isTrue);
await canvasScreenshot(rc, 'linear_gradient_tiled_mirrored_rect',
region: screenRect);
});
}, skip: isFirefox);
}

View File

@@ -6,6 +6,7 @@ import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide TextStyle;
import '../../common.dart';
import '../screenshot.dart';
void main() {
@@ -111,7 +112,9 @@ Future<void> testMain() async {
TileMode.repeated),
shaderRect: shaderRect,
region: const Rect.fromLTWH(0, 0, 600, 800));
});
},
// TODO(yjbanov): https://github.com/flutter/flutter/issues/86623
skip: isFirefox);
test('Should draw with radial gradient with TileMode.mirrored.', () async {
const Rect shaderRect = Rect.fromLTRB(50, 50, 100, 100);
@@ -126,5 +129,7 @@ Future<void> testMain() async {
TileMode.mirror),
shaderRect: shaderRect,
region: const Rect.fromLTWH(0, 0, 600, 800));
});
},
// TODO(yjbanov): https://github.com/flutter/flutter/issues/86623
skip: isFirefox);
}

View File

@@ -12,6 +12,8 @@ import 'package:ui/ui.dart';
import 'package:web_engine_tester/golden_tester.dart';
import '../../common.dart';
/// To debug compositing failures on browsers, set this flag to true and run
/// flutter run -d chrome --web-renderer=html
/// test/golden_tests/engine/shader_mask_golden_test.dart --profile
@@ -26,8 +28,9 @@ Future<void> main() async {
}
// TODO(ferhat): unskip webkit tests once flakiness is resolved. See
/// https://github.com/flutter/flutter/issues/76713
bool get isWebkit => browserEngine == BrowserEngine.webkit;
// https://github.com/flutter/flutter/issues/76713
// TODO(yjbanov): unskip Firefox tests when Firefox implements WebGL in headless mode.
// https://github.com/flutter/flutter/issues/86623
Future<void> testMain() async {
setUp(() async {
@@ -48,58 +51,58 @@ Future<void> testMain() async {
_renderCirclesScene(BlendMode.dst);
await matchGoldenFile('shadermask_linear_dst.png',
region: const Rect.fromLTWH(0, 0, 360, 200));
}, skip: isWebkit);
}, skip: isSafari || isFirefox);
/// Should render the gradient only where circles have alpha channel.
test('Renders shader mask with linear gradient BlendMode srcIn', () async {
_renderCirclesScene(BlendMode.srcIn);
await matchGoldenFile('shadermask_linear_srcin.png',
region: const Rect.fromLTWH(0, 0, 360, 200));
}, skip: isWebkit);
}, skip: isSafari || isFirefox);
test('Renders shader mask with linear gradient BlendMode color', () async {
_renderCirclesScene(BlendMode.color);
await matchGoldenFile('shadermask_linear_color.png',
region: const Rect.fromLTWH(0, 0, 360, 200));
}, skip: isWebkit);
}, skip: isSafari || isFirefox);
test('Renders shader mask with linear gradient BlendMode xor', () async {
_renderCirclesScene(BlendMode.xor);
await matchGoldenFile('shadermask_linear_xor.png',
region: const Rect.fromLTWH(0, 0, 360, 200));
}, skip: isWebkit);
}, skip: isSafari || isFirefox);
test('Renders shader mask with linear gradient BlendMode plus', () async {
_renderCirclesScene(BlendMode.plus);
await matchGoldenFile('shadermask_linear_plus.png',
region: const Rect.fromLTWH(0, 0, 360, 200));
}, skip: isWebkit);
}, skip: isSafari || isFirefox);
test('Renders shader mask with linear gradient BlendMode modulate', () async {
_renderCirclesScene(BlendMode.modulate);
await matchGoldenFile('shadermask_linear_modulate.png',
region: const Rect.fromLTWH(0, 0, 360, 200));
}, skip: isWebkit);
}, skip: isSafari || isFirefox);
test('Renders shader mask with linear gradient BlendMode overlay', () async {
_renderCirclesScene(BlendMode.overlay);
await matchGoldenFile('shadermask_linear_overlay.png',
region: const Rect.fromLTWH(0, 0, 360, 200));
}, skip: isWebkit);
}, skip: isSafari || isFirefox);
/// Should render the gradient opaque on top of content.
test('Renders shader mask with linear gradient BlendMode src', () async {
_renderCirclesScene(BlendMode.src);
await matchGoldenFile('shadermask_linear_src.png',
region: const Rect.fromLTWH(0, 0, 360, 200));
}, skip: isWebkit);
}, skip: isSafari || isFirefox);
/// Should render text with gradient.
test('Renders text with linear gradient shader mask', () async {
_renderTextScene(BlendMode.srcIn);
await matchGoldenFile('shadermask_linear_text.png',
region: const Rect.fromLTWH(0, 0, 360, 200), maxDiffRatePercent: 2.0);
}, skip: isWebkit);
}, skip: isSafari || isFirefox);
}
Picture _drawTestPictureWithCircles(