flutter_goldens.dart 11.3 KB
Newer Older
1 2 3
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5 6 7 8 9 10 11
import 'dart:async';
import 'dart:typed_data';

import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meta/meta.dart';
12
import 'package:platform/platform.dart';
13

14
import 'package:flutter_goldens_client/client.dart';
15 16
import 'package:flutter_goldens_client/skia_client.dart';

17
export 'package:flutter_goldens_client/client.dart';
18
export 'package:flutter_goldens_client/skia_client.dart';
Kate Lovett's avatar
Kate Lovett committed
19

20 21
/// Main method that can be used in a `flutter_test_config.dart` file to set
/// [goldenFileComparator] to an instance of [FlutterGoldenFileComparator] that
22 23
/// works for the current test. _Which_ FlutterGoldenFileComparator is
/// instantiated is based on the current testing environment.
24
Future<void> main(FutureOr<void> testMain()) async {
25 26 27 28 29 30 31 32
  const Platform platform = LocalPlatform();
  if (FlutterSkiaGoldFileComparator.isAvailableOnPlatform(platform)) {
    goldenFileComparator = await FlutterSkiaGoldFileComparator.fromDefaultComparator();
  } else if (FlutterGoldensRepositoryFileComparator.isAvailableOnPlatform(platform)) {
    goldenFileComparator = await FlutterGoldensRepositoryFileComparator.fromDefaultComparator();
  } else {
    goldenFileComparator = FlutterSkippingGoldenFileComparator.fromDefaultComparator();
  }
33 34 35
  await testMain();
}

36 37 38
/// Abstract base class golden file comparator specific to the `flutter/flutter`
/// repository.
abstract class FlutterGoldenFileComparator extends GoldenFileComparator {
39 40 41
  /// Creates a [FlutterGoldenFileComparator] that will resolve golden file
  /// URIs relative to the specified [basedir].
  ///
42 43
  /// The [fs] and [platform] parameters useful in tests, where the default file
  /// system and platform can be replaced by mock instances.
44 45 46
  @visibleForTesting
  FlutterGoldenFileComparator(
    this.basedir, {
47
    this.fs = const LocalFileSystem(),
48 49 50 51
    this.platform = const LocalPlatform(),
  }) : assert(basedir != null),
       assert(fs != null),
       assert(platform != null);
52

53 54
  /// The directory to which golden file URIs will be resolved in [compare] and
  /// [update].
55
  final Uri basedir;
56 57 58

  /// The file system used to perform file access.
  @visibleForTesting
59 60
  final FileSystem fs;

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
  /// A wrapper for the [dart:io.Platform] API.
  @visibleForTesting
  final Platform platform;

  @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);
  }

  /// Calculate the appropriate basedir for the current test context.
  @protected
  @visibleForTesting
  static Directory getBaseDirectory(GoldensClient goldens, LocalFileComparator defaultComparator) {
    final FileSystem fs = goldens.fs;
    final Directory testDirectory = fs.directory(defaultComparator.basedir);
    final String testDirectoryRelativePath = fs.path.relative(testDirectory.path, from: goldens.flutterRoot.path);
    return goldens.comparisonRoot.childDirectory(testDirectoryRelativePath);
  }

  /// Returns the golden [File] identified by the given [Uri].
  @protected
  File getGoldenFile(Uri uri) {
    assert(basedir.scheme == 'file');
    final File goldenFile = fs.directory(basedir).childFile(fs.file(uri).path);
    assert(goldenFile.uri.scheme == 'file');
    return goldenFile;
  }
}

