_goldens_io.dart 12.6 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// 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';
7
import 'dart:math' as math;
8
import 'dart:ui';
9

10
import 'package:flutter/foundation.dart';
11
import 'package:path/path.dart' as path;
12
import 'package:test_api/expect.dart' show fail;
13 14

import 'goldens.dart';
15
import 'test_async_utils.dart';
16 17 18

/// The default [GoldenFileComparator] implementation for `flutter test`.
///
19 20
/// The term __golden file__ refers to a master image that is considered the
/// true rendering of a given widget, state, application, or other visual
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
/// representation you have chosen to capture. This comparator loads golden
/// files from the local file system, treating the golden key as a relative
/// path from the test file's directory.
///
/// This comparator performs a pixel-for-pixel comparison of the decoded PNGs,
/// returning true only if there's an exact match. In cases where the captured
/// test image does not match the golden file, this comparator will provide
/// output to illustrate the difference, described in further detail below.
///
/// When using `flutter test --update-goldens`, [LocalFileComparator]
/// updates the golden files on disk to match the rendering.
///
/// ## Local Output from Golden File Testing
///
/// The [LocalFileComparator] will output test feedback when a golden file test
/// fails. This output takes the form of differential images contained within a
/// `failures` directory that will be generated in the same location specified
/// by the golden key. The differential images include the master and test
/// images that were compared, as well as an isolated diff of detected pixels,
/// and a masked diff that overlays these detected pixels over the master image.
///
/// The following images are examples of a test failure output:
///
/// |  File Name                 |  Image Output |
/// |----------------------------|---------------|
/// |  testName_masterImage.png  | ![A golden master image](https://flutter.github.io/assets-for-api-docs/assets/flutter-test/goldens/widget_masterImage.png)  |
/// |  testName_testImage.png    | ![Test image](https://flutter.github.io/assets-for-api-docs/assets/flutter-test/goldens/widget_testImage.png)  |
/// |  testName_isolatedDiff.png | ![An isolated pixel difference.](https://flutter.github.io/assets-for-api-docs/assets/flutter-test/goldens/widget_isolatedDiff.png) |
/// |  testName_maskedDiff.png   | ![A masked pixel difference](https://flutter.github.io/assets-for-api-docs/assets/flutter-test/goldens/widget_maskedDiff.png) |
///
51 52
/// {@macro flutter.flutter_test.matchesGoldenFile.custom_fonts}
///
53 54 55 56 57 58
/// See also:
///
///   * [GoldenFileComparator], the abstract class that [LocalFileComparator]
///   implements.
///   * [matchesGoldenFile], the function from [flutter_test] that invokes the
///    comparator.
59
class LocalFileComparator extends GoldenFileComparator with LocalComparisonOutput {
60 61 62 63 64 65
  /// Creates a new [LocalFileComparator] for the specified [testFile].
  ///
  /// Golden file keys will be interpreted as file paths relative to the
  /// directory in which [testFile] resides.
  ///
  /// The [testFile] URL must represent a file.
66
  LocalFileComparator(Uri testFile, {path.Style? pathStyle})
67 68 69
    : basedir = _getBasedir(testFile, pathStyle),
      _path = _getPath(pathStyle);

70
  static path.Context _getPath(path.Style? style) {
71 72 73
    return path.Context(style: style ?? path.Style.platform);
  }

74
  static Uri _getBasedir(Uri testFile, path.Style? pathStyle) {
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    final path.Context context = _getPath(pathStyle);
    final String testFilePath = context.fromUri(testFile);
    final String testDirectoryPath = context.dirname(testFilePath);
    return context.toUri(testDirectoryPath + context.separator);
  }

  /// The directory in which the test was loaded.
  ///
  /// Golden file keys will be interpreted as file paths relative to this
  /// directory.
  final Uri basedir;

  /// Path context exists as an instance variable rather than just using the
  /// system path context in order to support testing, where we can spoof the
  /// platform to test behaviors with arbitrary path styles.
  final path.Context _path;

  @override
  Future<bool> compare(Uint8List imageBytes, Uri golden) async {
94
    final ComparisonResult result = await GoldenFileComparator.compareLists(
95
      imageBytes,
96
      await getGoldenBytes(golden),
97
    );
98 99

    if (!result.passed) {
100 101
      final String error = await generateFailureOutput(result, golden, basedir);
      throw FlutterError(error);
102 103 104 105 106 107 108 109 110 111 112
    }
    return result.passed;
  }

