build_test.dart 20.9 KB
Newer Older
1 2 3 4
// Copyright 2017 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.

5
import 'dart:async';
6
import 'dart:convert';
7
import 'dart:convert' show JSON;
8

9
import 'package:file/memory.dart';
10
import 'package:flutter_tools/src/artifacts.dart';
11
import 'package:flutter_tools/src/build_info.dart';
12
import 'package:flutter_tools/src/base/build.dart';
13
import 'package:flutter_tools/src/base/context.dart';
14
import 'package:flutter_tools/src/base/file_system.dart';
15 16
import 'package:flutter_tools/src/version.dart';
import 'package:mockito/mockito.dart';
17 18 19 20
import 'package:test/test.dart';

import '../src/context.dart';

21
class MockFlutterVersion extends Mock implements FlutterVersion {}
22
class MockArtifacts extends Mock implements Artifacts {}
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 51 52 53 54 55 56
class _FakeGenSnapshot implements GenSnapshot {
  _FakeGenSnapshot({
    this.succeed: true,
    this.snapshotPath: 'output.snapshot',
    this.snapshotContent: '',
    this.depfileContent: 'output.snapshot.d : main.dart',
  });

  final bool succeed;
  final String snapshotPath;
  final String snapshotContent;
  final String depfileContent;
  int _callCount = 0;

  int get callCount => _callCount;

  @override
  Future<int> run({
    SnapshotType snapshotType,
    String packagesPath,
    String depfilePath,
    Iterable<String> additionalArgs,
  }) async {
    _callCount += 1;

    if (!succeed)
      return 1;
    await fs.file(snapshotPath).writeAsString(snapshotContent);
    await fs.file(depfilePath).writeAsString(depfileContent);
    return 0;
  }
}

