Implement screenshot test for flutter web. (#45530)

This commit is contained in:
Lau Ching Jun
2019-12-06 14:25:39 -08:00
committed by GitHub
parent 9233b53255
commit c2eb0681ce
19 changed files with 1093 additions and 131 deletions

View File

@@ -255,6 +255,7 @@ class FlutterWebTestBootstrapBuilder implements Builder {
final String assetPath = id.pathSegments.first == 'lib'
? path.url.join('packages', id.package, id.path)
: id.path;
final Uri testUrl = path.toUri(path.absolute(assetPath));
final Metadata metadata = parseMetadata(
assetPath, contents, Runtime.builtIn.map((Runtime runtime) => runtime.name).toSet());
@@ -265,6 +266,7 @@ import 'dart:html';
import 'dart:js';
import 'package:stream_channel/stream_channel.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:test_api/src/backend/stack_trace_formatter.dart'; // ignore: implementation_imports
import 'package:test_api/src/util/stack_trace_mapper.dart'; // ignore: implementation_imports
import 'package:test_api/src/remote_listener.dart'; // ignore: implementation_imports
@@ -279,6 +281,7 @@ Future<void> main() async {
// this stuff in.
ui.debugEmulateFlutterTesterEnvironment = true;
await ui.webOnlyInitializePlatform();
webGoldenComparator = DefaultWebGoldenComparator(Uri.parse('$testUrl'));
// TODO(flutterweb): remove need for dynamic cast.
(ui.window as dynamic).debugOverrideDevicePixelRatio(3.0);
(ui.window as dynamic).webOnlyDebugPhysicalSizeOverride = const ui.Size(2400, 1800);

View File

@@ -29,6 +29,7 @@ import '../globals.dart';
import '../project.dart';
import '../vmservice.dart';
import 'test_compiler.dart';
import 'test_config.dart';
import 'watcher.dart';
/// The timeout we give the test process to connect to the test harness
@@ -55,14 +56,6 @@ const Duration _kTestProcessTimeout = Duration(minutes: 5);
/// hold that against the test.
const String _kStartTimeoutTimerMessage = 'sky_shell test process has entered main method';
/// The name of the test configuration file that will be discovered by the
/// test harness if it exists in the project directory hierarchy.
const String _kTestConfigFileName = 'flutter_test_config.dart';
/// The name of the file that signals the root of the project and that will
/// cause the test harness to stop scanning for configuration files.
const String _kProjectRootSentinel = 'pubspec.yaml';
/// The address at which our WebSocket server resides and at which the sky_shell
/// processes will host the Observatory server.
final Map<InternetAddressType, InternetAddress> _kHosts = <InternetAddressType, InternetAddress>{
@@ -743,25 +736,9 @@ class FlutterPlatform extends PlatformPlugin {
Uri testUrl,
}) {
assert(testUrl.scheme == 'file');
File testConfigFile;
Directory directory = fs.file(testUrl).parent;
while (directory.path != directory.parent.path) {
final File configFile = directory.childFile(_kTestConfigFileName);
if (configFile.existsSync()) {
printTrace('Discovered $_kTestConfigFileName in ${directory.path}');
testConfigFile = configFile;
break;
}
if (directory.childFile(_kProjectRootSentinel).existsSync()) {
printTrace('Stopping scan for $_kTestConfigFileName; '
'found project root at ${directory.path}');
break;
}
directory = directory.parent;
}
return generateTestBootstrap(
testUrl: testUrl,
testConfigFile: testConfigFile,
testConfigFile: findTestConfigFile(fs.file(testUrl)),
host: host,
updateGoldens: updateGoldens,
);

View File

@@ -5,6 +5,7 @@
// ignore_for_file: implementation_imports
import 'dart:async';
import 'dart:typed_data';
import 'package:async/async.dart';
import 'package:http_multi_server/http_multi_server.dart';
@@ -27,18 +28,30 @@ import 'package:test_core/src/runner/plugin/platform_helpers.dart';
import 'package:test_core/src/runner/runner_suite.dart';
import 'package:test_core/src/runner/suite.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart' hide StackTrace;
import '../artifacts.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/process_manager.dart';
import '../build_info.dart';
import '../cache.dart';
import '../convert.dart';
import '../dart/package_map.dart';
import '../globals.dart';
import '../project.dart';
import '../web/chrome.dart';
import 'test_compiler.dart';
import 'test_config.dart';
class FlutterWebPlatform extends PlatformPlugin {
FlutterWebPlatform._(this._server, this._config, this._root) {
FlutterWebPlatform._(this._server, this._config, this._root, {
FlutterProject flutterProject,
String shellPath,
this.updateGoldens,
}) {
// Look up the location of the testing resources.
final Map<String, Uri> packageMap = PackageMap(fs.path.join(
Cache.flutterRoot,
@@ -58,17 +71,30 @@ class FlutterWebPlatform extends PlatformPlugin {
.add(createStaticHandler(_config.suiteDefaults.precompiledPath,
serveFilesOutsidePath: true))
.add(_handleStaticArtifact)
.add(_goldenFileHandler)
.add(_wrapperHandler);
_server.mount(cascade.handler);
_testGoldenComparator = TestGoldenComparator(
shellPath,
() => TestCompiler(BuildMode.debug, false, flutterProject),
);
}
static Future<FlutterWebPlatform> start(String root) async {
static Future<FlutterWebPlatform> start(String root, {
FlutterProject flutterProject,
String shellPath,
bool updateGoldens = false,
}) async {
final shelf_io.IOServer server =
shelf_io.IOServer(await HttpMultiServer.loopback(0));
return FlutterWebPlatform._(
server,
Configuration.current,
root,
flutterProject: flutterProject,
shellPath: shellPath,
updateGoldens: updateGoldens,
);
}
@@ -167,6 +193,59 @@ class FlutterWebPlatform extends PlatformPlugin {
}
}
final bool updateGoldens;
TestGoldenComparator _testGoldenComparator;
Future<shelf.Response> _goldenFileHandler(shelf.Request request) async {
if (request.url.path.contains('flutter_goldens')) {
final Map<String, Object> body = json.decode(await request.readAsString()) as Map<String, Object>;
final Uri goldenKey = Uri.parse(body['key'] as String);
final Uri testUri = Uri.parse(body['testUri'] as String);
final num width = body['width'] as num;
final num height = body['height'] as num;
Uint8List bytes;
try {
final Runtime browser = Runtime.chrome;
final BrowserManager browserManager = await _browserManagerFor(browser);
final ChromeTab chromeTab = await browserManager._browser.chromeConnection.getTab((ChromeTab tab) {
return tab.url.contains(browserManager._browser.url);
});
final WipConnection connection = await chromeTab.connect();
final WipResponse response = await connection.sendCommand('Page.captureScreenshot', <String, Object>{
// Clip the screenshot to include only the element.
// Prior to taking a screenshot, we are calling `window.render()` in
// `_matchers_web.dart` to only render the element on screen. That
// will make sure that the element will always be displayed on the
// origin of the screen.
'clip': <String, Object>{
'x': 0.0,
'y': 0.0,
'width': width.toDouble(),
'height': height.toDouble(),
'scale': 1.0,
}
});
bytes = base64.decode(response.result['data'] as String);
} on WipError catch (ex) {
printError('Caught WIPError: $ex');
return shelf.Response.ok('WIP error: $ex');
} on FormatException catch (ex) {
printError('Caught FormatException: $ex');
return shelf.Response.ok('Caught exception: $ex');
}
if (bytes == null) {
return shelf.Response.ok('Unknown error, bytes is null');
}
final String errorMessage = await _testGoldenComparator.compareGoldens(testUri, bytes, goldenKey, updateGoldens);
return shelf.Response.ok(errorMessage ?? 'true');
} else {
return shelf.Response.notFound('Not Found');
}
}
final OneOffHandler _webSocketHandler = OneOffHandler();
final PathHandler _jsHandler = PathHandler();
final AsyncMemoizer<void> _closeMemo = AsyncMemoizer<void>();
@@ -296,6 +375,7 @@ class FlutterWebPlatform extends PlatformPlugin {
})
.toList();
futures.add(_server.close());
futures.add(_testGoldenComparator.close());
await Future.wait<void>(futures);
});
}
@@ -702,3 +782,182 @@ class _BrowserEnvironment implements Environment {
@override
CancelableOperation<dynamic> displayPause() => _manager._displayPause();
}
/// Helper class to start golden file comparison in a separate process.
///
/// Golden file comparator is configured using flutter_test_config.dart and that
/// file can contain arbitrary Dart code that depends on dart:ui. Thus it has to
/// be executed in a `flutter_tester` environment. This helper class generates a
/// Dart file configured with flutter_test_config.dart to perform the comparison
/// of golden files.
class TestGoldenComparator {
/// Creates a [TestGoldenComparator] instance.
TestGoldenComparator(this.shellPath, this.compilerFactory)
: tempDir = fs.systemTempDirectory.createTempSync('flutter_web_platform.');
final String shellPath;
final Directory tempDir;
final TestCompiler Function() compilerFactory;
TestCompiler _compiler;
TestGoldenComparatorProcess _previousComparator;
Uri _previousTestUri;
Future<void> close() async {
tempDir.deleteSync(recursive: true);
await _compiler?.dispose();
await _previousComparator?.close();
}
/// Start golden comparator in a separate process. Start one file per test file
/// to reduce the overhead of starting `flutter_tester`.
Future<TestGoldenComparatorProcess> _processForTestFile(Uri testUri) async {
if (testUri == _previousTestUri) {
return _previousComparator;
}
final String bootstrap = TestGoldenComparatorProcess.generateBootstrap(testUri);
final Process process = await _startProcess(bootstrap);
unawaited(_previousComparator?.close());
_previousComparator = TestGoldenComparatorProcess(process);
_previousTestUri = testUri;
return _previousComparator;
}
Future<Process> _startProcess(String testBootstrap) async {
// Prepare the Dart file that will talk to us and start the test.
final File listenerFile = (await tempDir.createTemp('listener')).childFile('listener.dart');
await listenerFile.writeAsString(testBootstrap);
// Lazily create the compiler
_compiler = _compiler ?? compilerFactory();
final String output = await _compiler.compile(listenerFile.path);
final List<String> command = <String>[
shellPath,
'--disable-observatory',
'--non-interactive',
'--packages=${PackageMap.globalPackagesPath}',
output,
];
final Map<String, String> environment = <String, String>{
// Chrome is the only supported browser currently.
'FLUTTER_TEST_BROWSER': 'chrome',
};
return processManager.start(command, environment: environment);
}
Future<String> compareGoldens(Uri testUri, Uint8List bytes, Uri goldenKey, bool updateGoldens) async {
final File imageFile = await (await tempDir.createTemp('image')).childFile('image').writeAsBytes(bytes);
final TestGoldenComparatorProcess process = await _processForTestFile(testUri);
process.sendCommand(imageFile, goldenKey, updateGoldens);
final Map<String, dynamic> result = await process.getResponse().timeout(const Duration(seconds: 10));
if (result == null) {
return 'unknown error';
} else {
return (result['success'] as bool) ? null : ((result['message'] as String) ?? 'does not match');
}
}
}
/// Represents a `flutter_tester` process started for golden comparison. Also
/// handles communication with the child process.
class TestGoldenComparatorProcess {
/// Creates a [TestGoldenComparatorProcess] backed by [process].
TestGoldenComparatorProcess(this.process) {
// Pipe stdout and stderr to printTrace and printError.
// Also parse stdout as a stream of JSON objects.
streamIterator = StreamIterator<Map<String, dynamic>>(
process.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.where((String line) {
printTrace('<<< $line');
return line.isNotEmpty && line[0] == '{';
})
.map<dynamic>(jsonDecode)
.cast<Map<String, dynamic>>());
process.stderr
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.forEach((String line) {
printError('<<< $line');
});
}
final Process process;
StreamIterator<Map<String, dynamic>> streamIterator;
Future<void> close() async {
await process.stdin.close();
process.kill();
}
void sendCommand(File imageFile, Uri goldenKey, bool updateGoldens) {
final Object command = jsonEncode(<String, dynamic>{
'imageFile': imageFile.path,
'key': goldenKey.toString(),
'update': updateGoldens,
});
printTrace('Preparing to send command: $command');
process.stdin.writeln(command);
}
Future<Map<String, dynamic>> getResponse() async {
final bool available = await streamIterator.moveNext();
assert(available);
return streamIterator.current;
}
static String generateBootstrap(Uri testUri) {
final File testConfigFile = findTestConfigFile(fs.file(testUri));
// Generate comparator process for the file.
return '''
import 'dart:convert'; // ignore: dart_convert_import
import 'dart:io'; // ignore: dart_io_import
import 'package:flutter_test/flutter_test.dart';
${testConfigFile != null ? "import '${Uri.file(testConfigFile.path)}' as test_config;" : ""}
void main() async {
LocalFileComparator comparator = LocalFileComparator(Uri.parse('$testUri'));
goldenFileComparator = comparator;
${testConfigFile != null ? 'test_config.main(() async {' : ''}
final commands = stdin
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.map<Object>(jsonDecode);
await for (Object command in commands) {
if (command is Map<String, dynamic>) {
File imageFile = File(command['imageFile']);
Uri goldenKey = Uri.parse(command['key']);
bool update = command['update'];
final bytes = await File(imageFile.path).readAsBytes();
if (update) {
await goldenFileComparator.update(goldenKey, bytes);
print(jsonEncode({'success': true}));
} else {
try {
bool success = await goldenFileComparator.compare(bytes, goldenKey);
print(jsonEncode({'success': success}));
} catch (ex) {
print(jsonEncode({'success': false, 'message': '\$ex'}));
}
}
} else {
print('object type is not right');
}
}
${testConfigFile != null ? '});' : ''}
}
''';
}
}

View File

@@ -48,6 +48,12 @@ Future<int> runTests(
Directory coverageDirectory,
bool web = false,
}) async {
// Configure package:test to use the Flutter engine for child processes.
final String shellPath = artifacts.getArtifactPath(Artifact.flutterTester);
if (!processManager.canRun(shellPath)) {
throwToolExit('Cannot execute Flutter tester at $shellPath');
}
// Compute the command-line arguments for package:test.
final List<String> testArgs = <String>[
if (!terminal.supportsColor)
@@ -86,7 +92,12 @@ Future<int> runTests(
hack.registerPlatformPlugin(
<Runtime>[Runtime.chrome],
() {
return FlutterWebPlatform.start(flutterProject.directory.path);
return FlutterWebPlatform.start(
flutterProject.directory.path,
updateGoldens: updateGoldens,
shellPath: shellPath,
flutterProject: flutterProject,
);
},
);
await test.main(testArgs);
@@ -97,12 +108,6 @@ Future<int> runTests(
..add('--')
..addAll(testFiles);
// Configure package:test to use the Flutter engine for child processes.
final String shellPath = artifacts.getArtifactPath(Artifact.flutterTester);
if (!processManager.canRun(shellPath)) {
throwToolExit('Cannot find Flutter shell at $shellPath');
}
final InternetAddressType serverType =
ipv6 ? InternetAddressType.IPv6 : InternetAddressType.IPv4;

View File

@@ -0,0 +1,35 @@
// Copyright 2014 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 '../base/file_system.dart';
import '../globals.dart';
/// The name of the test configuration file that will be discovered by the
/// test harness if it exists in the project directory hierarchy.
const String _kTestConfigFileName = 'flutter_test_config.dart';
/// The name of the file that signals the root of the project and that will
/// cause the test harness to stop scanning for configuration files.
const String _kProjectRootSentinel = 'pubspec.yaml';
/// Find the `flutter_test_config.dart` file for a specific test file.
File findTestConfigFile(File testFile) {
File testConfigFile;
Directory directory = testFile.parent;
while (directory.path != directory.parent.path) {
final File configFile = directory.childFile(_kTestConfigFileName);
if (configFile.existsSync()) {
printTrace('Discovered $_kTestConfigFileName in ${directory.path}');
testConfigFile = configFile;
break;
}
if (directory.childFile(_kProjectRootSentinel).existsSync()) {
printTrace('Stopping scan for $_kTestConfigFileName; '
'found project root at ${directory.path}');
break;
}
directory = directory.parent;
}
return testConfigFile;
}

View File

@@ -137,6 +137,7 @@ class ChromeLauncher {
'--no-default-browser-check',
'--disable-default-apps',
'--disable-translate',
'--window-size=2400,1800',
if (headless)
...<String>['--headless', '--disable-gpu', '--no-sandbox'],
url,
@@ -174,6 +175,7 @@ class ChromeLauncher {
return _connect(Chrome._(
port,
ChromeConnection('localhost', port),
url: url,
process: process,
remoteDebuggerUri: remoteDebuggerUri,
), skipCheck);
@@ -225,10 +227,12 @@ class Chrome {
Chrome._(
this.debugPort,
this.chromeConnection, {
this.url,
Process process,
this.remoteDebuggerUri,
}) : _process = process;
final String url;
final int debugPort;
final Process _process;
final ChromeConnection chromeConnection;