  @override
  Future<void> update(Uri golden, Uint8List imageBytes) async {
    final File goldenFile = _getGoldenFile(golden);
    await goldenFile.parent.create(recursive: true);
    await goldenFile.writeAsBytes(imageBytes, flush: true);
  }

113 114 115 116 117 118 119
  /// Returns the bytes of the given [golden] file.
  ///
  /// If the file cannot be found, an error will be thrown.
  @protected
  Future<List<int>> getGoldenBytes(Uri golden) async {
    final File goldenFile = _getGoldenFile(golden);
    if (!goldenFile.existsSync()) {
120
      fail(
121 122 123 124 125
        'Could not be compared against non-existent file: "$golden"'
      );
    }
    final List<int> goldenBytes = await goldenFile.readAsBytes();
    return goldenBytes;
126
  }
127 128

  File _getGoldenFile(Uri golden) => File(_path.join(_path.fromUri(basedir), _path.fromUri(golden.path)));
129 130
}

131
/// A mixin for use in golden file comparators that run locally and provide
132
/// output.
133
mixin LocalComparisonOutput {
134 135 136
  /// Writes out diffs from the [ComparisonResult] of a golden file test.
  ///
  /// Will throw an error if a null result is provided.
137
  Future<String> generateFailureOutput(
138 139 140 141
    ComparisonResult result,
    Uri golden,
    Uri basedir, {
    String key = '',
142
  }) async => TestAsyncUtils.guard<String>(() async {
143 144
    String additionalFeedback = '';
    if (result.diffs != null) {
145
      additionalFeedback = '\nFailure feedback can be found at ${path.join(basedir.path, 'failures')}';
146
      final Map<String, Image> diffs = result.diffs!;
147
      for (final MapEntry<String, Image> entry in diffs.entries) {
148
        final File output = getFailureFile(
149
          key.isEmpty ? entry.key : '${entry.key}_$key',
150 151 152 153
          golden,
          basedir,
        );
        output.parent.createSync(recursive: true);
154
        final ByteData? pngBytes = await entry.value.toByteData(format: ImageByteFormat.png);
155
        output.writeAsBytesSync(pngBytes!.buffer.asUint8List());
156
      }
157
    }
158 159
    return 'Golden "$golden": ${result.error}$additionalFeedback';
  });
160

161 162
  /// Returns the appropriate file for a given diff from a [ComparisonResult].
  File getFailureFile(String failure, Uri golden, Uri basedir) {
163
    final String fileName = golden.pathSegments.last;
164
    final String testName = '${fileName.split(path.extension(fileName))[0]}_$failure.png';
165 166 167
    return File(path.join(
      path.fromUri(basedir),
      path.fromUri(Uri.parse('failures/$testName')),
168
    ));
169 170
  }
}
171 172 173

/// Returns a [ComparisonResult] to describe the pixel differential of the
/// [test] and [master] image bytes provided.
174
Future<ComparisonResult> compareLists(List<int>? test, List<int>? master) async {
175
  if (identical(test, master)) {
176 177 178 179
    return ComparisonResult(
      passed: true,
      diffPercent: 0.0,
    );
180
  }
181 182 183 184

  if (test == null || master == null || test.isEmpty || master.isEmpty) {
    return ComparisonResult(
      passed: false,
185
      diffPercent: 1.0,
186 187 188 189
      error: 'Pixel test failed, null image provided.',
    );
  }

190 191 192
  final Codec testImageCodec =
      await instantiateImageCodec(Uint8List.fromList(test));
  final Image testImage = (await testImageCodec.getNextFrame()).image;
193
  final ByteData? testImageRgba = await testImage.toByteData();
194 195 196 197

  final Codec masterImageCodec =
      await instantiateImageCodec(Uint8List.fromList(master));
  final Image masterImage = (await masterImageCodec.getNextFrame()).image;
198
  final ByteData? masterImageRgba = await masterImage.toByteData();
199 200 201 202 203 204 205

  final int width = testImage.width;
  final int height = testImage.height;

  if (width != masterImage.width || height != masterImage.height) {
    return ComparisonResult(
      passed: false,
206
      diffPercent: 1.0,
207 208 209 210 211 212 213 214
      error: 'Pixel test failed, image sizes do not match.\n'
        'Master Image: ${masterImage.width} X ${masterImage.height}\n'
        'Test Image: ${testImage.width} X ${testImage.height}',
    );
  }

  int pixelDiffCount = 0;
  final int totalPixels = width * height;
215 216
  final ByteData invertedMasterRgba = _invert(masterImageRgba!);
  final ByteData invertedTestRgba = _invert(testImageRgba!);
217

218
  final Uint8List testImageBytes = (await testImage.toByteData())!.buffer.asUint8List();
219 220
  final ByteData maskedDiffRgba = ByteData(testImageBytes.length);
  maskedDiffRgba.buffer.asUint8List().setRange(0, testImageBytes.length, testImageBytes);
221
  final ByteData isolatedDiffRgba = ByteData(width * height * 4);
222 223 224

  for (int x = 0; x < width; x++) {
    for (int y =0; y < height; y++) {
225 226 227
      final int byteOffset = (width * y + x) * 4;
      final int testPixel = testImageRgba.getUint32(byteOffset);
      final int masterPixel = masterImageRgba.getUint32(byteOffset);
228

229 230 231 232
      final int diffPixel = (_readRed(testPixel) - _readRed(masterPixel)).abs()
        + (_readGreen(testPixel) - _readGreen(masterPixel)).abs()
        + (_readBlue(testPixel) - _readBlue(masterPixel)).abs()
        + (_readAlpha(testPixel) - _readAlpha(masterPixel)).abs();
233 234

      if (diffPixel != 0 ) {
235 236 237 238 239 240 241 242 243 244 245
        final int invertedMasterPixel = invertedMasterRgba.getUint32(byteOffset);
        final int invertedTestPixel = invertedTestRgba.getUint32(byteOffset);
        // We grab the max of the 0xAABBGGRR encoded bytes, and then convert
        // back to 0xRRGGBBAA for the actual pixel value, since this is how it
        // was historically done.
        final int maskPixel = _toRGBA(math.max(
          _toABGR(invertedMasterPixel),
          _toABGR(invertedTestPixel),
        ));
        maskedDiffRgba.setUint32(byteOffset, maskPixel);
        isolatedDiffRgba.setUint32(byteOffset, maskPixel);
246 247 248 249 250 251
        pixelDiffCount++;
      }
    }
  }

  if (pixelDiffCount > 0) {
252
    final double diffPercent = pixelDiffCount / totalPixels;
253 254
    return ComparisonResult(
      passed: false,
255
      diffPercent: diffPercent,
256
      error: 'Pixel test failed, '
257
        '${(diffPercent * 100).toStringAsFixed(2)}% '
258
        'diff detected.',
259 260 261 262 263 264
      diffs:  <String, Image>{
        'masterImage' : masterImage,
        'testImage' : testImage,
        'maskedDiff' : await _createImage(maskedDiffRgba, width, height),
        'isolatedDiff' : await _createImage(isolatedDiffRgba, width, height),
      },
265 266
    );
  }
267
  return ComparisonResult(passed: true, diffPercent: 0.0);
268 269
}