57
void main() {
58 59 60 61 62 63 64 65 66 67 68 69
  group('SnapshotType', () {
    test('throws, if build mode is null', () {
      expect(
        () => new SnapshotType(TargetPlatform.android_x64, null),
        throwsA(anything),
      );
    });
    test('does not throw, if target platform is null', () {
      expect(new SnapshotType(null, BuildMode.release), isNotNull);
    });
  });
  group('Fingerprint', () {
70 71 72 73 74 75 76 77
    MockFlutterVersion mockVersion;
    const String kVersion = '123456abcdef';

    setUp(() {
      mockVersion = new MockFlutterVersion();
      when(mockVersion.frameworkRevision).thenReturn(kVersion);
    });

78
    group('fromBuildInputs', () {
79 80 81 82 83 84 85 86
      MemoryFileSystem fs;

      setUp(() {
        fs = new MemoryFileSystem();
      });

      testUsingContext('throws if any input file does not exist', () async {
        await fs.file('a.dart').create();
87
        expect(
88 89
          () => new Fingerprint.fromBuildInputs(<String, String>{}, <String>['a.dart', 'b.dart']),
          throwsArgumentError,
90
        );
91
      }, overrides: <Type, Generator>{ FileSystem: () => fs });
92 93 94 95

      testUsingContext('populates checksums for valid files', () async {
        await fs.file('a.dart').writeAsString('This is a');
        await fs.file('b.dart').writeAsString('This is b');
96
        final Fingerprint fingerprint = new Fingerprint.fromBuildInputs(<String, String>{}, <String>['a.dart', 'b.dart']);
97

98
        final Map<String, dynamic> json = JSON.decode(fingerprint.toJson());
99 100 101
        expect(json['files'], hasLength(2));
        expect(json['files']['a.dart'], '8a21a15fad560b799f6731d436c1b698');
        expect(json['files']['b.dart'], '6f144e08b58cd0925328610fad7ac07c');
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
      }, overrides: <Type, Generator>{ FileSystem: () => fs });

      testUsingContext('includes framework version', () {
        final Fingerprint fingerprint = new Fingerprint.fromBuildInputs(<String, String>{}, <String>[]);

        final Map<String, dynamic> json = JSON.decode(fingerprint.toJson());
        expect(json['version'], mockVersion.frameworkRevision);
      }, overrides: <Type, Generator>{ FlutterVersion: () => mockVersion });

      testUsingContext('includes provided properties', () {
        final Fingerprint fingerprint = new Fingerprint.fromBuildInputs(<String, String>{'a': 'A', 'b': 'B'}, <String>[]);

        final Map<String, dynamic> json = JSON.decode(fingerprint.toJson());
        expect(json['properties'], hasLength(2));
        expect(json['properties']['a'], 'A');
        expect(json['properties']['b'], 'B');
      }, overrides: <Type, Generator>{ FlutterVersion: () => mockVersion });
119 120 121
    });

    group('fromJson', () {
122
      testUsingContext('throws if JSON is invalid', () async {
123
        expect(() => new Fingerprint.fromJson('<xml></xml>'), throwsA(anything));
124 125
      }, overrides: <Type, Generator>{
        FlutterVersion: () => mockVersion,
126 127
      });

128
      testUsingContext('creates fingerprint from valid JSON', () async {
129 130
        final String json = JSON.encode(<String, dynamic>{
          'version': kVersion,
131 132 133 134 135
          'properties': <String, String>{
            'buildMode': BuildMode.release.toString(),
            'targetPlatform': TargetPlatform.ios.toString(),
            'entryPoint': 'a.dart',
          },
136 137 138 139 140
          'files': <String, dynamic>{
            'a.dart': '8a21a15fad560b799f6731d436c1b698',
            'b.dart': '6f144e08b58cd0925328610fad7ac07c',
          },
        });
141 142 143
        final Fingerprint fingerprint = new Fingerprint.fromJson(json);
        final Map<String, dynamic> content = JSON.decode(fingerprint.toJson());
        expect(content, hasLength(3));
144
        expect(content['version'], mockVersion.frameworkRevision);
145 146 147 148 149
        expect(content['properties'], hasLength(3));
        expect(content['properties']['buildMode'], BuildMode.release.toString());
        expect(content['properties']['targetPlatform'], TargetPlatform.ios.toString());
        expect(content['properties']['entryPoint'], 'a.dart');
        expect(content['files'], hasLength(2));
150 151 152 153 154 155 156
        expect(content['files']['a.dart'], '8a21a15fad560b799f6731d436c1b698');
        expect(content['files']['b.dart'], '6f144e08b58cd0925328610fad7ac07c');
      }, overrides: <Type, Generator>{
        FlutterVersion: () => mockVersion,
      });

      testUsingContext('throws ArgumentError for unknown versions', () async {
157 158
        final String json = JSON.encode(<String, dynamic>{
          'version': 'bad',
159 160
          'properties':<String, String>{},
          'files':<String, String>{},
161
        });
162
        expect(() => new Fingerprint.fromJson(json), throwsArgumentError);
163 164
      }, overrides: <Type, Generator>{
        FlutterVersion: () => mockVersion,
165 166
      });

167 168 169 170 171 172
      testUsingContext('throws ArgumentError if version is not present', () async {
        final String json = JSON.encode(<String, dynamic>{
          'properties':<String, String>{},
          'files':<String, String>{},
        });
        expect(() => new Fingerprint.fromJson(json), throwsArgumentError);
173 174 175 176
      }, overrides: <Type, Generator>{
        FlutterVersion: () => mockVersion,
      });

177 178
      testUsingContext('treats missing properties and files entries as if empty', () async {
        final String json = JSON.encode(<String, dynamic>{
179
          'version': kVersion,
180 181
        });
        expect(new Fingerprint.fromJson(json), new Fingerprint.fromBuildInputs(<String, String>{}, <String>[]));
182 183 184
      }, overrides: <Type, Generator>{
        FlutterVersion: () => mockVersion,
      });
185
    });
186

187 188
    group('operator ==', () {
      testUsingContext('reports not equal if properties do not match', () async {
189 190
        final Map<String, dynamic> a = <String, dynamic>{
          'version': kVersion,
191 192
          'properties': <String, String>{
            'buildMode': BuildMode.debug.toString(),
193
          },
194
          'files': <String, dynamic>{},
195 196
        };
        final Map<String, dynamic> b = new Map<String, dynamic>.from(a);
197 198 199 200
        b['properties'] = <String, String>{
          'buildMode': BuildMode.release.toString(),
        };
        expect(new Fingerprint.fromJson(JSON.encode(a)) == new Fingerprint.fromJson(JSON.encode(b)), isFalse);
201 202 203 204
      }, overrides: <Type, Generator>{
        FlutterVersion: () => mockVersion,
      });

205
      testUsingContext('reports not equal if file checksums do not match', () async {
206 207
        final Map<String, dynamic> a = <String, dynamic>{
          'version': kVersion,
208
          'properties': <String, String>{},
209 210 211 212 213 214 215 216 217 218
          'files': <String, dynamic>{
            'a.dart': '8a21a15fad560b799f6731d436c1b698',
            'b.dart': '6f144e08b58cd0925328610fad7ac07c',
          },
        };
        final Map<String, dynamic> b = new Map<String, dynamic>.from(a);
        b['files'] = <String, dynamic>{
          'a.dart': '8a21a15fad560b799f6731d436c1b698',
          'b.dart': '6f144e08b58cd0925328610fad7ac07d',
        };
219
        expect(new Fingerprint.fromJson(JSON.encode(a)) == new Fingerprint.fromJson(JSON.encode(b)), isFalse);
220 221
      }, overrides: <Type, Generator>{
        FlutterVersion: () => mockVersion,
222 223
      });

224
      testUsingContext('reports not equal if file paths do not match', () async {
225 226
        final Map<String, dynamic> a = <String, dynamic>{
          'version': kVersion,
227
          'properties': <String, String>{},
228 229 230 231 232 233 234 235 236 237
          'files': <String, dynamic>{
            'a.dart': '8a21a15fad560b799f6731d436c1b698',
            'b.dart': '6f144e08b58cd0925328610fad7ac07c',
          },
        };
        final Map<String, dynamic> b = new Map<String, dynamic>.from(a);
        b['files'] = <String, dynamic>{
          'a.dart': '8a21a15fad560b799f6731d436c1b698',
          'c.dart': '6f144e08b58cd0925328610fad7ac07d',
        };
238
        expect(new Fingerprint.fromJson(JSON.encode(a)) == new Fingerprint.fromJson(JSON.encode(b)), isFalse);
239 240
      }, overrides: <Type, Generator>{
        FlutterVersion: () => mockVersion,
241 242
      });

243
      testUsingContext('reports equal if properties and file checksums match', () async {
244 245
        final Map<String, dynamic> a = <String, dynamic>{
          'version': kVersion,
246 247 248 249 250
          'properties': <String, String>{
            'buildMode': BuildMode.debug.toString(),
            'targetPlatform': TargetPlatform.ios.toString(),
            'entryPoint': 'a.dart',
          },
251 252 253 254 255
          'files': <String, dynamic>{
            'a.dart': '8a21a15fad560b799f6731d436c1b698',
            'b.dart': '6f144e08b58cd0925328610fad7ac07c',
          },
        };
256 257 258 259 260 261 262 263 264 265 266
        expect(new Fingerprint.fromJson(JSON.encode(a)) == new Fingerprint.fromJson(JSON.encode(a)), isTrue);
      }, overrides: <Type, Generator>{
        FlutterVersion: () => mockVersion,
      });
    });
    group('hashCode', () {
      testUsingContext('is consistent with equals, even if map entries are reordered', () async {
        final Fingerprint a = new Fingerprint.fromJson('{"version":"$kVersion","properties":{"a":"A","b":"B"},"files":{}}');
        final Fingerprint b = new Fingerprint.fromJson('{"version":"$kVersion","properties":{"b":"B","a":"A"},"files":{}}');
        expect(a, b);
        expect(a.hashCode, b.hashCode);
267 268
      }, overrides: <Type, Generator>{
        FlutterVersion: () => mockVersion,
269
      });
270

271 272
    });
  });
273 274 275 276 277 278 279 280

  group('readDepfile', () {
    MemoryFileSystem fs;

    setUp(() {
      fs = new MemoryFileSystem();
    });

281 282
    final Map<Type, Generator> contextOverrides = <Type, Generator>{ FileSystem: () => fs };

283 284 285
    testUsingContext('returns one file if only one is listed', () async {
      await fs.file('a.d').writeAsString('snapshot.d: /foo/a.dart');
      expect(await readDepfile('a.d'), unorderedEquals(<String>['/foo/a.dart']));
286
    }, overrides: contextOverrides);
287 288 289 290 291 292 293

    testUsingContext('returns multiple files', () async {
      await fs.file('a.d').writeAsString('snapshot.d: /foo/a.dart /foo/b.dart');
      expect(await readDepfile('a.d'), unorderedEquals(<String>[
        '/foo/a.dart',
        '/foo/b.dart',
      ]));
294
    }, overrides: contextOverrides);
295 296 297 298 299 300 301 302

    testUsingContext('trims extra spaces between files', () async {
      await fs.file('a.d').writeAsString('snapshot.d: /foo/a.dart    /foo/b.dart  /foo/c.dart');
      expect(await readDepfile('a.d'), unorderedEquals(<String>[
        '/foo/a.dart',
        '/foo/b.dart',
        '/foo/c.dart',
      ]));
303
    }, overrides: contextOverrides);
304 305 306 307 308 309 310 311

    testUsingContext('returns files with spaces and backslashes', () async {
      await fs.file('a.d').writeAsString(r'snapshot.d: /foo/a\ a.dart /foo/b\\b.dart /foo/c\\ c.dart');
      expect(await readDepfile('a.d'), unorderedEquals(<String>[
        r'/foo/a a.dart',
        r'/foo/b\b.dart',
        r'/foo/c\ c.dart',
      ]));
312
    }, overrides: contextOverrides);
313
  });
314 315 316

  group('Snapshotter', () {
    const String kVersion = '123456abcdef';
317 318
    const String kIsolateSnapshotData = 'isolate_snapshot.bin';
    const String kVmSnapshotData = 'vm_isolate_snapshot.bin';
319 320 321 322 323

    _FakeGenSnapshot genSnapshot;
    MemoryFileSystem fs;
    MockFlutterVersion mockVersion;
    Snapshotter snapshotter;
324
    MockArtifacts mockArtifacts;
325 326 327

    setUp(() {
      fs = new MemoryFileSystem();
328 329
      fs.file(kIsolateSnapshotData).writeAsStringSync('snapshot data');
      fs.file(kVmSnapshotData).writeAsStringSync('vm data');
330 331 332
      genSnapshot = new _FakeGenSnapshot();
      mockVersion = new MockFlutterVersion();
      when(mockVersion.frameworkRevision).thenReturn(kVersion);
333 334 335 336
      snapshotter = new Snapshotter();
      mockArtifacts = new MockArtifacts();
      when(mockArtifacts.getArtifactPath(Artifact.isolateSnapshotData)).thenReturn(kIsolateSnapshotData);
      when(mockArtifacts.getArtifactPath(Artifact.vmSnapshotData)).thenReturn(kVmSnapshotData);
337 338
    });

339 340
    final Map<Type, Generator> contextOverrides = <Type, Generator>{
      Artifacts: () => mockArtifacts,
341 342 343
      FileSystem: () => fs,
      FlutterVersion: () => mockVersion,
      GenSnapshot: () => genSnapshot,
344
    };
345

346 347 348
    Future<Null> writeFingerprint({ Map<String, String> files = const <String, String>{} }) {
      return fs.file('output.snapshot.d.fingerprint').writeAsString(JSON.encode(<String, dynamic>{
        'version': kVersion,
349 350 351 352 353
        'properties': <String, String>{
          'buildMode': BuildMode.debug.toString(),
          'targetPlatform': '',
          'entryPoint': 'main.dart',
        },
354
        'files': <String, dynamic>{
355 356 357
          kVmSnapshotData: '2ec34912477a46c03ddef07e8b909b46',
          kIsolateSnapshotData: '621b3844bb7d4d17d2cfc5edf9a91c4c',
        }..addAll(files),
358
      }));
359 360 361 362 363
    }

    Future<Null> buildSnapshot({ String mainPath = 'main.dart' }) {
      return snapshotter.buildScriptSnapshot(
        mainPath: mainPath,
364 365 366 367
        snapshotPath: 'output.snapshot',
        depfilePath: 'output.snapshot.d',
        packagesPath: '.packages',
      );
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
    }

    void expectFingerprintHas({
      String entryPoint: 'main.dart',
      Map<String, String> checksums = const <String, String>{},
    }) {
      final Map<String, dynamic> json = JSON.decode(fs.file('output.snapshot.d.fingerprint').readAsStringSync());
      expect(json['properties']['entryPoint'], entryPoint);
      expect(json['files'], hasLength(checksums.length + 2));
      checksums.forEach((String path, String checksum) {
        expect(json['files'][path], checksum);
      });
      expect(json['files'][kVmSnapshotData], '2ec34912477a46c03ddef07e8b909b46');
      expect(json['files'][kIsolateSnapshotData], '621b3844bb7d4d17d2cfc5edf9a91c4c');
    }

    testUsingContext('builds snapshot and fingerprint when no fingerprint is present', () async {
      await fs.file('main.dart').writeAsString('void main() {}');
      await fs.file('output.snapshot').create();
      await fs.file('output.snapshot.d').writeAsString('snapshot : main.dart');
      await buildSnapshot();
389 390

      expect(genSnapshot.callCount, 1);
391 392 393 394 395
      expectFingerprintHas(checksums: <String, String>{
        'main.dart': '27f5ebf0f8c559b2af9419d190299a5e',
        'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e',
      });
    }, overrides: contextOverrides);
396

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    testUsingContext('builds snapshot and fingerprint when fingerprints differ', () async {
      await fs.file('main.dart').writeAsString('void main() {}');
      await fs.file('output.snapshot').create();
      await fs.file('output.snapshot.d').writeAsString('output.snapshot : main.dart');
      await writeFingerprint(files: <String, String>{
        'main.dart': '27f5ebf0f8c559b2af9419d190299a5e',
        'output.snapshot': 'deadbeef000b204e9800998ecaaaaa',
      });
      await buildSnapshot();

      expect(genSnapshot.callCount, 1);
      expectFingerprintHas(checksums: <String, String>{
        'main.dart': '27f5ebf0f8c559b2af9419d190299a5e',
        'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e',
      });
    }, overrides: contextOverrides);

    testUsingContext('builds snapshot and fingerprint when fingerprints match but previous snapshot not present', () async {
      await fs.file('main.dart').writeAsString('void main() {}');
      await fs.file('output.snapshot.d').writeAsString('output.snapshot : main.dart');
      await writeFingerprint(files: <String, String>{
        'main.dart': '27f5ebf0f8c559b2af9419d190299a5e',
        'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e',
      });
      await buildSnapshot();

      expect(genSnapshot.callCount, 1);
      expectFingerprintHas(checksums: <String, String>{
        'main.dart': '27f5ebf0f8c559b2af9419d190299a5e',
        'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e',
      });
    }, overrides: contextOverrides);
429

430
    testUsingContext('builds snapshot and fingerprint when main entry point changes to other dependency', () async {
431 432
      final _FakeGenSnapshot genSnapshot = new _FakeGenSnapshot(
        snapshotPath: 'output.snapshot',
433
        depfileContent: 'output.snapshot : main.dart other.dart',
434 435 436
      );
      context.setVariable(GenSnapshot, genSnapshot);

437 438
      await fs.file('main.dart').writeAsString('import "other.dart";\nvoid main() {}');
      await fs.file('other.dart').writeAsString('import "main.dart";\nvoid main() {}');
439
      await fs.file('output.snapshot').create();
440
      await fs.file('output.snapshot.d').writeAsString('output.snapshot : main.dart');
441 442 443 444 445 446 447 448 449 450 451
      await writeFingerprint(files: <String, String>{
        'main.dart': 'bc096b33f14dde5e0ffaf93a1d03395c',
        'other.dart': 'e0c35f083f0ad76b2d87100ec678b516',
        'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e',
      });
      await buildSnapshot(mainPath: 'other.dart');

      expect(genSnapshot.callCount, 1);
      expectFingerprintHas(
        entryPoint: 'other.dart',
        checksums: <String, String>{
452 453
          'main.dart': 'bc096b33f14dde5e0ffaf93a1d03395c',
          'other.dart': 'e0c35f083f0ad76b2d87100ec678b516',
454 455 456
          'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e',
        },
      );
457
    }, overrides: contextOverrides);
458

459
    testUsingContext('skips snapshot when fingerprints match and previous snapshot is present', () async {
460 461 462
      await fs.file('main.dart').writeAsString('void main() {}');
      await fs.file('output.snapshot').create();
      await fs.file('output.snapshot.d').writeAsString('output.snapshot : main.dart');
463 464 465 466 467
      await writeFingerprint(files: <String, String>{
        'main.dart': '27f5ebf0f8c559b2af9419d190299a5e',
        'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e',
      });
      await buildSnapshot();
468 469

      expect(genSnapshot.callCount, 0);
470 471 472 473 474
      expectFingerprintHas(checksums: <String, String>{
        'main.dart': '27f5ebf0f8c559b2af9419d190299a5e',
        'output.snapshot': 'd41d8cd98f00b204e9800998ecf8427e',
      });
    }, overrides: contextOverrides);
475 476

    group('createFingerprint', () {
477 478 479 480 481 482 483 484 485
      final Map<Type, Generator> contextOverrides = <Type, Generator>{
        FileSystem: () => fs,
        Artifacts: () => mockArtifacts,
      };
      final List<String> artifactPaths = <String>[
        kVmSnapshotData,
        kIsolateSnapshotData,
      ];
      testUsingContext('creates fingerprint with target platform', () {
486 487 488 489 490 491 492 493 494
        final Fingerprint fingerprint = Snapshotter.createFingerprint(
          new SnapshotType(TargetPlatform.android_x64, BuildMode.release),
          'a.dart',
          <String>[],
        );
        expect(fingerprint, new Fingerprint.fromBuildInputs(<String, String>{
          'buildMode': 'BuildMode.release',
          'targetPlatform': 'TargetPlatform.android_x64',
          'entryPoint': 'a.dart',
495 496 497
        }, artifactPaths));
      }, overrides: contextOverrides);
      testUsingContext('creates fingerprint without target platform', () {
498 499 500 501 502 503 504 505 506
        final Fingerprint fingerprint = Snapshotter.createFingerprint(
          new SnapshotType(null, BuildMode.release),
          'a.dart',
          <String>[],
        );
        expect(fingerprint, new Fingerprint.fromBuildInputs(<String, String>{
          'buildMode': 'BuildMode.release',
          'targetPlatform': '',
          'entryPoint': 'a.dart',
507 508
        }, artifactPaths));
      }, overrides: contextOverrides);
509 510 511 512 513 514 515 516 517 518 519 520
      testUsingContext('creates fingerprint with file checksums', () async {
        await fs.file('a.dart').create();
        await fs.file('b.dart').create();
        final Fingerprint fingerprint = Snapshotter.createFingerprint(
          new SnapshotType(TargetPlatform.android_x64, BuildMode.release),
          'a.dart',
          <String>['a.dart', 'b.dart'],
        );
        expect(fingerprint, new Fingerprint.fromBuildInputs(<String, String>{
          'buildMode': 'BuildMode.release',
          'targetPlatform': 'TargetPlatform.android_x64',
          'entryPoint': 'a.dart',
521 522 523 524 525
        }, <String>[
          'a.dart',
          'b.dart',
        ]..addAll(artifactPaths)));
      }, overrides: contextOverrides);
526
    });
527
  });
528
}