flutter_goldens_test.dart 33.1 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
// See also dev/automated_tests/flutter_test/flutter_gold_test.dart

7
import 'dart:convert';
8
import 'dart:io' hide Directory;
9 10 11

import 'package:file/file.dart';
import 'package:file/memory.dart';
12
import 'package:flutter/foundation.dart';
13 14 15 16 17
import 'package:flutter_goldens/flutter_goldens.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:platform/platform.dart';
import 'package:process/process.dart';

18 19
import 'json_templates.dart';

20
const String _kFlutterRoot = '/flutter';
21 22

// 1x1 transparent pixel
23 24
const List<int> _kTestPngBytes = <int>[
  137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0,
25 26
  1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 31, 21, 196, 137, 0, 0, 0, 11, 73, 68, 65, 84,
  120, 1, 99, 97, 0, 2, 0, 0, 25, 0, 5, 144, 240, 54, 245, 0, 0, 0, 0, 73, 69,
27 28
  78, 68, 174, 66, 96, 130,
];
29

30
void main() {
31 32 33 34
  late MemoryFileSystem fs;
  late FakePlatform platform;
  late FakeProcessManager process;
  late FakeHttpClient fakeHttpClient;
35

36
  setUp(() {
37
    fs = MemoryFileSystem();
38 39 40 41
    platform = FakePlatform(
      environment: <String, String>{'FLUTTER_ROOT': _kFlutterRoot},
      operatingSystem: 'macos'
    );
42 43
    process = FakeProcessManager();
    fakeHttpClient = FakeHttpClient();
44
    fs.directory(_kFlutterRoot).createSync(recursive: true);
45 46
  });

47
  group('SkiaGoldClient', () {
48 49
    late SkiaGoldClient skiaClient;
    late Directory workDirectory;
50 51

    setUp(() {
52
      workDirectory = fs.directory('/workDirectory')
53 54 55
        ..createSync(recursive: true);
      skiaClient = SkiaGoldClient(
        workDirectory,
56
        fs: fs,
57
        process: process,
58
        platform: platform,
59
        httpClient: fakeHttpClient,
60 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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
    test('web HTML test', () async {
      platform = FakePlatform(
        environment: <String, String>{
          'GOLDCTL': 'goldctl',
          'FLUTTER_ROOT': _kFlutterRoot,
          'FLUTTER_TEST_BROWSER': 'Chrome',
          'FLUTTER_WEB_RENDERER': 'html',
        },
        operatingSystem: 'macos'
      );
      skiaClient = SkiaGoldClient(
        workDirectory,
        fs: fs,
        process: process,
        platform: platform,
        httpClient: fakeHttpClient,
      );

      final File goldenFile = fs.file('/workDirectory/temp/golden_file_test.png')
        ..createSync(recursive: true);

      const RunInvocation goldctlInvocation = RunInvocation(
        <String>[
          'goldctl',
          'imgtest', 'add',
          '--work-dir', '/workDirectory/temp',
          '--test-name', 'golden_file_test',
          '--png-file', '/workDirectory/temp/golden_file_test.png',
          '--passfail',
          '--add-test-optional-key', 'image_matching_algorithm:fuzzy',
          '--add-test-optional-key', 'fuzzy_max_different_pixels:20',
          '--add-test-optional-key', 'fuzzy_pixel_delta_threshold:4',
        ],
        null,
      );
      process.processResults[goldctlInvocation] = ProcessResult(123, 0, '', '');

      expect(
        await skiaClient.imgtestAdd('golden_file_test.png', goldenFile),
        isTrue,
      );
    });

    test('web CanvasKit test', () async {
      platform = FakePlatform(
        environment: <String, String>{
          'GOLDCTL': 'goldctl',
          'FLUTTER_ROOT': _kFlutterRoot,
          'FLUTTER_TEST_BROWSER': 'Chrome',
          'FLUTTER_WEB_RENDERER': 'canvaskit',
        },
        operatingSystem: 'macos'
      );
      skiaClient = SkiaGoldClient(
        workDirectory,
        fs: fs,
        process: process,
        platform: platform,
        httpClient: fakeHttpClient,
      );

      final File goldenFile = fs.file('/workDirectory/temp/golden_file_test.png')
        ..createSync(recursive: true);

      const RunInvocation goldctlInvocation = RunInvocation(
        <String>[
          'goldctl',
          'imgtest', 'add',
          '--work-dir', '/workDirectory/temp',
          '--test-name', 'golden_file_test',
          '--png-file', '/workDirectory/temp/golden_file_test.png',
          '--passfail',
        ],
        null,
      );
      process.processResults[goldctlInvocation] = ProcessResult(123, 0, '', '');

      expect(
        await skiaClient.imgtestAdd('golden_file_test.png', goldenFile),
        isTrue,
      );
    });

146
    test('auth performs minimal work if already authorized', () async {
147
      final File authFile = fs.file('/workDirectory/temp/auth_opt.json')
148
        ..createSync(recursive: true);
149
      authFile.writeAsStringSync(authTemplate());
150
      process.fallbackProcessResult = ProcessResult(123, 0, '', '');
151 152
      await skiaClient.auth();

153
      expect(process.workingDirectories, isEmpty);
154 155
    });

156 157 158 159 160 161 162 163 164 165
    test('gsutil is checked when authorization file is present', () async {
      final File authFile = fs.file('/workDirectory/temp/auth_opt.json')
        ..createSync(recursive: true);
      authFile.writeAsStringSync(authTemplate(gsutil: true));
      expect(
        await skiaClient.clientIsAuthorized(),
        isFalse,
      );
    });

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    test('throws for error state from auth', () async {
      platform = FakePlatform(
        environment: <String, String>{
          'FLUTTER_ROOT': _kFlutterRoot,
          'GOLD_SERVICE_ACCOUNT' : 'Service Account',
          'GOLDCTL' : 'goldctl',
        },
        operatingSystem: 'macos'
      );

      skiaClient = SkiaGoldClient(
        workDirectory,
        fs: fs,
        process: process,
        platform: platform,
181
        httpClient: fakeHttpClient,
182 183
      );

184
      process.fallbackProcessResult = ProcessResult(123, 1, 'Fallback failure', 'Fallback failure');
185 186

      expect(
187
        skiaClient.auth(),
188 189 190 191
        throwsException,
      );
    });

192
    test('throws for error state from init', () {
193 194 195 196 197 198 199 200 201 202 203 204 205
      platform = FakePlatform(
        environment: <String, String>{
          'FLUTTER_ROOT': _kFlutterRoot,
          'GOLDCTL' : 'goldctl',
        },
        operatingSystem: 'macos'
      );

      skiaClient = SkiaGoldClient(
        workDirectory,
        fs: fs,
        process: process,
        platform: platform,
206
        httpClient: fakeHttpClient,
207 208
      );

209
      const RunInvocation gitInvocation = RunInvocation(
210
        <String>['git', 'rev-parse', 'HEAD'],
211 212 213
        '/flutter',
      );
      const RunInvocation goldctlInvocation = RunInvocation(
214 215 216 217 218 219 220 221 222 223
        <String>[
          'goldctl',
          'imgtest', 'init',
          '--instance', 'flutter',
          '--work-dir', '/workDirectory/temp',
          '--commit', '12345678',
          '--keys-file', '/workDirectory/keys.json',
          '--failure-file', '/workDirectory/failures.json',
          '--passfail',
        ],
224 225 226
        null,
      );
      process.processResults[gitInvocation] = ProcessResult(12345678, 0, '12345678', '');
227 228
      process.processResults[goldctlInvocation] = ProcessResult(123, 1, 'Expected failure', 'Expected failure');
      process.fallbackProcessResult = ProcessResult(123, 1, 'Fallback failure', 'Fallback failure');
229 230

      expect(
231
        skiaClient.imgtestInit(),
232 233
        throwsException,
      );
234 235
    });

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
    test('Only calls init once', () async {
      platform = FakePlatform(
        environment: <String, String>{
          'FLUTTER_ROOT': _kFlutterRoot,
          'GOLDCTL' : 'goldctl',
        },
        operatingSystem: 'macos'
      );

      skiaClient = SkiaGoldClient(
        workDirectory,
        fs: fs,
        process: process,
        platform: platform,
        httpClient: fakeHttpClient,
      );

      const RunInvocation gitInvocation = RunInvocation(
        <String>['git', 'rev-parse', 'HEAD'],
        '/flutter',
      );
      const RunInvocation goldctlInvocation = RunInvocation(
        <String>[
          'goldctl',
          'imgtest', 'init',
          '--instance', 'flutter',
          '--work-dir', '/workDirectory/temp',
          '--commit', '1234',
          '--keys-file', '/workDirectory/keys.json',
          '--failure-file', '/workDirectory/failures.json',
266
          '--passfail',
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 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 332 333 334 335 336 337 338 339 340 341
        ],
        null,
      );
      process.processResults[gitInvocation] = ProcessResult(1234, 0, '1234', '');
      process.processResults[goldctlInvocation] = ProcessResult(5678, 0, '5678', '');
      process.fallbackProcessResult = ProcessResult(123, 1, 'Fallback failure', 'Fallback failure');

      // First call
      await skiaClient.imgtestInit();

      // Remove fake process result.
      // If the init call is executed again, the fallback process will throw.
      process.processResults.remove(goldctlInvocation);

      // Second call
      await skiaClient.imgtestInit();
    });

    test('Only calls tryjob init once', () async {
      platform = FakePlatform(
        environment: <String, String>{
          'FLUTTER_ROOT': _kFlutterRoot,
          'GOLDCTL' : 'goldctl',
          'SWARMING_TASK_ID' : '4ae997b50dfd4d11',
          'LOGDOG_STREAM_PREFIX' : 'buildbucket/cr-buildbucket.appspot.com/8885996262141582672',
          'GOLD_TRYJOB' : 'refs/pull/49815/head',
        },
        operatingSystem: 'macos'
      );

      skiaClient = SkiaGoldClient(
        workDirectory,
        fs: fs,
        process: process,
        platform: platform,
        httpClient: fakeHttpClient,
      );

      const RunInvocation gitInvocation = RunInvocation(
        <String>['git', 'rev-parse', 'HEAD'],
        '/flutter',
      );
      const RunInvocation goldctlInvocation = RunInvocation(
        <String>[
          'goldctl',
          'imgtest', 'init',
          '--instance', 'flutter',
          '--work-dir', '/workDirectory/temp',
          '--commit', '1234',
          '--keys-file', '/workDirectory/keys.json',
          '--failure-file', '/workDirectory/failures.json',
          '--passfail',
          '--crs', 'github',
          '--patchset_id', '1234',
          '--changelist', '49815',
          '--cis', 'buildbucket',
          '--jobid', '8885996262141582672',
        ],
        null,
      );
      process.processResults[gitInvocation] = ProcessResult(1234, 0, '1234', '');
      process.processResults[goldctlInvocation] = ProcessResult(5678, 0, '5678', '');
      process.fallbackProcessResult = ProcessResult(123, 1, 'Fallback failure', 'Fallback failure');

      // First call
      await skiaClient.tryjobInit();

      // Remove fake process result.
      // If the init call is executed again, the fallback process will throw.
      process.processResults.remove(goldctlInvocation);

      // Second call
      await skiaClient.tryjobInit();
    });

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    test('throws for error state from imgtestAdd', () {
      final File goldenFile = fs.file('/workDirectory/temp/golden_file_test.png')
        ..createSync(recursive: true);
      platform = FakePlatform(
          environment: <String, String>{
            'FLUTTER_ROOT': _kFlutterRoot,
            'GOLDCTL' : 'goldctl',
          },
          operatingSystem: 'macos'
      );

      skiaClient = SkiaGoldClient(
        workDirectory,
        fs: fs,
        process: process,
        platform: platform,
        httpClient: fakeHttpClient,
      );

      const RunInvocation goldctlInvocation = RunInvocation(
        <String>[
          'goldctl',
          'imgtest', 'add',
          '--work-dir', '/workDirectory/temp',
          '--test-name', 'golden_file_test',
          '--png-file', '/workDirectory/temp/golden_file_test.png',
          '--passfail',
        ],
        null,
      );
      process.processResults[goldctlInvocation] = ProcessResult(123, 1, 'Expected failure', 'Expected failure');
      process.fallbackProcessResult = ProcessResult(123, 1, 'Fallback failure', 'Fallback failure');

      expect(
        skiaClient.imgtestAdd('golden_file_test', goldenFile),
        throwsException,
      );
    });
380

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    test('correctly inits tryjob for luci', () async {
      platform = FakePlatform(
        environment: <String, String>{
          'FLUTTER_ROOT': _kFlutterRoot,
          'GOLDCTL' : 'goldctl',
          'SWARMING_TASK_ID' : '4ae997b50dfd4d11',
          'LOGDOG_STREAM_PREFIX' : 'buildbucket/cr-buildbucket.appspot.com/8885996262141582672',
          'GOLD_TRYJOB' : 'refs/pull/49815/head',
        },
        operatingSystem: 'macos'
      );

      skiaClient = SkiaGoldClient(
        workDirectory,
        fs: fs,
        process: process,
        platform: platform,
398
        httpClient: fakeHttpClient,
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
      );

      final List<String> ciArguments = skiaClient.getCIArguments();

      expect(
        ciArguments,
        equals(
          <String>[
            '--changelist', '49815',
            '--cis', 'buildbucket',
            '--jobid', '8885996262141582672',
          ],
        ),
      );
    });

415
    test('Creates traceID correctly', () async {
416 417 418 419 420 421 422 423 424 425 426
      String traceID;
      platform = FakePlatform(
        environment: <String, String>{
          'FLUTTER_ROOT': _kFlutterRoot,
          'GOLDCTL' : 'goldctl',
          'SWARMING_TASK_ID' : '4ae997b50dfd4d11',
          'LOGDOG_STREAM_PREFIX' : 'buildbucket/cr-buildbucket.appspot.com/8885996262141582672',
          'GOLD_TRYJOB' : 'refs/pull/49815/head',
        },
        operatingSystem: 'linux'
      );
427

428 429 430 431 432
      skiaClient = SkiaGoldClient(
        workDirectory,
        fs: fs,
        process: process,
        platform: platform,
433
        httpClient: fakeHttpClient,
434
      );
435

436
      traceID = skiaClient.getTraceID('flutter.golden.1');
437 438
      expect(
        traceID,
439
        equals('ae18c7a6aa48e0685525dfe8fdf79003'),
440
      );
441

442 443 444 445 446 447 448 449 450 451 452 453
      // Browser
      platform = FakePlatform(
        environment: <String, String>{
          'FLUTTER_ROOT': _kFlutterRoot,
          'GOLDCTL' : 'goldctl',
          'SWARMING_TASK_ID' : '4ae997b50dfd4d11',
          'LOGDOG_STREAM_PREFIX' : 'buildbucket/cr-buildbucket.appspot.com/8885996262141582672',
          'GOLD_TRYJOB' : 'refs/pull/49815/head',
          'FLUTTER_TEST_BROWSER' : 'chrome',
        },
        operatingSystem: 'linux'
      );
454

455 456 457 458 459
      skiaClient = SkiaGoldClient(
        workDirectory,
        fs: fs,
        process: process,
        platform: platform,
460
        httpClient: fakeHttpClient,
461
      );
462 463

      traceID = skiaClient.getTraceID('flutter.golden.1');
464 465
      expect(
        traceID,
466
        equals('e9d5c296c48e7126808520e9cc191243'),
467
      );
468

469 470 471 472 473 474 475 476 477 478 479 480 481
      // Locally - should defer to luci traceID
      platform = FakePlatform(
        environment: <String, String>{
          'FLUTTER_ROOT': _kFlutterRoot,
        },
        operatingSystem: 'macos'
      );

      skiaClient = SkiaGoldClient(
        workDirectory,
        fs: fs,
        process: process,
        platform: platform,
482
        httpClient: fakeHttpClient,
483
      );
484 485

      traceID = skiaClient.getTraceID('flutter.golden.1');
486 487
      expect(
        traceID,
488
        equals('9968695b9ae78cdb77cbb2be621ca2d6'),
489 490 491 492
      );
    });

    group('Request Handling', () {
493
      const String expectation = '55109a4bed52acc780530f7a9aeff6c0';
494 495 496 497 498

      test('image bytes are processed properly', () async {
        final Uri imageUrl = Uri.parse(
          'https://flutter-gold.skia.org/img/images/$expectation.png'
        );
499 500
        final FakeHttpClientRequest fakeImageRequest = FakeHttpClientRequest();
        final FakeHttpImageResponse fakeImageResponse = FakeHttpImageResponse(
501 502
          imageResponseTemplate()
        );
503 504 505

        fakeHttpClient.request = fakeImageRequest;
        fakeImageRequest.response = fakeImageResponse;
506 507 508

        final List<int> masterBytes = await skiaClient.getImageBytes(expectation);

509
        expect(fakeHttpClient.lastUri, imageUrl);
510 511
        expect(masterBytes, equals(_kTestPngBytes));
      });
512 513
    });
  });
514

515
  group('FlutterGoldenFileComparator', () {
516
    late FlutterGoldenFileComparator comparator;
517 518

    setUp(() {
519 520
      final Directory basedir = fs.directory('flutter/test/library/')
        ..createSync(recursive: true);
521
      comparator = FlutterPostSubmitFileComparator(
522
        basedir.uri,
523
        FakeSkiaGoldClient(),
524 525
        fs: fs,
        platform: platform,
526 527 528
      );
    });

529
    test('calculates the basedir correctly from defaultComparator for local testing', () async {
530
      final FakeLocalFileComparator defaultComparator = FakeLocalFileComparator();
531 532
      final Directory flutterRoot = fs.directory(platform.environment['FLUTTER_ROOT'])
        ..createSync(recursive: true);
533
      defaultComparator.basedir = flutterRoot.childDirectory('baz').uri;
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548

      final Directory basedir = FlutterGoldenFileComparator.getBaseDirectory(
        defaultComparator,
        platform,
      );
      expect(
        basedir.uri,
        fs.directory('/flutter/bin/cache/pkg/skia_goldens/baz').uri,
      );
    });

    test('ignores version number', () {
      final Uri key = comparator.getTestUri(Uri.parse('foo.png'), 1);
      expect(key, Uri.parse('foo.png'));
    });
549

550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    test('adds namePrefix', () async {
      const String libraryName = 'sidedishes';
      const String namePrefix = 'tomatosalad';
      const String fileName = 'lettuce.png';
      final FakeSkiaGoldClient fakeSkiaClient = FakeSkiaGoldClient();
      final Directory basedir = fs.directory('flutter/test/$libraryName/')
        ..createSync(recursive: true);
      final FlutterGoldenFileComparator comparator = FlutterPostSubmitFileComparator(
        basedir.uri,
        fakeSkiaClient,
        fs: fs,
        platform: platform,
        namePrefix: namePrefix,
      );
      await comparator.compare(
        Uint8List.fromList(_kTestPngBytes),
        Uri.parse(fileName),
      );
      expect(fakeSkiaClient.testNames.single, '$namePrefix.$libraryName.$fileName');
    });

571
    group('Post-Submit', () {
572
      late FakeSkiaGoldClient fakeSkiaClient;
573 574

      setUp(() {
575
        fakeSkiaClient = FakeSkiaGoldClient();
576
        final Directory basedir = fs.directory('flutter/test/library/')
577
          ..createSync(recursive: true);
578
        comparator = FlutterPostSubmitFileComparator(
579
          basedir.uri,
580
          fakeSkiaClient,
581 582 583
          fs: fs,
          platform: platform,
        );
584
      });
585

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
      test('asserts .png format', () async {
        await expectLater(
          () async {
            return comparator.compare(
              Uint8List.fromList(_kTestPngBytes),
              Uri.parse('flutter.golden_test.1'),
            );
          },
          throwsA(
            isA<AssertionError>().having((AssertionError error) => error.toString(),
              'description',
              contains(
                'Golden files in the Flutter framework must end with the file '
                'extension .png.'
              ),
            ),
          ),
        );
      });

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
      test('calls init during compare', () {
        expect(fakeSkiaClient.initCalls, 0);
        comparator.compare(
          Uint8List.fromList(_kTestPngBytes),
          Uri.parse('flutter.golden_test.1.png'),
        );
        expect(fakeSkiaClient.initCalls, 1);
      });

      test('does not call init in during construction', () {
        expect(fakeSkiaClient.initCalls, 0);
        FlutterPostSubmitFileComparator.fromDefaultComparator(
          platform,
          goldens: fakeSkiaClient,
        );
        expect(fakeSkiaClient.initCalls, 0);
      });

624
      group('correctly determines testing environment', () {
625
        test('returns true for configured Luci', () {
626 627 628 629 630 631
          platform = FakePlatform(
            environment: <String, String>{
              'FLUTTER_ROOT': _kFlutterRoot,
              'SWARMING_TASK_ID' : '12345678990',
              'GOLDCTL' : 'goldctl',
            },
632
            operatingSystem: 'macos',
633 634 635 636 637 638 639
          );
          expect(
            FlutterPostSubmitFileComparator.isAvailableForEnvironment(platform),
            isTrue,
          );
        });

640
        test('returns false - GOLDCTL not present', () {
641 642 643
          platform = FakePlatform(
            environment: <String, String>{
              'FLUTTER_ROOT': _kFlutterRoot,
644
              'SWARMING_TASK_ID' : '12345678990',
645
            },
646
            operatingSystem: 'macos',
647 648
          );
          expect(
649
            FlutterPostSubmitFileComparator.isAvailableForEnvironment(platform),
650 651 652 653
            isFalse,
          );
        });

654
        test('returns false - GOLD_TRYJOB active', () {
655 656 657
          platform = FakePlatform(
            environment: <String, String>{
              'FLUTTER_ROOT': _kFlutterRoot,
658 659
              'SWARMING_TASK_ID' : '12345678990',
              'GOLDCTL' : 'goldctl',
660
              'GOLD_TRYJOB' : 'git/ref/12345/head',
661
            },
662
            operatingSystem: 'macos',
663 664
          );
          expect(
665
            FlutterPostSubmitFileComparator.isAvailableForEnvironment(platform),
666 667 668 669
            isFalse,
          );
        });

670
        test('returns false - on Cirrus', () {
671 672 673 674 675
          platform = FakePlatform(
            environment: <String, String>{
              'FLUTTER_ROOT': _kFlutterRoot,
              'CIRRUS_CI': 'true',
              'CIRRUS_PR': '',
676
              'CIRRUS_BRANCH': 'master',
677
              'GOLD_SERVICE_ACCOUNT': 'service account...',
678
            },
679
            operatingSystem: 'macos',
680 681
          );
          expect(
682
            FlutterPostSubmitFileComparator.isAvailableForEnvironment(platform),
683 684 685
            isFalse,
          );
        });
686
      });
687
    });
688

689
    group('Pre-Submit', () {
690 691 692 693 694 695 696 697 698 699 700 701 702 703
      late FakeSkiaGoldClient fakeSkiaClient;

      setUp(() {
        fakeSkiaClient = FakeSkiaGoldClient();
        final Directory basedir = fs.directory('flutter/test/library/')
          ..createSync(recursive: true);
        comparator = FlutterPreSubmitFileComparator(
          basedir.uri,
          fakeSkiaClient,
          fs: fs,
          platform: platform,
        );
      });

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
      test('asserts .png format', () async {
        await expectLater(
          () async {
            return comparator.compare(
              Uint8List.fromList(_kTestPngBytes),
              Uri.parse('flutter.golden_test.1'),
            );
          },
          throwsA(
            isA<AssertionError>().having((AssertionError error) => error.toString(),
              'description',
              contains(
                'Golden files in the Flutter framework must end with the file '
                'extension .png.'
              ),
            ),
          ),
        );
      });

724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
      test('calls init during compare', () {
        expect(fakeSkiaClient.tryInitCalls, 0);
        comparator.compare(
          Uint8List.fromList(_kTestPngBytes),
          Uri.parse('flutter.golden_test.1.png'),
        );
        expect(fakeSkiaClient.tryInitCalls, 1);
      });

      test('does not call init in during construction', () {
        expect(fakeSkiaClient.tryInitCalls, 0);
        FlutterPostSubmitFileComparator.fromDefaultComparator(
          platform,
          goldens: fakeSkiaClient,
        );
        expect(fakeSkiaClient.tryInitCalls, 0);
      });

742
      group('correctly determines testing environment', () {
743
        test('returns true for Luci', () {
744 745 746
          platform = FakePlatform(
            environment: <String, String>{
              'FLUTTER_ROOT': _kFlutterRoot,
747 748
              'SWARMING_TASK_ID' : '12345678990',
              'GOLDCTL' : 'goldctl',
749
              'GOLD_TRYJOB' : 'git/ref/12345/head',
750
            },
751
            operatingSystem: 'macos',
752 753 754 755 756 757
          );
          expect(
            FlutterPreSubmitFileComparator.isAvailableForEnvironment(platform),
            isTrue,
          );
        });
758

759
        test('returns false - not on Luci', () {
760 761 762 763
          platform = FakePlatform(
            environment: <String, String>{
              'FLUTTER_ROOT': _kFlutterRoot,
            },
764
            operatingSystem: 'macos',
765 766 767
          );
          expect(
            FlutterPreSubmitFileComparator.isAvailableForEnvironment(platform),
768
            isFalse,
769 770 771
          );
        });

772
        test('returns false - GOLDCTL missing', () {
773 774 775
          platform = FakePlatform(
            environment: <String, String>{
              'FLUTTER_ROOT': _kFlutterRoot,
776
              'SWARMING_TASK_ID' : '12345678990',
777
              'GOLD_TRYJOB' : 'git/ref/12345/head',
778
            },
779
            operatingSystem: 'macos',
780 781 782 783 784 785 786
          );
          expect(
            FlutterPreSubmitFileComparator.isAvailableForEnvironment(platform),
            isFalse,
          );
        });

787
        test('returns false - GOLD_TRYJOB missing', () {
788 789 790
          platform = FakePlatform(
            environment: <String, String>{
              'FLUTTER_ROOT': _kFlutterRoot,
791 792
              'SWARMING_TASK_ID' : '12345678990',
              'GOLDCTL' : 'goldctl',
793
            },
794
            operatingSystem: 'macos',
795 796 797 798 799 800 801
          );
          expect(
            FlutterPreSubmitFileComparator.isAvailableForEnvironment(platform),
            isFalse,
          );
        });

802
        test('returns false - on Cirrus', () {
803 804 805
          platform = FakePlatform(
            environment: <String, String>{
              'FLUTTER_ROOT': _kFlutterRoot,
806 807 808
              'CIRRUS_CI': 'true',
              'CIRRUS_PR': '',
              'CIRRUS_BRANCH': 'master',
809
              'GOLD_SERVICE_ACCOUNT': 'service account...',
810
            },
811
            operatingSystem: 'macos',
812 813
          );
          expect(
814
            FlutterPostSubmitFileComparator.isAvailableForEnvironment(platform),
815 816 817
            isFalse,
          );
        });
818
      });
819
    });
820

821 822 823 824 825 826 827 828
    group('Skipping', () {
      group('correctly determines testing environment', () {
        test('returns true on Cirrus builds', () {
          platform = FakePlatform(
            environment: <String, String>{
              'FLUTTER_ROOT': _kFlutterRoot,
              'CIRRUS_CI' : 'yep',
            },
829
            operatingSystem: 'macos',
830
          );
831
          expect(
832
            FlutterSkippingFileComparator.isAvailableForEnvironment(platform),
833
            isTrue,
834
          );
835 836
        });

837
        test('returns true on irrelevant LUCI builds', () {
838 839 840
          platform = FakePlatform(
            environment: <String, String>{
              'FLUTTER_ROOT': _kFlutterRoot,
841
              'SWARMING_TASK_ID' : '1234567890',
842 843 844 845
            },
            operatingSystem: 'macos'
          );
          expect(
846
            FlutterSkippingFileComparator.isAvailableForEnvironment(platform),
847 848 849
            isTrue,
          );
        });
850

851 852 853 854 855
        test('returns false - no CI', () {
          platform = FakePlatform(
            environment: <String, String>{
              'FLUTTER_ROOT': _kFlutterRoot,
            },
856
            operatingSystem: 'macos',
857 858
          );
          expect(
859
            FlutterSkippingFileComparator.isAvailableForEnvironment(
860 861 862 863
              platform),
            isFalse,
          );
        });
864 865 866
      });
    });

867
    group('Local', () {
868
      late FlutterLocalFileComparator comparator;
869
      final FakeSkiaGoldClient fakeSkiaClient = FakeSkiaGoldClient();
870

871 872 873 874 875
      setUp(() async {
        final Directory basedir = fs.directory('flutter/test/library/')
          ..createSync(recursive: true);
        comparator = FlutterLocalFileComparator(
          basedir.uri,
876
          fakeSkiaClient,
877 878 879
          fs: fs,
          platform: FakePlatform(
            environment: <String, String>{'FLUTTER_ROOT': _kFlutterRoot},
880
            operatingSystem: 'macos',
881 882 883
          ),
        );

884 885 886 887
        const String hash = '55109a4bed52acc780530f7a9aeff6c0';
        fakeSkiaClient.expectationForTestValues['flutter.golden_test.1'] = hash;
        fakeSkiaClient.imageBytesValues[hash] =_kTestPngBytes;
        fakeSkiaClient.cleanTestNameValues['library.flutter.golden_test.1.png'] = 'flutter.golden_test.1';
888 889
      });

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
      test('asserts .png format', () async {
        await expectLater(
          () async {
            return comparator.compare(
              Uint8List.fromList(_kTestPngBytes),
              Uri.parse('flutter.golden_test.1'),
            );
          },
          throwsA(
            isA<AssertionError>().having((AssertionError error) => error.toString(),
              'description',
              contains(
                'Golden files in the Flutter framework must end with the file '
                'extension .png.'
              ),
            ),
          ),
        );
      });

910 911 912 913 914 915 916 917 918 919
      test('passes when bytes match', () async {
        expect(
          await comparator.compare(
            Uint8List.fromList(_kTestPngBytes),
            Uri.parse('flutter.golden_test.1.png'),
          ),
          isTrue,
        );
      });

920
      test('returns FlutterSkippingGoldenFileComparator when network connection is unavailable', () async {
921 922 923 924 925
        final FakeDirectory fakeDirectory = FakeDirectory();
        fakeDirectory.existsSyncValue = true;
        fakeDirectory.uri = Uri.parse('/flutter');

        fakeSkiaClient.getExpectationForTestThrowable = const OSError("Can't reach Gold");
926 927 928

        FlutterGoldenFileComparator comparator = await FlutterLocalFileComparator.fromDefaultComparator(
          platform,
929 930
          goldens: fakeSkiaClient,
          baseDirectory: fakeDirectory,
931
        );
932
        expect(comparator.runtimeType, FlutterSkippingFileComparator);
933

934 935
        fakeSkiaClient.getExpectationForTestThrowable =  const SocketException("Can't reach Gold");

936
        comparator = await FlutterLocalFileComparator.fromDefaultComparator(
937
          platform,
938 939
          goldens: fakeSkiaClient,
          baseDirectory: fakeDirectory,
940
        );
941
        expect(comparator.runtimeType, FlutterSkippingFileComparator);
942 943
        // reset property or it will carry on to other tests
        fakeSkiaClient.getExpectationForTestThrowable = null;
944
      });
945
    });
946 947 948
  });
}

949 950 951 952 953
@immutable
class RunInvocation {
  const RunInvocation(this.command, this.workingDirectory);

  final List<String> command;
954
  final String? workingDirectory;
955 956

  @override
957
  int get hashCode => Object.hash(Object.hashAll(command), workingDirectory);
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982

  bool _commandEquals(List<String> other) {
    if (other == command) {
      return true;
    }
    if (other.length != command.length) {
      return false;
    }
    for (int index = 0; index < other.length; index += 1) {
      if (other[index] != command[index]) {
        return false;
      }
    }
    return true;
  }

  @override
  bool operator ==(Object other) {
    if (other.runtimeType != runtimeType) {
      return false;
    }
    return other is RunInvocation
        && _commandEquals(other.command)
        && other.workingDirectory == workingDirectory;
  }
983

984 985 986
  @override
  String toString() => '$command ($workingDirectory)';
}
987

988 989
class FakeProcessManager extends Fake implements ProcessManager {
  Map<RunInvocation, ProcessResult> processResults = <RunInvocation, ProcessResult>{};
990

991 992
  /// Used if [processResults] does not contain a matching invocation.
  ProcessResult? fallbackProcessResult;
993

994
  final List<String?> workingDirectories = <String?>[];
995

996 997
  @override
  Future<ProcessResult> run(
998 999 1000
    List<Object> command, {
    String? workingDirectory,
    Map<String, String>? environment,
1001 1002
    bool includeParentEnvironment = true,
    bool runInShell = false,
1003 1004
    Encoding? stdoutEncoding = systemEncoding,
    Encoding? stderrEncoding = systemEncoding,
1005 1006
  }) async {
    workingDirectories.add(workingDirectory);
1007
    final ProcessResult? result = processResults[RunInvocation(command.cast<String>(), workingDirectory)];
1008
    if (result == null && fallbackProcessResult == null) {
1009
      printOnFailure('ProcessManager.run was called with $command ($workingDirectory) unexpectedly - $processResults.');
1010
      fail('See above.');
1011
    }
1012
    return result ?? fallbackProcessResult!;
1013 1014 1015
  }
}

1016
// See also dev/automated_tests/flutter_test/flutter_gold_test.dart
1017 1018
class FakeSkiaGoldClient extends Fake implements SkiaGoldClient {
  Map<String, String> expectationForTestValues = <String, String>{};
1019
  Exception? getExpectationForTestThrowable;
1020 1021 1022
  @override
  Future<String> getExpectationForTest(String testName) async {
    if (getExpectationForTestThrowable != null) {
1023
      throw getExpectationForTestThrowable!;
1024
    }
1025
    return expectationForTestValues[testName] ?? '';
1026 1027
  }

1028 1029 1030
  @override
  Future<void> auth() async {}

1031 1032
  final List<String> testNames = <String>[];

1033 1034 1035 1036
  int initCalls = 0;
  @override
  Future<void> imgtestInit() async => initCalls += 1;
  @override
1037 1038 1039 1040
  Future<bool> imgtestAdd(String testName, File goldenFile) async {
    testNames.add(testName);
    return true;
  }
1041 1042 1043 1044 1045 1046 1047

  int tryInitCalls = 0;
  @override
  Future<void> tryjobInit() async => tryInitCalls += 1;
  @override
  Future<bool> tryjobAdd(String testName, File goldenFile) async => true;

1048 1049
  Map<String, List<int>> imageBytesValues = <String, List<int>>{};
  @override
1050
  Future<List<int>> getImageBytes(String imageHash) async => imageBytesValues[imageHash]!;
1051 1052 1053

  Map<String, String> cleanTestNameValues = <String, String>{};
  @override
1054
  String cleanTestName(String fileName) => cleanTestNameValues[fileName] ?? '';
1055 1056 1057 1058
}

class FakeLocalFileComparator extends Fake implements LocalFileComparator {
  @override
1059
  late Uri basedir;
1060 1061 1062
}

class FakeDirectory extends Fake implements Directory {
1063
  late bool existsSyncValue;
1064 1065 1066 1067
  @override
  bool existsSync() => existsSyncValue;

  @override
1068
  late Uri uri;
1069 1070 1071
}

class FakeHttpClient extends Fake implements HttpClient {
1072 1073
  late Uri lastUri;
  late FakeHttpClientRequest request;
1074 1075 1076 1077 1078 1079 1080 1081 1082

  @override
  Future<HttpClientRequest> getUrl(Uri url) async {
    lastUri = url;
    return request;
  }
}

class FakeHttpClientRequest extends Fake implements HttpClientRequest {
1083
  late FakeHttpImageResponse response;
1084 1085 1086 1087 1088 1089

  @override
  Future<HttpClientResponse> close() async {
    return response;
  }
}
1090

1091 1092
class FakeHttpImageResponse extends Fake implements HttpClientResponse {
  FakeHttpImageResponse(this.response);
1093 1094 1095 1096

  final List<List<int>> response;

  @override
1097
  Future<void> forEach(void Function(List<int> element) action) async {
1098 1099 1100
    response.forEach(action);
  }
}