/// A [FlutterGoldenFileComparator] for testing golden images against the
/// `flutter/goldens` repository.
///
/// Within the https://github.com/flutter/flutter repository, it's important
/// not to check-in binaries in order to keep the size of the repository to a
/// minimum. To satisfy this requirement, this comparator retrieves the golden
/// files from a sibling repository, `flutter/goldens`.
///
/// This comparator will locally clone the `flutter/goldens` repository into
/// the `$FLUTTER_ROOT/bin/cache/pkg/goldens` folder using the
/// [GoldensRepositoryClient], then perform the comparison against the files
/// therein.
///
/// See also:
///
///  * [GoldenFileComparator], the abstract class that
///    [FlutterGoldenFileComparator] implements.
///  * [FlutterSkiaGoldFileComparator], another [FlutterGoldenFileComparator]
///    that tests golden images through Skia Gold.
class FlutterGoldensRepositoryFileComparator extends FlutterGoldenFileComparator {
  /// Creates a [FlutterGoldensRepositoryFileComparator] that will test golden
  /// file images against the `flutter/goldens` repository.
  ///
  /// The [fs] and [platform] parameters useful in tests, where the default file
  /// system and platform can be replaced by mock instances.
  FlutterGoldensRepositoryFileComparator(
    Uri basedir, {
    FileSystem fs = const LocalFileSystem(),
    Platform platform = const LocalPlatform(),
  }) : super(
    basedir,
    fs: fs,
    platform: platform,
  );

  /// Creates a new [FlutterGoldensRespositoryFileComparator] that mirrors the
  /// relative path resolution of the default [goldenFileComparator].
129
  ///
130
  /// By the time the future completes, the clone of the `flutter/goldens`
131
  /// repository is guaranteed to be ready to use.
132 133
  ///
  /// The [goldens] and [defaultComparator] parameters are visible for testing
134
  /// purposes only.
135 136
  static Future<FlutterGoldensRepositoryFileComparator> fromDefaultComparator({
    GoldensRepositoryClient goldens,
137 138 139 140
    LocalFileComparator defaultComparator,
  }) async {
    defaultComparator ??= goldenFileComparator;

141
    // Prepare the goldens repo.
142
    goldens ??= GoldensRepositoryClient();
143 144
    await goldens.prepare();

145 146
    final Directory baseDirectory = FlutterGoldenFileComparator.getBaseDirectory(goldens, defaultComparator);
    return FlutterGoldensRepositoryFileComparator(baseDirectory.uri);
147 148 149 150
  }

  @override
  Future<bool> compare(Uint8List imageBytes, Uri golden) async {
151
    final File goldenFile = getGoldenFile(golden);
152 153
    if (!goldenFile.existsSync()) {
      throw TestFailure('Could not be compared against non-existent file: "$golden"');
154
    }
155
    final List<int> goldenBytes = await goldenFile.readAsBytes();
156
    final ComparisonResult result = GoldenFileComparator.compareLists(imageBytes, goldenBytes);
157
    return result.passed;
158 159
  }

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  /// Decides based on the current platform whether goldens tests should be
  /// performed against the flutter/goldens repository.
  static bool isAvailableOnPlatform(Platform platform) => platform.isLinux;
}

/// A [FlutterGoldenFileComparator] for testing golden images with Skia Gold.
///
/// For testing across all platforms, the [SkiaGoldClient] is used to upload
/// images for framework-related golden tests and process results. Currently
/// these tests are designed to be run post-submit on Cirrus CI, informed by the
/// environment.
///
/// See also:
///
///  * [GoldenFileComparator], the abstract class that
///    [FlutterGoldenFileComparator] implements.
///  * [FlutterGoldensRepositoryFileComparator], another
///    [FlutterGoldenFileComparator] that tests golden images using the
///    flutter/goldens repository.
class FlutterSkiaGoldFileComparator extends FlutterGoldenFileComparator {
  /// Creates a [FlutterSkiaGoldFileComparator] that will test golden file
  /// images against Skia Gold.
  ///
  /// The [fs] and [platform] parameters useful in tests, where the default file
  /// system and platform can be replaced by mock instances.
  FlutterSkiaGoldFileComparator(
    final Uri basedir,
    this.skiaClient, {
    FileSystem fs = const LocalFileSystem(),
    Platform platform = const LocalPlatform(),
  }) : super(
    basedir,
    fs: fs,
    platform: platform,
  );

  final SkiaGoldClient skiaClient;

