Store screenshot test output as Cirrus artifacts; do fuzzy comparison of non-matching screenshot pixels (flutter/engine#12274)

- Store screenshot test output as Cirrus artifacts
- Do fuzzy comparison of non-matching screenshot pixels
- Make screenshot tests fail on Cirrus
This commit is contained in:
Yegor
2019-09-20 14:46:00 -07:00
committed by GitHub
parent 1cad708800
commit e08ce018a4
3 changed files with 179 additions and 34 deletions

View File

@@ -36,7 +36,6 @@ task:
cd $ENGINE_PATH/src
./flutter/testing/run_tests.sh host_debug_unopt
test_web_engine_script: |
google-chrome --version
cd $ENGINE_PATH/src/flutter/web_sdk/web_engine_tester
$ENGINE_PATH/src/out/host_debug_unopt/dart-sdk/bin/pub get
cd $ENGINE_PATH/src/flutter/lib/web_ui
@@ -44,6 +43,9 @@ task:
export FELT="$ENGINE_PATH/src/out/host_debug_unopt/dart-sdk/bin/dart dev/felt.dart"
$FELT check-licenses
CHROME_NO_SANDBOX=true $FELT test
always:
web_engine_test_artifacts:
path: test_results/*
fetch_framework_script: |
mkdir -p $FRAMEWORK_PATH
cd $FRAMEWORK_PATH

View File

@@ -1,9 +1,18 @@
// 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:image/image.dart';
void main(List<String> args) {
final io.File fileA = io.File(args[0]);
final io.File fileB = io.File(args[1]);
final Image imageA = decodeNamedImage(fileA.readAsBytesSync(), 'a.png');
final Image imageB = decodeNamedImage(fileB.readAsBytesSync(), 'b.png');
final ImageDiff diff = ImageDiff(golden: imageA, other: imageB);
print('Diff: ${(diff.rate * 100).toStringAsFixed(4)}');
}
/// This class encapsulates visually diffing an Image with any other.
/// Both images need to be the exact same size.
class ImageDiff {
@@ -33,10 +42,65 @@ class ImageDiff {
int _pixelCount = 0;
int _wrongPixels = 0;
/// That would be the distance between black and white.
static final double _maxTheoreticalColorDistance = Color.distance(
<int>[255, 255, 255], // white
<int>[0, 0, 0], // black
false,
);
// If the normalized color difference of a pixel is greater than this number,
// we consider it a wrong pixel.
static const double _kColorDistanceThreshold = 0.1;
final int _colorOk = Color.fromRgb(255, 255, 255);
final int _colorBadPixel = Color.fromRgb(255, 0, 0);
final int _colorExpectedPixel = Color.fromRgb(0, 255, 0);
/// Reads a pixel value out of [image] at [x] and [y].
///
/// If the pixel is out of bounds, reflects the [x] and [y] coordinates off
/// the border back into the image treating the border like a mirror.
static int _reflectedPixel(Image image, int x, int y) {
x = x.abs();
if (x == image.width) {
x = image.width - 2;
}
y = y.abs();
if (y == image.height) {
y = image.height - 2;
}
return image.getPixel(x, y);
}
static int _average(Iterable<int> values) {
return values.reduce((a, b) => a + b) ~/ values.length;
}
/// Reads the RGBA values of the average of the 3x3 box of pixels centered at [x] and [y].
static List<int> _getFuzzyRgb(Image image, int x, int y) {
final List<int> pixels = <int>[
_reflectedPixel(image, x - 1, y - 1),
_reflectedPixel(image, x - 1, y),
_reflectedPixel(image, x - 1, y + 1),
_reflectedPixel(image, x, y - 1),
_reflectedPixel(image, x, y),
_reflectedPixel(image, x, y + 1),
_reflectedPixel(image, x + 1, y - 1),
_reflectedPixel(image, x + 1, y),
_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))),
];
}
void _computeDiff() {
int goldenWidth = golden.width;
int goldenHeight = golden.height;
@@ -47,13 +111,16 @@ class ImageDiff {
if (goldenWidth == other.width && goldenHeight == other.height) {
for(int y = 0; y < goldenHeight; y++) {
for (int x = 0; x < goldenWidth; x++) {
int goldenPixel = golden.getPixel(x, y);
int otherPixel = other.getPixel(x, y);
if (goldenPixel == otherPixel) {
final bool isExactlySame = golden.getPixel(x, y) == other.getPixel(x, y);
final List<int> goldenPixel = _getFuzzyRgb(golden, x, y);
final List<int> otherPixel = _getFuzzyRgb(other, x, y);
final double colorDistance = Color.distance(goldenPixel, otherPixel, false) / _maxTheoreticalColorDistance;
if (isExactlySame || colorDistance < _kColorDistanceThreshold) {
diff.setPixel(x, y, _colorOk);
} else {
if (getLuminance(goldenPixel) < getLuminance(otherPixel)) {
final int goldenLuminance = getLuminanceRgb(goldenPixel[0], goldenPixel[1], goldenPixel[2]);
final int otherLuminance = getLuminanceRgb(otherPixel[0], otherPixel[1], otherPixel[2]);
if (goldenLuminance < otherLuminance) {
diff.setPixel(x, y, _colorExpectedPixel);
} else {
diff.setPixel(x, y, _colorBadPixel);
@@ -69,12 +136,7 @@ class ImageDiff {
}
}
// Returns text with info about the files we just compared
String getPrintableDiffFilesInfo(diffRate, maxRate, filename, outputPath, diffPath) => '''
(${((diffRate) * 100).toStringAsFixed(4)}% different pixels. Max: ${((maxRate) * 100).toStringAsFixed(4)}%).
* Output image: ${outputPath}
* Diff pixels: ${diffPath}
To update the golden file call matchGoldenFile('$filename', write: true).
''';
// Returns text explaining pixel difference rate.
String getPrintableDiffFilesInfo(double diffRate, double maxRate) =>
'(${((diffRate) * 100).toStringAsFixed(4)}% of pixels were different. '
'Maximum allowed rate is: ${(maxRate * 100).toStringAsFixed(4)}%).';

View File

@@ -6,7 +6,6 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import 'package:async/async.dart';
import 'package:http_multi_server/http_multi_server.dart';
@@ -49,7 +48,7 @@ import 'goldens.dart';
const int _kChromeDevtoolsPort = 12345;
const int _kMaxScreenshotWidth = 1024;
const int _kMaxScreenshotHeight = 1024;
const double _kMaxDiffRateFailure = 0.211/100; // 0.211%
const double _kMaxDiffRateFailure = 0.28/100; // 0.28%
class BrowserPlatform extends PlatformPlugin {
/// Starts the server.
@@ -196,26 +195,93 @@ To automatically create this file call matchGoldenFile('$filename', write: true)
ImageDiff diff = ImageDiff(golden: decodeNamedImage(file.readAsBytesSync(), filename), other: screenshot);
if (diff.rate > 0) { // Images are different, so produce some debug info
final File failedFile = File(p.join(file.parent.path, '${p.basenameWithoutExtension(file.path)}.out.png'));
failedFile.writeAsBytesSync(encodePng(screenshot), flush: true);
final String testResultsPath = isCirrus
? p.join(
Platform.environment['CIRRUS_WORKING_DIR'],
'test_results',
)
: p.join(
env.environment.webUiDartToolDir.path,
'test_results',
);
Directory(testResultsPath).createSync(recursive: true);
final String basename = p.basenameWithoutExtension(file.path);
final File failedDiff = File(p.join(file.parent.path, '${p.basenameWithoutExtension(file.path)}.diff.png'));
failedDiff.writeAsBytesSync(encodePng(diff.diff), flush:true);
final File actualFile = File(p.join(testResultsPath, '$basename.actual.png'));
actualFile.writeAsBytesSync(encodePng(screenshot), flush: true);
final String printableDiffFilesInfo = getPrintableDiffFilesInfo(diff.rate, _kMaxDiffRateFailure, filename, failedFile.path, failedDiff.path);
final File diffFile = File(p.join(testResultsPath, '$basename.diff.png'));
diffFile.writeAsBytesSync(encodePng(diff.diff), flush:true);
if (diff.rate < _kMaxDiffRateFailure) { // Warn user
print('[WARN] Golden file ${file.path} is slightly different from the image generated by this test!\n${printableDiffFilesInfo}');
return 'OK'; // But test success!
final File expectedFile = File(p.join(testResultsPath, '$basename.expected.png'));
file.copySync(expectedFile.path);
final File reportFile = File(p.join(testResultsPath, '$basename.report.html'));
reportFile.writeAsStringSync('''
Golden file $filename did not match the image generated by the test.
<table>
<tr>
<th>Expected</th>
<th>Diff</th>
<th>Actual</th>
</tr>
<tr>
<td>
<img src="$basename.expected.png">
</td>
<td>
<img src="$basename.diff.png">
</td>
<td>
<img src="$basename.actual.png">
</td>
</tr>
</table>
''');
final StringBuffer message = StringBuffer();
message.writeln('Golden file $filename did not match the image generated by the test.');
message.writeln(getPrintableDiffFilesInfo(diff.rate, _kMaxDiffRateFailure));
message.writeln('You can view the test report in your browser by opening:');
// Cirrus cannot serve HTML pages generated by build jobs, so we
// archive all the files so that they can be downloaded and inspected
// locally.
if (isCirrus) {
final String taskId = Platform.environment['CIRRUS_TASK_ID'];
final String baseArtifactsUrl = 'https://api.cirrus-ci.com/v1/artifact/task/$taskId/web_engine_test/test_results';
final String cirrusReportUrl = '$baseArtifactsUrl/$basename.report.zip';
message.writeln(cirrusReportUrl);
await Process.run(
'zip',
<String>[
'$basename.report.zip',
'$basename.report.html',
'$basename.expected.png',
'$basename.diff.png',
'$basename.actual.png',
],
workingDirectory: testResultsPath,
);
} else {
final String localReportPath = '$testResultsPath/$basename.report.html';
message.writeln(localReportPath);
}
message.writeln('To update the golden file call matchGoldenFile(\'$filename\', write: true).');
message.writeln('Golden file: ${expectedFile.path}');
message.writeln('Actual file: ${actualFile.path}');
if (diff.rate < _kMaxDiffRateFailure) {
// Issue a warning but do not fail the test.
print('WARNING:');
print(message);
return 'OK';
} else {
// TODO(yjbanov): do not fail Cirrus builds. They currently fail because Chrome produces
// different pictures. We need to pin Chrome versions and use a fuzzy image
// comparator.
if (Platform.environment['CIRRUS_CI'] == 'true') {
return 'OK';
}
// Fail test
return 'Golden file ${file.path} is too different from the image generated by the test!\n${printableDiffFilesInfo}';
return '$message';
}
}
return 'OK';
@@ -885,8 +951,21 @@ class Chrome extends Browser {
assert(version != null);
var remoteDebuggerCompleter = Completer<Uri>.sync();
return Chrome._(() async {
final ChromeInstallation installation = await getOrInstallChrome(version, infoLog: _DevNull());
final ChromeInstallation installation = await getOrInstallChrome(
version,
infoLog: isCirrus ? stdout : _DevNull(),
);
// A good source of various Chrome CLI options:
// https://peter.sh/experiments/chromium-command-line-switches/
//
// Things to try:
// --font-render-hinting
// --enable-font-antialiasing
// --gpu-rasterization-msaa-sample-count
// --disable-gpu
// --disallow-non-exact-resource-reuse
// --disable-font-subpixel-positioning
final bool isChromeNoSandbox = Platform.environment['CHROME_NO_SANDBOX'] == 'true';
var dir = createTempDir();
var args = [
@@ -939,3 +1018,5 @@ class _DevNull implements StringSink {
void writeln([Object obj = ""]) {
}
}
bool get isCirrus => Platform.environment['CIRRUS_CI'] == 'true';