diff --git a/engine/src/flutter/lib/web_ui/dev/README.md b/engine/src/flutter/lib/web_ui/dev/README.md index edbb743df3..940ef99917 100644 --- a/engine/src/flutter/lib/web_ui/dev/README.md +++ b/engine/src/flutter/lib/web_ui/dev/README.md @@ -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 diff --git a/engine/src/flutter/lib/web_ui/dev/browser_lock.dart b/engine/src/flutter/lib/web_ui/dev/browser_lock.dart new file mode 100644 index 0000000000..f32815abd9 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/dev/browser_lock.dart @@ -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'; +} diff --git a/engine/src/flutter/lib/web_ui/dev/browser_lock.yaml b/engine/src/flutter/lib/web_ui/dev/browser_lock.yaml index 51baa3e517..f39818799f 100644 --- a/engine/src/flutter/lib/web_ui/dev/browser_lock.yaml +++ b/engine/src/flutter/lib/web_ui/dev/browser_lock.yaml @@ -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 diff --git a/engine/src/flutter/lib/web_ui/dev/build.dart b/engine/src/flutter/lib/web_ui/dev/build.dart index 525f2f31fc..17953a40a0 100644 --- a/engine/src/flutter/lib/web_ui/dev/build.dart +++ b/engine/src/flutter/lib/web_ui/dev/build.dart @@ -30,7 +30,7 @@ class BuildCommand extends Command with ArgUtils { @override String get description => 'Build the Flutter web engine.'; - bool get isWatchMode => boolArg('watch')!; + bool get isWatchMode => boolArg('watch'); @override FutureOr run() async { @@ -61,7 +61,7 @@ class BuildCommand extends Command with ArgUtils { /// 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; diff --git a/engine/src/flutter/lib/web_ui/dev/chrome.dart b/engine/src/flutter/lib/web_ui/dev/chrome.dart index 5daf0a92b0..152bdb5d29 100644 --- a/engine/src/flutter/lib/web_ui/dev/chrome.dart +++ b/engine/src/flutter/lib/web_ui/dev/chrome.dart @@ -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 remoteDebuggerCompleter = Completer.sync(); return Chrome._(() async { final BrowserInstallation installation = await getOrInstallChrome( diff --git a/engine/src/flutter/lib/web_ui/dev/chrome_installer.dart b/engine/src/flutter/lib/web_ui/dev/chrome_installer.dart index 4015f49535..6f6b677ee7 100644 --- a/engine/src/flutter/lib/web_ui/dev/chrome_installer.dart +++ b/engine/src/flutter/lib/web_ui/dev/chrome_installer.dart @@ -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 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; diff --git a/engine/src/flutter/lib/web_ui/dev/clean.dart b/engine/src/flutter/lib/web_ui/dev/clean.dart index 9bc4c99faa..b31567c15c 100644 --- a/engine/src/flutter/lib/web_ui/dev/clean.dart +++ b/engine/src/flutter/lib/web_ui/dev/clean.dart @@ -29,9 +29,9 @@ class CleanCommand extends Command with ArgUtils { @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.'; diff --git a/engine/src/flutter/lib/web_ui/dev/common.dart b/engine/src/flutter/lib/web_ui/dev/common.dart index 7af7a0559a..fa5166954f 100644 --- a/engine/src/flutter/lib/web_ui/dev/common.dart +++ b/engine/src/flutter/lib/web_ui/dev/common.dart @@ -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 kAllBrowserNames = [ + 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.'); +} diff --git a/engine/src/flutter/lib/web_ui/dev/create_simulator.dart b/engine/src/flutter/lib/web_ui/dev/create_simulator.dart index 77e3e5e723..85fd076c4d 100644 --- a/engine/src/flutter/lib/web_ui/dev/create_simulator.dart +++ b/engine/src/flutter/lib/web_ui/dev/create_simulator.dart @@ -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 with ArgUtils { - 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 with ArgUtils { @override FutureOr 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 ' diff --git a/engine/src/flutter/lib/web_ui/dev/edge.dart b/engine/src/flutter/lib/web_ui/dev/edge.dart index 843d68880e..0b810bccca 100644 --- a/engine/src/flutter/lib/web_ui/dev/edge.dart +++ b/engine/src/flutter/lib/web_ui/dev/edge.dart @@ -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(), ); diff --git a/engine/src/flutter/lib/web_ui/dev/edge_installation.dart b/engine/src/flutter/lib/web_ui/dev/edge_installation.dart index e44318b9db..c10e220cb0 100644 --- a/engine/src/flutter/lib/web_ui/dev/edge_installation.dart +++ b/engine/src/flutter/lib/web_ui/dev/edge_installation.dart @@ -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 install() async { diff --git a/engine/src/flutter/lib/web_ui/dev/environment.dart b/engine/src/flutter/lib/web_ui/dev/environment.dart index 361e805e88..ec3f42bd42 100644 --- a/engine/src/flutter/lib/web_ui/dev/environment.dart +++ b/engine/src/flutter/lib/web_ui/dev/environment.dart @@ -38,7 +38,7 @@ class Environment { webUiRootDir ]) { if (!expectedDirectory.existsSync()) { - throw ToolException('$expectedDirectory does not exist.'); + throw ToolExit('$expectedDirectory does not exist.'); } } diff --git a/engine/src/flutter/lib/web_ui/dev/exceptions.dart b/engine/src/flutter/lib/web_ui/dev/exceptions.dart index acb665bf6a..319eae17c2 100644 --- a/engine/src/flutter/lib/web_ui/dev/exceptions.dart +++ b/engine/src/flutter/lib/web_ui/dev/exceptions.dart @@ -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; diff --git a/engine/src/flutter/lib/web_ui/dev/felt.dart b/engine/src/flutter/lib/web_ui/dev/felt.dart index 61ad546f99..ec036869aa 100644 --- a/engine/src/flutter/lib/web_ui/dev/felt.dart +++ b/engine/src/flutter/lib/web_ui/dev/felt.dart @@ -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 runner = CommandRunner( '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 main(List rawArgs) async { // Remove --clean from the list as that's processed by the wrapper script. @@ -38,17 +40,17 @@ Future main(List 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} ' diff --git a/engine/src/flutter/lib/web_ui/dev/firefox.dart b/engine/src/flutter/lib/web_ui/dev/firefox.dart index 3f0277ac45..61c02da271 100644 --- a/engine/src/flutter/lib/web_ui/dev/firefox.dart +++ b/engine/src/flutter/lib/web_ui/dev/firefox.dart @@ -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 remoteDebuggerCompleter = Completer.sync(); return Firefox._(() async { final BrowserInstallation installation = await getOrInstallFirefox( - version, + browserLock.firefoxLock.version, infoLog: isCirrus ? stdout : DevNull(), ); diff --git a/engine/src/flutter/lib/web_ui/dev/firefox_installer.dart b/engine/src/flutter/lib/web_ui/dev/firefox_installer.dart index aa887c2de5..2d48c16e02 100644 --- a/engine/src/flutter/lib/web_ui/dev/firefox_installer.dart +++ b/engine/src/flutter/lib/web_ui/dev/firefox_installer.dart @@ -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 diff --git a/engine/src/flutter/lib/web_ui/dev/run.dart b/engine/src/flutter/lib/web_ui/dev/run.dart new file mode 100644 index 0000000000..955fd06b45 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/dev/run.dart @@ -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 with ArgUtils { + 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 get stepNames => argResults!.rest; + + @override + FutureOr run() async { + // All available build steps. + final Map buildSteps = { + '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 unrecognizedStepNames = []; + 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 steps = []; + 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; + } +} diff --git a/engine/src/flutter/lib/web_ui/dev/safari_installation.dart b/engine/src/flutter/lib/web_ui/dev/safari_installation.dart index 47e96ca6a5..497ae06dc7 100644 --- a/engine/src/flutter/lib/web_ui/dev/safari_installation.dart +++ b/engine/src/flutter/lib/web_ui/dev/safari_installation.dart @@ -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 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 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 getOrInstallSafari( - String requestedVersion, { +Future getOrInstallSafari({ StringSink? infoLog, }) async { // These tests are aimed to run only on macOS machines local or on LUCI. @@ -195,16 +80,11 @@ Future 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(), + ); } diff --git a/engine/src/flutter/lib/web_ui/dev/safari_ios.dart b/engine/src/flutter/lib/web_ui/dev/safari_ios.dart index 905fe6ef9f..cd68ec0fc7 100644 --- a/engine/src/flutter/lib/web_ui/dev/safari_ios.dart +++ b/engine/src/flutter/lib/web_ui/dev/safari_ios.dart @@ -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 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)); diff --git a/engine/src/flutter/lib/web_ui/dev/steps/compile_tests_step.dart b/engine/src/flutter/lib/web_ui/dev/steps/compile_tests_step.dart new file mode 100644 index 0000000000..a351bc1b9d --- /dev/null +++ b/engine/src/flutter/lib/web_ui/dev/steps/compile_tests_step.dart @@ -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? testFiles; + + @override + String get description => 'compile_tests'; + + @override + bool get isSafeToInterrupt => true; + + @override + Future interrupt() async { + await cleanup(); + } + + @override + Future run() async { + if (!skipGoldensRepoFetch) { + await fetchGoldensRepo(); + } + await buildHostPage(); + await compileTests(testFiles ?? findAllTests()); + } +} + +/// Compiles the specified unit tests. +Future compileTests(List testFiles) async { + final Stopwatch stopwatch = Stopwatch()..start(); + + // Separate HTML targets from CanvasKit targets because the two use + // different dart2js options. + final List htmlTargets = []; + final List canvasKitTargets = []; + 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(>[ + 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 _compileTestsInParallel({ + required List targets, + required bool forCanvasKit, +}) async { + final Stream 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 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 arguments = [ + '--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 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, + [ + 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 fetchGoldensRepo() async { + print('INFO: Fetching goldens repo'); + final GoldensRepoFetcher goldensRepoFetcher = GoldensRepoFetcher( + environment.webUiGoldensRepositoryDirectory, + pathlib.join(environment.webUiDevDir.path, 'goldens_lock.yaml')); + await goldensRepoFetcher.fetch(); +} diff --git a/engine/src/flutter/lib/web_ui/dev/steps/run_tests_step.dart b/engine/src/flutter/lib/web_ui/dev/steps/run_tests_step.dart new file mode 100644 index 0000000000..bd5009b137 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/dev/steps/run_tests_step.dart @@ -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? 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 failedShards = []; + + /// Whether all test shards succeeded. + bool get allShardsPassed => failedShards.isEmpty; + + @override + String get description => 'run_tests'; + + @override + bool get isSafeToInterrupt => true; + + @override + Future interrupt() async {} + + @override + Future run() async { + _copyTestFontsIntoWebUi(); + await _prepareTestResultsDirectory(); + await browserEnvironment.prepareEnvironment(); + + final List 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 screenshotTestFiles = []; + final List unitTestFiles = []; + + 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: [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: [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 _prepareTestResultsDirectory() async { + if (environment.webUiTestResultsDirectory.existsSync()) { + environment.webUiTestResultsDirectory.deleteSync(recursive: true); + } + environment.webUiTestResultsDirectory.createSync(recursive: true); +} + +const List _kTestFonts = [ + '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 _runTestBatch({ + required List 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 testArgs = [ + ...['-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([ + 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() {} +} diff --git a/engine/src/flutter/lib/web_ui/dev/test_platform.dart b/engine/src/flutter/lib/web_ui/dev/test_platform.dart index 481de1524a..b7e1c11fe6 100644 --- a/engine/src/flutter/lib/web_ui/dev/test_platform.dart +++ b/engine/src/flutter/lib/web_ui/dev/test_platform.dart @@ -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 requestData = json.decode(payload) as Map; 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) diff --git a/engine/src/flutter/lib/web_ui/dev/test_runner.dart b/engine/src/flutter/lib/web_ui/dev/test_runner.dart index 2046a39a6d..08f36a2d4d 100644 --- a/engine/src/flutter/lib/web_ui/dev/test_runner.dart +++ b/engine/src/flutter/lib/web_ui/dev/test_runner.dart @@ -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 failedShards = []; - -/// Whether all test shards succeeded. -bool get allShardsPassed => failedShards.isEmpty; - -/// Command-line argument parsers that parse browser-specific options. -final List _browserArgParsers = [ - 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 with ArgUtils { TestCommand() { @@ -145,11 +83,6 @@ class TestCommand extends Command with ArgUtils { '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 with ArgUtils { @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 get targets => argResults!.rest; + + /// The target test files to run. + List 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 run() async { - for (final BrowserArgParser browserArgParser in _browserArgParsers) { - browserArgParser.parseOptions(argResults!); - } - GeneralTestsArgumentParser.instance.parseOptions(argResults!); + final BrowserEnvironment browserEnvironment = getBrowserEnvironment(browser); + + final List testFiles = runAllTests + ? findAllTests() + : targetFiles; final Pipeline testPipeline = Pipeline(steps: [ 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 with ArgUtils { // 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 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 _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 _buildTargets() async { - final Stopwatch stopwatch = Stopwatch()..start(); - List allTargets; - if (runAllTests) { - allTargets = environment.webUiTestDir - .listSync(recursive: true) - .whereType() - .where((io.File f) => f.path.endsWith('_test.dart')) - .map((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 htmlTargets = []; - final List canvasKitTargets = []; - 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 get targets => argResults!.rest; - - /// The target test files to run. - List 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 _runSpecificTests(List 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 _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 screenshotTestFiles = []; - final List unitTestFiles = []; - - for (final io.File testFile - in testDir.listSync(recursive: true).whereType()) { - 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( - [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( - [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 _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, - [ - 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 _buildTestsInParallel({ - required List targets, - bool forCanvasKit = false, - }) async { - final List buildInputs = targets - .map((FilePath f) => TestBuildInput(f, forCanvasKit: forCanvasKit)) - .toList(); - - final Stream 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 _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 arguments = [ - '--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 _runTestBatch( - List testFiles, { - required int concurrency, - required bool expectFailure, - }) async { - final String configurationFilePath = path.join( - environment.webUiRootDir.path, - browserEnvironment.packageTestConfigurationYamlFile, - ); - final List testArgs = [ - ...['-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([ - 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 _kTestFonts = [ - '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 interrupt() async { - // Interrupt this step by killing all spawned processes (browsers, web drivers, etc). - cleanup(); - } - - @override - bool get isSafeToInterrupt => true; - - @override - Future run() async { - await testCommand.runUnitTests(); - } -} diff --git a/engine/src/flutter/lib/web_ui/dev/utils.dart b/engine/src/flutter/lib/web_ui/dev/utils.dart index 5912676833..c3eac56cd8 100644 --- a/engine/src/flutter/lib/web_ui/dev/utils.dart +++ b/engine/src/flutter/lib/web_ui/dev/utils.dart @@ -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 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 on Command { /// 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 cleanup() async { await callback(); } } + +/// Scans the test/ directory for test files and returns them. +List findAllTests() { + return environment.webUiTestDir + .listSync(recursive: true) + .whereType() + .where((io.File f) => f.path.endsWith('_test.dart')) + .map((io.File f) => FilePath.fromWebUi( + path.relative(f.path, from: environment.webUiRootDir.path))) + .toList(); +} diff --git a/engine/src/flutter/lib/web_ui/dev/watcher.dart b/engine/src/flutter/lib/web_ui/dev/watcher.dart index 08f8677931..b8ad28b711 100644 --- a/engine/src/flutter/lib/web_ui/dev/watcher.dart +++ b/engine/src/flutter/lib/web_ui/dev/watcher.dart @@ -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; } diff --git a/engine/src/flutter/lib/web_ui/test/canvaskit/canvas_golden_test.dart b/engine/src/flutter/lib/web_ui/test/canvaskit/canvas_golden_test.dart index f61943f4d7..414be1ebc7 100644 --- a/engine/src/flutter/lib/web_ui/test/canvaskit/canvas_golden_test.dart +++ b/engine/src/flutter/lib/web_ui/test/canvaskit/canvas_golden_test.dart @@ -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 { diff --git a/engine/src/flutter/lib/web_ui/test/canvaskit/common.dart b/engine/src/flutter/lib/web_ui/test/canvaskit/common.dart index 7344557738..32f4f01d6a 100644 --- a/engine/src/flutter/lib/web_ui/test/canvaskit/common.dart +++ b/engine/src/flutter/lib/web_ui/test/canvaskit/common.dart @@ -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. diff --git a/engine/src/flutter/lib/web_ui/test/common.dart b/engine/src/flutter/lib/web_ui/test/common.dart new file mode 100644 index 0000000000..2909a6feca --- /dev/null +++ b/engine/src/flutter/lib/web_ui/test/common.dart @@ -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; diff --git a/engine/src/flutter/lib/web_ui/test/html/drawing/draw_vertices_golden_test.dart b/engine/src/flutter/lib/web_ui/test/html/drawing/draw_vertices_golden_test.dart index cdaa6b4336..f2045319cf 100644 --- a/engine/src/flutter/lib/web_ui/test/html/drawing/draw_vertices_golden_test.dart +++ b/engine/src/flutter/lib/web_ui/test/html/drawing/draw_vertices_golden_test.dart @@ -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 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 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 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([ @@ -307,7 +315,9 @@ Future 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([ @@ -337,7 +347,9 @@ Future 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 testTexture(TileMode tileMode, String filename) async { final Uint16List indices = Uint16List.fromList([0, 1, 2, 3, 4, 0]); @@ -377,15 +389,21 @@ Future 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 createTestImage({int width = 50, int height = 40}) { diff --git a/engine/src/flutter/lib/web_ui/test/html/shaders/gradient_golden_test.dart b/engine/src/flutter/lib/web_ui/test/html/shaders/gradient_golden_test.dart index 98a068446f..72a2c353ba 100644 --- a/engine/src/flutter/lib/web_ui/test/html/shaders/gradient_golden_test.dart +++ b/engine/src/flutter/lib/web_ui/test/html/shaders/gradient_golden_test.dart @@ -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 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 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 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 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 { diff --git a/engine/src/flutter/lib/web_ui/test/html/shaders/image_shader_golden_test.dart b/engine/src/flutter/lib/web_ui/test/html/shaders/image_shader_golden_test.dart index 0af6894aa6..d6dd92843d 100644 --- a/engine/src/flutter/lib/web_ui/test/html/shaders/image_shader_golden_test.dart +++ b/engine/src/flutter/lib/web_ui/test/html/shaders/image_shader_golden_test.dart @@ -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 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() { diff --git a/engine/src/flutter/lib/web_ui/test/html/shaders/linear_gradient_golden_test.dart b/engine/src/flutter/lib/web_ui/test/html/shaders/linear_gradient_golden_test.dart index 67db2f16b7..75ba082793 100644 --- a/engine/src/flutter/lib/web_ui/test/html/shaders/linear_gradient_golden_test.dart +++ b/engine/src/flutter/lib/web_ui/test/html/shaders/linear_gradient_golden_test.dart @@ -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 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 testMain() async { expect(rc.renderStrategy.hasArbitraryPaint, isTrue); await canvasScreenshot(rc, 'linear_gradient_tiled_mirrored_rect', region: screenRect); - }); + }, skip: isFirefox); } diff --git a/engine/src/flutter/lib/web_ui/test/html/shaders/radial_gradient_golden_test.dart b/engine/src/flutter/lib/web_ui/test/html/shaders/radial_gradient_golden_test.dart index 558cd6aff3..0e82ea3aaa 100644 --- a/engine/src/flutter/lib/web_ui/test/html/shaders/radial_gradient_golden_test.dart +++ b/engine/src/flutter/lib/web_ui/test/html/shaders/radial_gradient_golden_test.dart @@ -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 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 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); } diff --git a/engine/src/flutter/lib/web_ui/test/html/shaders/shader_mask_golden_test.dart b/engine/src/flutter/lib/web_ui/test/html/shaders/shader_mask_golden_test.dart index c00f6a505d..394d447ac5 100644 --- a/engine/src/flutter/lib/web_ui/test/html/shaders/shader_mask_golden_test.dart +++ b/engine/src/flutter/lib/web_ui/test/html/shaders/shader_mask_golden_test.dart @@ -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 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 testMain() async { setUp(() async { @@ -48,58 +51,58 @@ Future 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(