  /// Creates a new [FlutterSkiaGoldFileComparator] that mirrors the relative
  /// path resolution of the default [goldenFileComparator].
  ///
  /// The [goldens] and [defaultComparator] parameters are visible for testing
  /// purposes only.
  static Future<FlutterSkiaGoldFileComparator> fromDefaultComparator({
    SkiaGoldClient goldens,
    LocalFileComparator defaultComparator,
  }) async {
    defaultComparator ??= goldenFileComparator;
    goldens ??= SkiaGoldClient();

    final Directory baseDirectory = FlutterGoldenFileComparator.getBaseDirectory(goldens, defaultComparator);
    if (!baseDirectory.existsSync())
      baseDirectory.createSync(recursive: true);
    await goldens.auth(baseDirectory);
    await goldens.imgtestInit();
    return FlutterSkiaGoldFileComparator(baseDirectory.uri, goldens);
  }

218
  @override
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
  Future<bool> compare(Uint8List imageBytes, Uri golden) async {
    golden = _addPrefix(golden);
    await update(golden, imageBytes);

    final File goldenFile = getGoldenFile(golden);
    if (!goldenFile.existsSync()) {
      throw TestFailure('Could not be compared against non-existent file: "$golden"');
    }
    return await skiaClient.imgtestAdd(golden.path, goldenFile);
  }

  @override
  Uri getTestUri(Uri key, int version) => key;

  /// Decides based on the current environment whether goldens tests should be
  /// performed against Skia Gold.
  static bool isAvailableOnPlatform(Platform platform) {
    final String cirrusCI = platform.environment['CIRRUS_CI'] ?? '';
    final String cirrusPR = platform.environment['CIRRUS_PR'] ?? '';
    final String cirrusBranch = platform.environment['CIRRUS_BRANCH'] ?? '';
    final String goldServiceAccount = platform.environment['GOLD_SERVICE_ACCOUNT'] ?? '';
    return cirrusCI.isNotEmpty
      && cirrusPR.isEmpty
      && cirrusBranch == 'master'
      && goldServiceAccount.isNotEmpty;
244 245
  }

246 247 248 249 250
  /// Prepends the golden Uri with the library name that encloses the current
  /// test.
  Uri _addPrefix(Uri golden) {
    final String prefix = basedir.pathSegments[basedir.pathSegments.length - 2];
    return Uri.parse(prefix + '.' + golden.toString());
251 252
  }
}
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

/// A [FlutterGoldenFileComparator] for skipping golden image tests when Skia
/// Gold is unavailable or the current platform that is executing tests is not
/// Linux.
///
/// See also:
///
///  * [FlutterGoldensRepositoryFileComparator], another
///    [FlutterGoldenFileComparator] that tests golden images using the
///    flutter/goldens repository.
///  * [FlutterSkiaGoldFileComparator], another [FlutterGoldenFileComparator]
///    that tests golden images through Skia Gold.
class FlutterSkippingGoldenFileComparator extends FlutterGoldenFileComparator {
  /// Creates a [FlutterSkippingGoldenFileComparator] that will skip tests that
  /// are not in the right environment for golden file testing.
  FlutterSkippingGoldenFileComparator(Uri basedir) : super(basedir);

  /// Creates a new [FlutterSkippingGoldenFileComparator] that mirrors the relative
  /// path resolution of the default [goldenFileComparator].
  static FlutterSkippingGoldenFileComparator fromDefaultComparator({
    LocalFileComparator defaultComparator,
  }) {
    defaultComparator ??= goldenFileComparator;
    return FlutterSkippingGoldenFileComparator(defaultComparator.basedir);
  }

  @override
  Future<bool> compare(Uint8List imageBytes, Uri golden) async {
    print('Skipping "$golden" test : Skia Gold is not available in this testing '
      'environment and flutter/goldens repository comparison is only available '
      'on Linux machines.'
    );
    return true;
  }

  @override
  Future<void> update(Uri golden, Uint8List imageBytes) => null;
}