270 271 272 273 274 275 276 277 278 279 280 281 282
/// Inverts [imageBytes], returning a new [ByteData] object.
ByteData _invert(ByteData imageBytes) {
  final ByteData bytes = ByteData(imageBytes.lengthInBytes);
  // Invert the RGB data (but not A).
  for (int i = 0; i < imageBytes.lengthInBytes; i += 4) {
    bytes.setUint8(i, 255 - imageBytes.getUint8(i));
    bytes.setUint8(i + 1, 255 - imageBytes.getUint8(i + 1));
    bytes.setUint8(i + 2, 255 - imageBytes.getUint8(i + 2));
    bytes.setUint8(i + 3, imageBytes.getUint8(i + 3));
  }
  return bytes;
}

283 284 285
/// An unsupported [WebGoldenComparator] that exists for API compatibility.
class DefaultWebGoldenComparator extends WebGoldenComparator {
  @override
286
  Future<bool> compare(double width, double height, Uri golden) {
287 288 289 290
    throw UnsupportedError('DefaultWebGoldenComparator is only supported on the web.');
  }

  @override
291
  Future<void> update(double width, double height, Uri golden) {
292 293 294
    throw UnsupportedError('DefaultWebGoldenComparator is only supported on the web.');
  }
}
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

/// Reads the red value out of a 32 bit rgba pixel.
int _readRed(int pixel) => (pixel >> 24) & 0xff;

/// Reads the green value out of a 32 bit rgba pixel.
int _readGreen(int pixel) => (pixel >> 16) & 0xff;

/// Reads the blue value out of a 32 bit rgba pixel.
int _readBlue(int pixel) => (pixel >> 8) & 0xff;

/// Reads the alpha value out of a 32 bit rgba pixel.
int _readAlpha(int pixel) => pixel & 0xff;

/// Convenience wrapper around [decodeImageFromPixels].
Future<Image> _createImage(ByteData bytes, int width, int height) {
  final Completer<Image> completer = Completer<Image>();
  decodeImageFromPixels(
    bytes.buffer.asUint8List(),
    width,
    height,
    PixelFormat.rgba8888,
    completer.complete,
  );
  return completer.future;
}

// Converts a 32 bit rgba pixel to a 32 bit abgr pixel
int _toABGR(int rgba) =>
    (_readAlpha(rgba) << 24) |
    (_readBlue(rgba) << 16) |
    (_readGreen(rgba) << 8) |
    _readRed(rgba);

// Converts a 32 bit abgr pixel to a 32 bit rgba pixel
int _toRGBA(int abgr) =>
  // This is just a mirror of the other conversion.
  _toABGR(abgr);