forked from firka/flutter
[web] Start support for Skia Gold (flutter/engine#29139)
This commit is contained in:
@@ -155,6 +155,12 @@ class Environment {
|
||||
'goldens',
|
||||
));
|
||||
|
||||
/// Path to the base directory to be used by Skia Gold.
|
||||
io.Directory get webUiSkiaGoldDirectory => io.Directory(pathlib.join(
|
||||
webUiDartToolDir.path,
|
||||
'skia_gold',
|
||||
));
|
||||
|
||||
/// Directory to add test results which would later be uploaded to a gcs
|
||||
/// bucket by LUCI.
|
||||
io.Directory get webUiTestResultsDirectory => io.Directory(pathlib.join(
|
||||
|
||||
@@ -49,7 +49,7 @@ class RunCommand extends Command<bool> with ArgUtils<bool> {
|
||||
'compile_tests': CompileTestsStep(),
|
||||
for (final String browserName in kAllBrowserNames)
|
||||
'run_tests_$browserName': RunTestsStep(
|
||||
browserEnvironment: getBrowserEnvironment(browserName),
|
||||
browserName: browserName,
|
||||
isDebug: false,
|
||||
doUpdateScreenshotGoldens: false,
|
||||
),
|
||||
|
||||
@@ -15,8 +15,10 @@ 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:web_test_utils/skia_client.dart';
|
||||
|
||||
import '../browser.dart';
|
||||
import '../common.dart';
|
||||
import '../environment.dart';
|
||||
import '../exceptions.dart';
|
||||
import '../pipeline.dart';
|
||||
@@ -33,17 +35,19 @@ const int _testConcurrency = int.fromEnvironment('FELT_TEST_CONCURRENCY', defaul
|
||||
/// them from another bot.
|
||||
class RunTestsStep implements PipelineStep {
|
||||
RunTestsStep({
|
||||
required this.browserEnvironment,
|
||||
required this.browserName,
|
||||
required this.isDebug,
|
||||
required this.doUpdateScreenshotGoldens,
|
||||
this.testFiles,
|
||||
});
|
||||
}) : _browserEnvironment = getBrowserEnvironment(browserName);
|
||||
|
||||
final BrowserEnvironment browserEnvironment;
|
||||
final String browserName;
|
||||
final List<FilePath>? testFiles;
|
||||
final bool isDebug;
|
||||
final bool doUpdateScreenshotGoldens;
|
||||
|
||||
final BrowserEnvironment _browserEnvironment;
|
||||
|
||||
/// Global list of shards that failed.
|
||||
///
|
||||
/// This is used to make sure that when there's a test failure anywhere we
|
||||
@@ -67,7 +71,9 @@ class RunTestsStep implements PipelineStep {
|
||||
@override
|
||||
Future<void> run() async {
|
||||
await _prepareTestResultsDirectory();
|
||||
await browserEnvironment.prepareEnvironment();
|
||||
await _browserEnvironment.prepareEnvironment();
|
||||
|
||||
final SkiaGoldClient? skiaClient = await _createSkiaClient();
|
||||
|
||||
final List<FilePath> testFiles = this.testFiles ?? findAllTests();
|
||||
|
||||
@@ -108,11 +114,12 @@ class RunTestsStep implements PipelineStep {
|
||||
if (testFiles.contains(failureSmokeTestPath)) {
|
||||
await _runTestBatch(
|
||||
testFiles: <FilePath>[failureSmokeTestPath],
|
||||
browserEnvironment: browserEnvironment,
|
||||
browserEnvironment: _browserEnvironment,
|
||||
concurrency: 1,
|
||||
expectFailure: true,
|
||||
isDebug: isDebug,
|
||||
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
|
||||
skiaClient: skiaClient,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -120,11 +127,12 @@ class RunTestsStep implements PipelineStep {
|
||||
if (unitTestFiles.isNotEmpty) {
|
||||
await _runTestBatch(
|
||||
testFiles: unitTestFiles,
|
||||
browserEnvironment: browserEnvironment,
|
||||
browserEnvironment: _browserEnvironment,
|
||||
concurrency: _testConcurrency,
|
||||
expectFailure: false,
|
||||
isDebug: isDebug,
|
||||
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
|
||||
skiaClient: skiaClient,
|
||||
);
|
||||
_checkExitCode('Unit tests');
|
||||
}
|
||||
@@ -134,11 +142,12 @@ class RunTestsStep implements PipelineStep {
|
||||
if (screenshotTestFiles.isNotEmpty) {
|
||||
await _runTestBatch(
|
||||
testFiles: screenshotTestFiles,
|
||||
browserEnvironment: browserEnvironment,
|
||||
browserEnvironment: _browserEnvironment,
|
||||
concurrency: 1,
|
||||
expectFailure: false,
|
||||
isDebug: isDebug,
|
||||
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
|
||||
skiaClient: skiaClient,
|
||||
);
|
||||
_checkExitCode('Golden tests');
|
||||
}
|
||||
@@ -163,6 +172,47 @@ class RunTestsStep implements PipelineStep {
|
||||
}
|
||||
return message.toString();
|
||||
}
|
||||
|
||||
Future<SkiaGoldClient?> _createSkiaClient() async {
|
||||
final SkiaGoldClient skiaClient = SkiaGoldClient(
|
||||
environment.webUiSkiaGoldDirectory,
|
||||
browserName: browserName,
|
||||
);
|
||||
|
||||
if (!await _checkSkiaClient(skiaClient)) {
|
||||
print('WARNING: Unable to use Skia Client in this environment.');
|
||||
return null;
|
||||
}
|
||||
|
||||
return skiaClient;
|
||||
}
|
||||
|
||||
/// Checks whether the Skia Client is usable in this environment.
|
||||
Future<bool> _checkSkiaClient(SkiaGoldClient skiaClient) async {
|
||||
// Now let's check whether Skia Gold is reachable or not.
|
||||
if (isLuci) {
|
||||
if (SkiaGoldClient.isAvailable) {
|
||||
try {
|
||||
await skiaClient.auth();
|
||||
return true;
|
||||
} catch (e) {
|
||||
print(e);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
// Check if we can reach Gold.
|
||||
await skiaClient.getExpectationForTest('');
|
||||
return true;
|
||||
} on io.OSError catch (_) {
|
||||
print('OSError occurred, could not reach Gold.');
|
||||
} on io.SocketException catch (_) {
|
||||
print('SocketException occurred, could not reach Gold.');
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _prepareTestResultsDirectory() async {
|
||||
@@ -183,6 +233,7 @@ Future<void> _runTestBatch({
|
||||
required bool doUpdateScreenshotGoldens,
|
||||
required int concurrency,
|
||||
required bool expectFailure,
|
||||
required SkiaGoldClient? skiaClient,
|
||||
}) async {
|
||||
final String configurationFilePath = pathlib.join(
|
||||
environment.webUiRootDir.path,
|
||||
@@ -219,6 +270,7 @@ Future<void> _runTestBatch({
|
||||
// It doesn't make sense to update a screenshot for a test that is
|
||||
// expected to fail.
|
||||
doUpdateScreenshotGoldens: !expectFailure && doUpdateScreenshotGoldens,
|
||||
skiaClient: skiaClient,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ import 'package:test_core/src/util/stack_trace_mapper.dart';
|
||||
import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
import 'package:web_test_utils/goldens.dart';
|
||||
import 'package:web_test_utils/image_compare.dart';
|
||||
import 'package:web_test_utils/skia_client.dart';
|
||||
|
||||
import 'browser.dart';
|
||||
import 'common.dart';
|
||||
@@ -51,6 +52,7 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
static Future<BrowserPlatform> start({
|
||||
required BrowserEnvironment browserEnvironment,
|
||||
required bool doUpdateScreenshotGoldens,
|
||||
required SkiaGoldClient? skiaClient,
|
||||
}) async {
|
||||
final shelf_io.IOServer server = shelf_io.IOServer(await HttpMultiServer.loopback(0));
|
||||
return BrowserPlatform._(
|
||||
@@ -59,6 +61,7 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
isDebug: Configuration.current.pauseAfterLoad,
|
||||
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
|
||||
packageConfig: await loadPackageConfigUri((await Isolate.packageConfig)!),
|
||||
skiaClient: skiaClient,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -98,12 +101,17 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
|
||||
final PackageConfig packageConfig;
|
||||
|
||||
/// A client for communicating with the Skia Gold backend to fetch, compare
|
||||
/// and update images.
|
||||
final SkiaGoldClient? skiaClient;
|
||||
|
||||
BrowserPlatform._({
|
||||
required this.browserEnvironment,
|
||||
required this.server,
|
||||
required this.isDebug,
|
||||
required this.doUpdateScreenshotGoldens,
|
||||
required this.packageConfig,
|
||||
required this.skiaClient,
|
||||
}) : _screenshotManager = browserEnvironment.getScreenshotManager() {
|
||||
// The cascade of request handlers.
|
||||
final shelf.Cascade cascade = shelf.Cascade()
|
||||
@@ -267,9 +275,6 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
write = true;
|
||||
}
|
||||
|
||||
filename =
|
||||
filename.replaceAll('.png', '${_screenshotManager!.filenameSuffix}.png');
|
||||
|
||||
String goldensDirectory;
|
||||
if (filename.startsWith('__local__')) {
|
||||
filename = filename.substring('__local__/'.length);
|
||||
@@ -297,13 +302,16 @@ class BrowserPlatform extends PlatformPlugin {
|
||||
final Image screenshot = await _screenshotManager!.capture(regionAsRectange);
|
||||
|
||||
return compareImage(
|
||||
screenshot,
|
||||
doUpdateScreenshotGoldens,
|
||||
filename,
|
||||
pixelComparison,
|
||||
maxDiffRateFailure,
|
||||
goldensDirectory: goldensDirectory,
|
||||
write: write);
|
||||
screenshot,
|
||||
doUpdateScreenshotGoldens,
|
||||
filename,
|
||||
pixelComparison,
|
||||
maxDiffRateFailure,
|
||||
skiaClient,
|
||||
goldensDirectory: goldensDirectory,
|
||||
filenameSuffix: _screenshotManager!.filenameSuffix,
|
||||
write: write,
|
||||
);
|
||||
}
|
||||
|
||||
static const Map<String, String> contentTypes = <String, String>{
|
||||
|
||||
@@ -10,8 +10,6 @@ import 'package:path/path.dart' as path;
|
||||
|
||||
import 'package:watcher/src/watch_event.dart';
|
||||
|
||||
import 'browser.dart';
|
||||
import 'common.dart';
|
||||
import 'pipeline.dart';
|
||||
import 'steps/compile_tests_step.dart';
|
||||
import 'steps/run_tests_step.dart';
|
||||
@@ -111,7 +109,7 @@ class TestCommand extends Command<bool> with ArgUtils<bool> {
|
||||
bool get runAllTests => targets.isEmpty;
|
||||
|
||||
/// The name of the browser to run tests in.
|
||||
String get browser => stringArg('browser');
|
||||
String get browserName => stringArg('browser');
|
||||
|
||||
/// When running screenshot tests writes them to the file system into
|
||||
/// ".dart_tool/goldens".
|
||||
@@ -122,8 +120,6 @@ class TestCommand extends Command<bool> with ArgUtils<bool> {
|
||||
|
||||
@override
|
||||
Future<bool> run() async {
|
||||
final BrowserEnvironment browserEnvironment = getBrowserEnvironment(browser);
|
||||
|
||||
final List<FilePath> testFiles = runAllTests
|
||||
? findAllTests()
|
||||
: targetFiles;
|
||||
@@ -135,7 +131,7 @@ class TestCommand extends Command<bool> with ArgUtils<bool> {
|
||||
testFiles: testFiles,
|
||||
),
|
||||
RunTestsStep(
|
||||
browserEnvironment: browserEnvironment,
|
||||
browserName: browserName,
|
||||
testFiles: testFiles,
|
||||
isDebug: isDebug,
|
||||
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
|
||||
|
||||
@@ -176,6 +176,12 @@ class Environment {
|
||||
'goldens',
|
||||
));
|
||||
|
||||
/// Path to the base directory to be used by Skia Gold.
|
||||
io.Directory get webUiSkiaGoldDirectory => io.Directory(pathlib.join(
|
||||
webUiDartToolDir.path,
|
||||
'skia_gold',
|
||||
));
|
||||
|
||||
/// Directory to add test results which would later be uploaded to a gcs
|
||||
/// bucket by LUCI.
|
||||
io.Directory get webUiTestResultsDirectory => io.Directory(pathlib.join(
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
import 'dart:io' as io;
|
||||
import 'package:image/image.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
|
||||
import 'package:yaml/yaml.dart';
|
||||
@@ -104,7 +103,7 @@ class ImageDiff {
|
||||
}
|
||||
|
||||
static int _average(Iterable<int> values) {
|
||||
return values.reduce((a, b) => a + b) ~/ values.length;
|
||||
return values.reduce((int a, int b) => a + b) ~/ values.length;
|
||||
}
|
||||
|
||||
/// The value of the pixel at [x] and [y] coordinates.
|
||||
@@ -129,9 +128,9 @@ class ImageDiff {
|
||||
_reflectedPixel(image, x + 1, y + 1),
|
||||
];
|
||||
return <int>[
|
||||
_average(pixels.map((p) => getRed(p))),
|
||||
_average(pixels.map((p) => getGreen(p))),
|
||||
_average(pixels.map((p) => getBlue(p))),
|
||||
_average(pixels.map((int p) => getRed(p))),
|
||||
_average(pixels.map((int p) => getGreen(p))),
|
||||
_average(pixels.map((int p) => getBlue(p))),
|
||||
];
|
||||
case PixelComparison.precise:
|
||||
final int pixel = image.getPixel(x, y);
|
||||
@@ -141,7 +140,7 @@ class ImageDiff {
|
||||
getBlue(pixel),
|
||||
];
|
||||
default:
|
||||
throw 'Unrecognized pixel comparison value: ${pixelComparison}';
|
||||
throw 'Unrecognized pixel comparison value: $pixelComparison';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,7 +187,7 @@ class ImageDiff {
|
||||
|
||||
/// Returns text explaining pixel difference rate.
|
||||
String getPrintableDiffFilesInfo(double diffRate, double maxRate) =>
|
||||
'(${((diffRate) * 100).toStringAsFixed(4)}% of pixels were different. '
|
||||
'(${(diffRate * 100).toStringAsFixed(4)}% of pixels were different. '
|
||||
'Maximum allowed rate is: ${(maxRate * 100).toStringAsFixed(4)}%).';
|
||||
|
||||
/// Downloads the repository that stores the golden files.
|
||||
|
||||
@@ -9,8 +9,15 @@ import 'package:path/path.dart' as p;
|
||||
|
||||
import 'environment.dart';
|
||||
import 'goldens.dart';
|
||||
import 'skia_client.dart';
|
||||
|
||||
/// Compares a screenshot taken through a test with it's golden.
|
||||
/// Whether this code is running on LUCI.
|
||||
bool _isLuci = Platform.environment.containsKey('SWARMING_TASK_ID') && Platform.environment.containsKey('GOLDCTL');
|
||||
bool _isPreSubmit = _isLuci && Platform.environment.containsKey('GOLD_TRYJOB');
|
||||
bool _isPostSubmit = _isLuci && !_isPreSubmit;
|
||||
|
||||
|
||||
/// Compares a screenshot taken through a test with its golden.
|
||||
///
|
||||
/// Used by Flutter Web Engine unit tests and the integration tests.
|
||||
///
|
||||
@@ -18,15 +25,29 @@ import 'goldens.dart';
|
||||
/// is simply `OK`, however when they fail it contains a detailed explanation
|
||||
/// on which files are compared, their absolute locations and an HTML page
|
||||
/// that the developer can see the comparison.
|
||||
String compareImage(
|
||||
Future<String> compareImage(
|
||||
Image screenshot,
|
||||
bool doUpdateScreenshotGoldens,
|
||||
String filename,
|
||||
PixelComparison pixelComparison,
|
||||
double maxDiffRateFailure, {
|
||||
double maxDiffRateFailure,
|
||||
SkiaGoldClient? skiaClient, {
|
||||
// TODO(mdebbar): Remove these args with goldens repo.
|
||||
String goldensDirectory = '',
|
||||
String filenameSuffix = '',
|
||||
bool write = false,
|
||||
}) {
|
||||
}) async {
|
||||
if (_isLuci && skiaClient != null) {
|
||||
// This is temporary to get started by uploading existing screenshots to
|
||||
// Skia Gold. The next step would be to actually use Skia Gold for
|
||||
// comparison.
|
||||
|
||||
// TODO(mdebbar): Use Skia Gold for comparison, not only for uploading.
|
||||
await _uploadToSkiaGold(skiaClient, screenshot, filename);
|
||||
}
|
||||
|
||||
filename = filename.replaceAll('.png', '$filenameSuffix.png');
|
||||
|
||||
final Environment environment = Environment();
|
||||
if (goldensDirectory.isEmpty) {
|
||||
goldensDirectory = p.join(
|
||||
@@ -137,3 +158,42 @@ Golden file $filename did not match the image generated by the test.
|
||||
}
|
||||
return 'OK';
|
||||
}
|
||||
|
||||
Future<void> _uploadToSkiaGold(
|
||||
SkiaGoldClient skiaClient,
|
||||
Image screenshot,
|
||||
String filename,
|
||||
) async {
|
||||
// Can't upload to Gold Skia unless running in LUCI.
|
||||
assert(_isLuci);
|
||||
|
||||
// Write the screenshot to the file system so it can be consumed by the
|
||||
// `goldctl` tool.
|
||||
final File goldenFile = File(p.join(environment.webUiSkiaGoldDirectory.path, filename));
|
||||
await goldenFile.writeAsBytes(encodePng(screenshot), flush: true);
|
||||
|
||||
if (_isPreSubmit) {
|
||||
return _uploadInPreSubmit(skiaClient, filename, goldenFile);
|
||||
}
|
||||
if (_isPostSubmit) {
|
||||
return _uploadInPostSubmit(skiaClient, filename, goldenFile);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _uploadInPreSubmit(
|
||||
SkiaGoldClient skiaClient,
|
||||
String filename,
|
||||
File goldenFile,
|
||||
) {
|
||||
assert(_isPreSubmit);
|
||||
return skiaClient.tryjobAdd(filename, goldenFile);
|
||||
}
|
||||
|
||||
Future<void> _uploadInPostSubmit(
|
||||
SkiaGoldClient skiaClient,
|
||||
String filename,
|
||||
File goldenFile,
|
||||
) {
|
||||
assert(_isPostSubmit);
|
||||
return skiaClient.imgtestAdd(filename, goldenFile);
|
||||
}
|
||||
|
||||
406
engine/src/flutter/web_sdk/web_test_utils/lib/skia_client.dart
Normal file
406
engine/src/flutter/web_sdk/web_test_utils/lib/skia_client.dart
Normal file
@@ -0,0 +1,406 @@
|
||||
// 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:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:process/process.dart';
|
||||
|
||||
import 'environment.dart';
|
||||
|
||||
const String _kGoldctlKey = 'GOLDCTL';
|
||||
|
||||
const String _skiaGoldHost = 'https://flutter-engine-gold.skia.org';
|
||||
const String _instance = 'flutter-engine';
|
||||
|
||||
/// A client for uploading image tests and making baseline requests to the
|
||||
/// Flutter Gold Dashboard.
|
||||
class SkiaGoldClient {
|
||||
/// Creates a [SkiaGoldClient] with the given [workDirectory].
|
||||
///
|
||||
/// The [browserName] parameter is the name of the browser that generated the
|
||||
/// screenshots.
|
||||
SkiaGoldClient(this.workDirectory, { required this.browserName });
|
||||
|
||||
/// Whether the Skia Gold client is available and can be used in this
|
||||
/// environment.
|
||||
static bool get isAvailable => Platform.environment.containsKey(_kGoldctlKey);
|
||||
|
||||
/// The name of the browser running the tests.
|
||||
final String browserName;
|
||||
|
||||
/// A controller for launching sub-processes.
|
||||
final ProcessManager process = const LocalProcessManager();
|
||||
|
||||
/// A client for making Http requests to the Flutter Gold dashboard.
|
||||
final HttpClient httpClient = HttpClient();
|
||||
|
||||
/// The local [Directory] for the current test context. In this directory, the
|
||||
/// client will create image and JSON files for the `goldctl` tool to use.
|
||||
final Directory workDirectory;
|
||||
|
||||
String get _tempPath => path.join(workDirectory.path, 'temp');
|
||||
String get _keysPath => path.join(workDirectory.path, 'keys.json');
|
||||
String get _failuresPath => path.join(workDirectory.path, 'failures.json');
|
||||
|
||||
/// Indicates whether the `goldctl` tool has been initialized for the current
|
||||
/// test context.
|
||||
bool _isInitialized = false;
|
||||
|
||||
/// Indicates whether the client has already been authorized to communicate
|
||||
/// with the Skia Gold backend.
|
||||
bool get _isAuthorized {
|
||||
final File authFile = File(path.join(_tempPath, 'auth_opt.json'));
|
||||
|
||||
if(authFile.existsSync()) {
|
||||
final String contents = authFile.readAsStringSync();
|
||||
final Map<String, dynamic> decoded = json.decode(contents) as Map<String, dynamic>;
|
||||
return !(decoded['GSUtil'] as bool);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// The path to the local [Directory] where the `goldctl` tool is hosted.
|
||||
String get _goldctl {
|
||||
assert(
|
||||
isAvailable,
|
||||
'Trying to use `goldctl` in an environment where it is not available',
|
||||
);
|
||||
return Platform.environment[_kGoldctlKey]!;
|
||||
}
|
||||
|
||||
/// Prepares the local work space for golden file testing and calls the
|
||||
/// `goldctl auth` command.
|
||||
///
|
||||
/// This ensures that the `goldctl` tool is authorized and ready for testing.
|
||||
Future<void> auth() async {
|
||||
if (_isAuthorized)
|
||||
return;
|
||||
final List<String> authCommand = <String>[
|
||||
_goldctl,
|
||||
'auth',
|
||||
'--work-dir', _tempPath,
|
||||
'--luci',
|
||||
];
|
||||
|
||||
final ProcessResult result = await process.run(authCommand);
|
||||
|
||||
if (result.exitCode != 0) {
|
||||
final StringBuffer buf = StringBuffer()
|
||||
..writeln('Skia Gold authorization failed.')
|
||||
..writeln('Luci environments authenticate using the file provided '
|
||||
'by LUCI_CONTEXT. There may be an error with this file or Gold '
|
||||
'authentication.')
|
||||
..writeln('Debug information for Gold:')
|
||||
..writeln('stdout: ${result.stdout}')
|
||||
..writeln('stderr: ${result.stderr}');
|
||||
throw Exception(buf.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes the `imgtest init` command in the `goldctl` tool.
|
||||
///
|
||||
/// The `imgtest` command collects and uploads test results to the Skia Gold
|
||||
/// backend, the `init` argument initializes the current test.
|
||||
Future<void> _imgtestInit() async {
|
||||
if (_isInitialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
final File keys = File(_keysPath);
|
||||
final File failures = File(_failuresPath);
|
||||
|
||||
await keys.writeAsString(_getKeysJSON());
|
||||
await failures.create();
|
||||
final String commitHash = await _getCurrentCommit();
|
||||
|
||||
final List<String> imgtestInitCommand = <String>[
|
||||
_goldctl,
|
||||
'imgtest', 'init',
|
||||
'--instance', _instance,
|
||||
'--work-dir', _tempPath,
|
||||
'--commit', commitHash,
|
||||
'--keys-file', keys.path,
|
||||
'--failure-file', failures.path,
|
||||
'--passfail',
|
||||
];
|
||||
|
||||
if (imgtestInitCommand.contains(null)) {
|
||||
final StringBuffer buf = StringBuffer()
|
||||
..writeln('A null argument was provided for Skia Gold imgtest init.')
|
||||
..writeln('Please confirm the settings of your golden file test.')
|
||||
..writeln('Arguments provided:');
|
||||
imgtestInitCommand.forEach(buf.writeln);
|
||||
throw Exception(buf.toString());
|
||||
}
|
||||
|
||||
final ProcessResult result = await process.run(imgtestInitCommand);
|
||||
|
||||
if (result.exitCode != 0) {
|
||||
final StringBuffer buf = StringBuffer()
|
||||
..writeln('Skia Gold imgtest init failed.')
|
||||
..writeln('An error occurred when initializing golden file test with ')
|
||||
..writeln('goldctl.')
|
||||
..writeln()
|
||||
..writeln('Debug information for Gold:')
|
||||
..writeln('stdout: ${result.stdout}')
|
||||
..writeln('stderr: ${result.stderr}');
|
||||
throw Exception(buf.toString());
|
||||
}
|
||||
_isInitialized = true;
|
||||
}
|
||||
|
||||
/// Executes the `imgtest add` command in the `goldctl` tool.
|
||||
///
|
||||
/// The `imgtest` command collects and uploads test results to the Skia Gold
|
||||
/// backend, the `add` argument uploads the current image test. A response is
|
||||
/// returned from the invocation of this command that indicates a pass or fail
|
||||
/// result.
|
||||
///
|
||||
/// The [testName] and [goldenFile] parameters reference the current
|
||||
/// comparison being evaluated.
|
||||
Future<bool> imgtestAdd(String testName, File goldenFile) async {
|
||||
await _imgtestInit();
|
||||
|
||||
final List<String> imgtestCommand = <String>[
|
||||
_goldctl,
|
||||
'imgtest', 'add',
|
||||
'--work-dir', _tempPath,
|
||||
'--test-name', cleanTestName(testName),
|
||||
'--png-file', goldenFile.path,
|
||||
];
|
||||
|
||||
final ProcessResult result = await process.run(imgtestCommand);
|
||||
|
||||
if (result.exitCode != 0) {
|
||||
// We do not want to throw for non-zero exit codes here, as an intentional
|
||||
// change or new golden file test expect non-zero exit codes. Logging here
|
||||
// is meant to inform when an unexpected result occurs.
|
||||
print('goldctl imgtest add stdout: ${result.stdout}');
|
||||
print('goldctl imgtest add stderr: ${result.stderr}');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Executes the `imgtest init` command in the `goldctl` tool for tryjobs.
|
||||
///
|
||||
/// The `imgtest` command collects and uploads test results to the Skia Gold
|
||||
/// backend, the `init` argument initializes the current tryjob.
|
||||
Future<void> _tryjobInit() async {
|
||||
if (_isInitialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
final File keys = File(_keysPath);
|
||||
final File failures = File(_failuresPath);
|
||||
|
||||
await keys.writeAsString(_getKeysJSON());
|
||||
await failures.create();
|
||||
final String commitHash = await _getCurrentCommit();
|
||||
|
||||
final List<String> imgtestInitCommand = <String>[
|
||||
_goldctl,
|
||||
'imgtest', 'init',
|
||||
'--instance', _instance,
|
||||
'--work-dir', _tempPath,
|
||||
'--commit', commitHash,
|
||||
'--keys-file', keys.path,
|
||||
'--failure-file', failures.path,
|
||||
'--passfail',
|
||||
'--crs', 'github',
|
||||
'--patchset_id', commitHash,
|
||||
...getCIArguments(),
|
||||
];
|
||||
|
||||
if (imgtestInitCommand.contains(null)) {
|
||||
final StringBuffer buf = StringBuffer()
|
||||
..writeln('A null argument was provided for Skia Gold tryjob init.')
|
||||
..writeln('Please confirm the settings of your golden file test.')
|
||||
..writeln('Arguments provided:');
|
||||
imgtestInitCommand.forEach(buf.writeln);
|
||||
throw Exception(buf.toString());
|
||||
}
|
||||
|
||||
final ProcessResult result = await process.run(imgtestInitCommand);
|
||||
|
||||
if (result.exitCode != 0) {
|
||||
final StringBuffer buf = StringBuffer()
|
||||
..writeln('Skia Gold tryjobInit failure.')
|
||||
..writeln('An error occurred when initializing golden file tryjob with ')
|
||||
..writeln('goldctl.')
|
||||
..writeln()
|
||||
..writeln('Debug information for Gold:')
|
||||
..writeln('stdout: ${result.stdout}')
|
||||
..writeln('stderr: ${result.stderr}');
|
||||
throw Exception(buf.toString());
|
||||
}
|
||||
_isInitialized = true;
|
||||
}
|
||||
|
||||
/// Executes the `imgtest add` command in the `goldctl` tool for tryjobs.
|
||||
///
|
||||
/// The `imgtest` command collects and uploads test results to the Skia Gold
|
||||
/// backend, the `add` argument uploads the current image test. A response is
|
||||
/// returned from the invocation of this command that indicates a pass or fail
|
||||
/// result for the tryjob.
|
||||
///
|
||||
/// The [testName] and [goldenFile] parameters reference the current
|
||||
/// comparison being evaluated.
|
||||
Future<void> tryjobAdd(String testName, File goldenFile) async {
|
||||
await _tryjobInit();
|
||||
|
||||
final List<String> imgtestCommand = <String>[
|
||||
_goldctl,
|
||||
'imgtest', 'add',
|
||||
'--work-dir', _tempPath,
|
||||
'--test-name', cleanTestName(testName),
|
||||
'--png-file', goldenFile.path,
|
||||
];
|
||||
|
||||
final ProcessResult result = await process.run(imgtestCommand);
|
||||
|
||||
final String resultStdout = result.stdout.toString();
|
||||
if (result.exitCode != 0 &&
|
||||
!(resultStdout.contains('Untriaged') || resultStdout.contains('negative image'))) {
|
||||
final StringBuffer buf = StringBuffer()
|
||||
..writeln('Unexpected Gold tryjobAdd failure.')
|
||||
..writeln('Tryjob execution for golden file test $testName failed for')
|
||||
..writeln('a reason unrelated to pixel comparison.')
|
||||
..writeln()
|
||||
..writeln('Debug information for Gold:')
|
||||
..writeln('stdout: ${result.stdout}')
|
||||
..writeln('stderr: ${result.stderr}')
|
||||
..writeln();
|
||||
throw Exception(buf.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the latest positive digest for the given test known to Skia Gold
|
||||
/// at head.
|
||||
Future<String?> getExpectationForTest(String testName) async {
|
||||
late String? expectation;
|
||||
final String traceID = getTraceID(testName);
|
||||
await HttpOverrides.runWithHttpOverrides<Future<void>>(() async {
|
||||
final Uri requestForExpectations = Uri.parse(
|
||||
'$_skiaGoldHost/json/v2/latestpositivedigest/$traceID'
|
||||
);
|
||||
late String rawResponse;
|
||||
try {
|
||||
final HttpClientRequest request = await httpClient.getUrl(requestForExpectations);
|
||||
final HttpClientResponse response = await request.close();
|
||||
rawResponse = await utf8.decodeStream(response);
|
||||
final dynamic jsonResponse = json.decode(rawResponse);
|
||||
if (jsonResponse is! Map<String, dynamic>)
|
||||
throw const FormatException('Skia gold expectations do not match expected format.');
|
||||
expectation = jsonResponse['digest'] as String?;
|
||||
} on FormatException catch (error) {
|
||||
print(
|
||||
'Formatting error detected requesting expectations from Flutter Gold.\n'
|
||||
'error: $error\n'
|
||||
'url: $requestForExpectations\n'
|
||||
'response: $rawResponse'
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
},
|
||||
SkiaGoldHttpOverrides(),
|
||||
);
|
||||
return expectation;
|
||||
}
|
||||
|
||||
/// Returns a list of bytes representing the golden image retrieved from the
|
||||
/// Skia Gold dashboard.
|
||||
///
|
||||
/// The provided image hash represents an expectation from Skia Gold.
|
||||
Future<List<int>>getImageBytes(String imageHash) async {
|
||||
final List<int> imageBytes = <int>[];
|
||||
await HttpOverrides.runWithHttpOverrides<Future<void>>(() async {
|
||||
final Uri requestForImage = Uri.parse(
|
||||
'$_skiaGoldHost/img/images/$imageHash.png',
|
||||
);
|
||||
|
||||
final HttpClientRequest request = await httpClient.getUrl(requestForImage);
|
||||
final HttpClientResponse response = await request.close();
|
||||
await response.forEach((List<int> bytes) => imageBytes.addAll(bytes));
|
||||
},
|
||||
SkiaGoldHttpOverrides(),
|
||||
);
|
||||
return imageBytes;
|
||||
}
|
||||
|
||||
/// Returns the current commit hash of the engine repository.
|
||||
Future<String> _getCurrentCommit() async {
|
||||
final Directory webUiRoot = environment.webUiRootDir;
|
||||
if (!webUiRoot.existsSync()) {
|
||||
throw Exception('Web Engine root could not be found: $webUiRoot\n');
|
||||
} else {
|
||||
final ProcessResult revParse = await process.run(
|
||||
<String>['git', 'rev-parse', 'HEAD'],
|
||||
workingDirectory: webUiRoot.path,
|
||||
);
|
||||
if (revParse.exitCode != 0) {
|
||||
throw Exception('Current commit of Web Engine can not be found.');
|
||||
}
|
||||
return (revParse.stdout as String).trim();
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a Map of key value pairs used to uniquely identify the
|
||||
/// configuration that generated the given golden file.
|
||||
///
|
||||
/// Currently, the only key value pairs being tracked are the platform and
|
||||
/// browser the image was rendered on.
|
||||
Map<String, dynamic> _getKeys() {
|
||||
return <String, dynamic>{
|
||||
'CI': 'luci',
|
||||
'Platform': Platform.operatingSystem,
|
||||
'Browser': browserName,
|
||||
};
|
||||
}
|
||||
|
||||
/// Same as [_getKeys] but encodes it in a JSON string.
|
||||
String _getKeysJSON() {
|
||||
return json.encode(_getKeys());
|
||||
}
|
||||
|
||||
/// Removes the file extension from the [fileName] to represent the test name
|
||||
/// properly.
|
||||
String cleanTestName(String fileName) {
|
||||
return fileName.split(path.extension(fileName))[0];
|
||||
}
|
||||
|
||||
/// Returns a list of arguments for initializing a tryjob based on the testing
|
||||
/// environment.
|
||||
List<String> getCIArguments() {
|
||||
final String jobId = Platform.environment['LOGDOG_STREAM_PREFIX']!.split('/').last;
|
||||
final List<String> refs = Platform.environment['GOLD_TRYJOB']!.split('/');
|
||||
final String pullRequest = refs[refs.length - 2];
|
||||
|
||||
return <String>[
|
||||
'--changelist', pullRequest,
|
||||
'--cis', 'buildbucket',
|
||||
'--jobid', jobId,
|
||||
];
|
||||
}
|
||||
|
||||
/// Returns a trace id based on the current testing environment to lookup
|
||||
/// the latest positive digest on Skia Gold with a hex-encoded md5 hash of
|
||||
/// the image keys.
|
||||
String getTraceID(String testName) {
|
||||
final Map<String, dynamic> keys = <String, dynamic>{
|
||||
..._getKeys(),
|
||||
'name': testName,
|
||||
'source_type': _instance,
|
||||
};
|
||||
final String jsonTrace = json.encode(keys);
|
||||
final String md5Sum = md5.convert(utf8.encode(jsonTrace)).toString();
|
||||
return md5Sum;
|
||||
}
|
||||
}
|
||||
|
||||
/// Used to make HttpRequests during testing.
|
||||
class SkiaGoldHttpOverrides extends HttpOverrides { }
|
||||
@@ -5,7 +5,12 @@ environment:
|
||||
sdk: ">=2.12.0-0 <3.0.0"
|
||||
|
||||
dependencies:
|
||||
path: 1.8.0
|
||||
collection: 1.15.0
|
||||
crypto: 3.0.1
|
||||
image: 3.0.1
|
||||
js: 0.6.3
|
||||
meta: 1.3.0
|
||||
path: 1.8.0
|
||||
process: 4.2.3
|
||||
typed_data: 1.3.0
|
||||
yaml: 3.0.0
|
||||
|
||||
Reference in New Issue
Block a user