version_test.dart 31.7 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:convert';

7
import 'package:collection/collection.dart' show ListEquality;
8 9
import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/io.dart';
10
import 'package:flutter_tools/src/base/platform.dart';
11
import 'package:flutter_tools/src/base/process.dart';
12 13
import 'package:flutter_tools/src/base/time.dart';
import 'package:flutter_tools/src/base/utils.dart';
14
import 'package:flutter_tools/src/cache.dart';
15
import 'package:flutter_tools/src/globals.dart' as globals;
16
import 'package:flutter_tools/src/version.dart';
17 18
import 'package:mockito/mockito.dart';
import 'package:process/process.dart';
19

20 21
import '../src/common.dart';
import '../src/context.dart';
22

23
final SystemClock _testClock = SystemClock.fixed(DateTime(2015, 1, 1));
24 25
final DateTime _stampUpToDate = _testClock.ago(FlutterVersion.checkAgeConsideredUpToDate ~/ 2);
final DateTime _stampOutOfDate = _testClock.ago(FlutterVersion.checkAgeConsideredUpToDate * 2);
26 27

void main() {
28 29 30 31
  MockProcessManager mockProcessManager;
  MockCache mockCache;

  setUp(() {
32 33
    mockProcessManager = MockProcessManager();
    mockCache = MockCache();
34
  });
35

36
  for (final String channel in FlutterVersion.officialChannels) {
37 38 39
    DateTime getChannelUpToDateVersion() {
      return _testClock.ago(FlutterVersion.versionAgeConsideredUpToDate(channel) ~/ 2);
    }
40

41 42 43
    DateTime getChannelOutOfDateVersion() {
      return _testClock.ago(FlutterVersion.versionAgeConsideredUpToDate(channel) * 2);
    }
44

45 46 47 48 49
    group('$FlutterVersion for $channel', () {
      setUpAll(() {
        Cache.disableLocking();
        FlutterVersion.timeToPauseToLetUserReadTheMessage = Duration.zero;
      });
50

51 52 53 54 55 56 57 58 59 60 61
      testUsingContext('prints nothing when Flutter installation looks fresh', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          localCommitDate: getChannelUpToDateVersion(),
          // Server will be pinged because we haven't pinged within last x days
          expectServerPing: true,
          remoteCommitDate: getChannelOutOfDateVersion(),
          expectSetStamp: true,
          channel: channel,
        );
62
        await globals.flutterVersion.checkFlutterVersionFreshness();
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
        _expectVersionMessage('');
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('prints nothing when Flutter installation looks out-of-date but is actually up-to-date', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          localCommitDate: getChannelOutOfDateVersion(),
          stamp: VersionCheckStamp(
            lastTimeVersionWasChecked: _stampOutOfDate,
            lastKnownRemoteVersion: getChannelOutOfDateVersion(),
          ),
          remoteCommitDate: getChannelOutOfDateVersion(),
          expectSetStamp: true,
          expectServerPing: true,
          channel: channel,
        );
84
        final FlutterVersion version = globals.flutterVersion;
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

        await version.checkFlutterVersionFreshness();
        _expectVersionMessage('');
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('does not ping server when version stamp is up-to-date', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          localCommitDate: getChannelOutOfDateVersion(),
          stamp: VersionCheckStamp(
100
            lastTimeVersionWasChecked: _stampUpToDate,
101 102 103 104 105 106
            lastKnownRemoteVersion: getChannelUpToDateVersion(),
          ),
          expectSetStamp: true,
          channel: channel,
        );

107
        final FlutterVersion version = globals.flutterVersion;
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        await version.checkFlutterVersionFreshness();
        _expectVersionMessage(FlutterVersion.newVersionAvailableMessage());
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('does not print warning if printed recently', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          localCommitDate: getChannelOutOfDateVersion(),
          stamp: VersionCheckStamp(
            lastTimeVersionWasChecked: _stampUpToDate,
            lastKnownRemoteVersion: getChannelUpToDateVersion(),
          ),
          expectSetStamp: true,
          channel: channel,
        );

129
        final FlutterVersion version = globals.flutterVersion;
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        await version.checkFlutterVersionFreshness();
        _expectVersionMessage(FlutterVersion.newVersionAvailableMessage());
        expect((await VersionCheckStamp.load()).lastTimeWarningWasPrinted, _testClock.now());

        await version.checkFlutterVersionFreshness();
        _expectVersionMessage('');
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('pings server when version stamp is missing then does not', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          localCommitDate: getChannelOutOfDateVersion(),
          remoteCommitDate: getChannelUpToDateVersion(),
          expectSetStamp: true,
          expectServerPing: true,
          channel: channel,
        );
152
        final FlutterVersion version = globals.flutterVersion;
153

154 155
        await version.checkFlutterVersionFreshness();
        _expectVersionMessage(FlutterVersion.newVersionAvailableMessage());
156

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        // Immediate subsequent check is not expected to ping the server.
        fakeData(
          mockProcessManager,
          mockCache,
          localCommitDate: getChannelOutOfDateVersion(),
          stamp: await VersionCheckStamp.load(),
          channel: channel,
        );
        await version.checkFlutterVersionFreshness();
        _expectVersionMessage('');
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('pings server when version stamp is out-of-date', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          localCommitDate: getChannelOutOfDateVersion(),
          stamp: VersionCheckStamp(
179
            lastTimeVersionWasChecked: _stampOutOfDate,
180
            lastKnownRemoteVersion: _testClock.ago(const Duration(days: 2)),
181 182 183 184 185 186
          ),
          remoteCommitDate: getChannelUpToDateVersion(),
          expectSetStamp: true,
          expectServerPing: true,
          channel: channel,
        );
187
        final FlutterVersion version = globals.flutterVersion;
188 189 190 191 192 193 194 195 196 197 198

        await version.checkFlutterVersionFreshness();
        _expectVersionMessage(FlutterVersion.newVersionAvailableMessage());
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('does not print warning when unable to connect to server if not out of date', () async {
        fakeData(
199 200
          mockProcessManager,
          mockCache,
201
          localCommitDate: getChannelUpToDateVersion(),
202 203
          errorOnFetch: true,
          expectServerPing: true,
204 205 206
          expectSetStamp: true,
          channel: channel,
        );
207
        final FlutterVersion version = globals.flutterVersion;
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

        await version.checkFlutterVersionFreshness();
        _expectVersionMessage('');
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('prints warning when unable to connect to server if really out of date', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          localCommitDate: getChannelOutOfDateVersion(),
          errorOnFetch: true,
          expectServerPing: true,
          expectSetStamp: true,
          channel: channel,
        );
227
        final FlutterVersion version = globals.flutterVersion;
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246

        await version.checkFlutterVersionFreshness();
        _expectVersionMessage(FlutterVersion.versionOutOfDateMessage(_testClock.now().difference(getChannelOutOfDateVersion())));
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('versions comparison', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          localCommitDate: getChannelOutOfDateVersion(),
          errorOnFetch: true,
          expectServerPing: true,
          expectSetStamp: true,
          channel: channel,
        );
247
        final FlutterVersion version = globals.flutterVersion;
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

        when(mockProcessManager.runSync(
          <String>['git', 'merge-base', '--is-ancestor', 'abcdef', '123456'],
          workingDirectory: anyNamed('workingDirectory'),
        )).thenReturn(ProcessResult(1, 0, '', ''));

        expect(
            version.checkRevisionAncestry(
              tentativeDescendantRevision: '123456',
              tentativeAncestorRevision: 'abcdef',
            ),
            true);

        verify(mockProcessManager.runSync(
          <String>['git', 'merge-base', '--is-ancestor', 'abcdef', '123456'],
          workingDirectory: anyNamed('workingDirectory'),
        ));
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
      });
269 270
    });

271 272 273 274 275 276
    group('$VersionCheckStamp for $channel', () {
      void _expectDefault(VersionCheckStamp stamp) {
        expect(stamp.lastKnownRemoteVersion, isNull);
        expect(stamp.lastTimeVersionWasChecked, isNull);
        expect(stamp.lastTimeWarningWasPrinted, isNull);
      }
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
      testUsingContext('loads blank when stamp file missing', () async {
        fakeData(mockProcessManager, mockCache, channel: channel);
        _expectDefault(await VersionCheckStamp.load());
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('loads blank when stamp file is malformed JSON', () async {
        fakeData(mockProcessManager, mockCache, stampJson: '<', channel: channel);
        _expectDefault(await VersionCheckStamp.load());
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('loads blank when stamp file is well-formed but invalid JSON', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          stampJson: '[]',
          channel: channel,
        );
        _expectDefault(await VersionCheckStamp.load());
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('loads valid JSON', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          stampJson: '''
315
      {
316 317
        "lastKnownRemoteVersion": "${_testClock.ago(const Duration(days: 1))}",
        "lastTimeVersionWasChecked": "${_testClock.ago(const Duration(days: 2))}",
318 319
        "lastTimeWarningWasPrinted": "${_testClock.now()}"
      }
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 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 380 381 382 383 384 385 386 387 388 389 390
      ''',
          channel: channel,
        );

        final VersionCheckStamp stamp = await VersionCheckStamp.load();
        expect(stamp.lastKnownRemoteVersion, _testClock.ago(const Duration(days: 1)));
        expect(stamp.lastTimeVersionWasChecked, _testClock.ago(const Duration(days: 2)));
        expect(stamp.lastTimeWarningWasPrinted, _testClock.now());
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('stores version stamp', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          expectSetStamp: true,
          channel: channel,
        );

        _expectDefault(await VersionCheckStamp.load());

        final VersionCheckStamp stamp = VersionCheckStamp(
          lastKnownRemoteVersion: _testClock.ago(const Duration(days: 1)),
          lastTimeVersionWasChecked: _testClock.ago(const Duration(days: 2)),
          lastTimeWarningWasPrinted: _testClock.now(),
        );
        await stamp.store();

        final VersionCheckStamp storedStamp = await VersionCheckStamp.load();
        expect(storedStamp.lastKnownRemoteVersion, _testClock.ago(const Duration(days: 1)));
        expect(storedStamp.lastTimeVersionWasChecked, _testClock.ago(const Duration(days: 2)));
        expect(storedStamp.lastTimeWarningWasPrinted, _testClock.now());
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('overwrites individual fields', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          expectSetStamp: true,
          channel: channel,
        );

        _expectDefault(await VersionCheckStamp.load());

        final VersionCheckStamp stamp = VersionCheckStamp(
          lastKnownRemoteVersion: _testClock.ago(const Duration(days: 10)),
          lastTimeVersionWasChecked: _testClock.ago(const Duration(days: 9)),
          lastTimeWarningWasPrinted: _testClock.ago(const Duration(days: 8)),
        );
        await stamp.store(
          newKnownRemoteVersion: _testClock.ago(const Duration(days: 1)),
          newTimeVersionWasChecked: _testClock.ago(const Duration(days: 2)),
          newTimeWarningWasPrinted: _testClock.now(),
        );

        final VersionCheckStamp storedStamp = await VersionCheckStamp.load();
        expect(storedStamp.lastKnownRemoteVersion, _testClock.ago(const Duration(days: 1)));
        expect(storedStamp.lastTimeVersionWasChecked, _testClock.ago(const Duration(days: 2)));
        expect(storedStamp.lastTimeWarningWasPrinted, _testClock.now());
      }, overrides: <Type, Generator>{
        FlutterVersion: () => FlutterVersion(_testClock),
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });
391
    });
392
  }
393 394 395

  testUsingContext('GitTagVersion', () {
    const String hash = 'abcdef';
396 397
    GitTagVersion gitTagVersion;

398 399 400 401
    // Master channel
    gitTagVersion = GitTagVersion.parse('1.2.3-4.5.pre-13-g$hash');
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.3-5.0.pre.13');
    expect(gitTagVersion.gitTag, '1.2.3-4.5.pre');
402 403 404
    expect(gitTagVersion.devVersion, 4);
    expect(gitTagVersion.devPatch, 5);

405 406 407 408 409 410 411 412 413 414 415 416
    // Stable channel
    gitTagVersion = GitTagVersion.parse('1.2.3');
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.3');
    expect(gitTagVersion.x, 1);
    expect(gitTagVersion.y, 2);
    expect(gitTagVersion.z, 3);
    expect(gitTagVersion.devVersion, null);
    expect(gitTagVersion.devPatch, null);

    // Dev channel
    gitTagVersion = GitTagVersion.parse('1.2.3-4.5.pre');
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.3-4.5.pre');
417 418 419 420 421
    expect(gitTagVersion.gitTag, '1.2.3-4.5.pre');
    expect(gitTagVersion.devVersion, 4);
    expect(gitTagVersion.devPatch, 5);

    gitTagVersion = GitTagVersion.parse('1.2.3-13-g$hash');
422
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.4-0.0.pre.13');
423
    expect(gitTagVersion.gitTag, '1.2.3');
424 425 426
    expect(gitTagVersion.devVersion, null);
    expect(gitTagVersion.devPatch, null);

427 428 429 430
    // new tag release format, dev channel
    gitTagVersion = GitTagVersion.parse('1.2.3-4.5.pre-0-g$hash');
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.3-4.5.pre');
    expect(gitTagVersion.gitTag, '1.2.3-4.5.pre');
431 432 433
    expect(gitTagVersion.devVersion, 4);
    expect(gitTagVersion.devPatch, 5);

434
    // new tag release format, stable channel
435
    gitTagVersion = GitTagVersion.parse('1.2.3-13-g$hash');
436
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.4-0.0.pre.13');
437
    expect(gitTagVersion.gitTag, '1.2.3');
438 439 440
    expect(gitTagVersion.devVersion, null);
    expect(gitTagVersion.devPatch, null);

441
    expect(GitTagVersion.parse('98.76.54-32-g$hash').frameworkVersionFor(hash), '98.76.55-0.0.pre.32');
442
    expect(GitTagVersion.parse('10.20.30-0-g$hash').frameworkVersionFor(hash), '10.20.30');
443
    expect(testLogger.traceText, '');
444
    expect(GitTagVersion.parse('v1.2.3+hotfix.1-4-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
445
    expect(GitTagVersion.parse('x1.2.3-4-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
446
    expect(GitTagVersion.parse('1.0.0-unknown-0-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
447
    expect(GitTagVersion.parse('beta-1-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
448
    expect(GitTagVersion.parse('1.2.3-4-gx$hash').frameworkVersionFor(hash), '0.0.0-unknown');
449 450
    expect(testLogger.statusText, '');
    expect(testLogger.errorText, '');
451 452
    expect(
      testLogger.traceText,
453
      'Could not interpret results of "git describe": v1.2.3+hotfix.1-4-gabcdef\n'
454
      'Could not interpret results of "git describe": x1.2.3-4-gabcdef\n'
455
      'Could not interpret results of "git describe": 1.0.0-unknown-0-gabcdef\n'
456
      'Could not interpret results of "git describe": beta-1-gabcdef\n'
457
      'Could not interpret results of "git describe": 1.2.3-4-gxabcdef\n',
458 459
    );
  });
460

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
  testUsingContext('determine favors stable tags over dev tags', () {
    final MockProcessUtils mockProcessUtils = MockProcessUtils();
    when(mockProcessUtils.runSync(
      <String>['git', 'tag', '--contains', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(RunResult(
      ProcessResult(1, 0, '1.2.3-0.0.pre\n1.2.3\n1.2.3-0.1.pre', ''),
      <String>['git', 'tag', '--contains', 'HEAD'],
    ));
    final GitTagVersion version = GitTagVersion.determine(mockProcessUtils, workingDirectory: '.');
    expect(version.gitTag, '1.2.3');
    expect(version.devPatch, null);
    expect(version.devVersion, null);
    // We shouldn't have to fallback to git describe, because we are exactly
    // on a release tag.
    verifyNever(mockProcessUtils.runSync(
478
      <String>['git', 'describe', '--match', '*.*.*', '--first-parent', '--long', '--tags'],
479 480 481 482 483
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    ));
  });

484 485 486 487 488 489 490 491
  testUsingContext('determine does not call fetch --tags', () {
    final MockProcessUtils processUtils = MockProcessUtils();
    when(processUtils.runSync(
      <String>['git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(RunResult(ProcessResult(105, 0, '', ''), <String>['git', 'fetch']));
    when(processUtils.runSync(
492
      <String>['git', 'describe', '--match', '*.*.*', '--first-parent', '--long', '--tags'],
493 494 495
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(RunResult(ProcessResult(106, 0, 'v0.1.2-3-1234abcd', ''), <String>['git', 'describe']));
496 497 498 499 500 501 502 503
    when(processUtils.runSync(
      <String>['git', 'tag', '--contains', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(
      RunResult(ProcessResult(110, 0, '', ''),
      <String>['git', 'tag', '--contains', 'HEAD'],
    ));
504 505 506

    GitTagVersion.determine(processUtils, workingDirectory: '.');

507 508 509 510 511
    verifyNever(processUtils.runSync(
      <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    ));
512 513 514 515 516 517
    verifyNever(processUtils.runSync(
      <String>['git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    ));
    verify(processUtils.runSync(
518
      <String>['git', 'describe', '--match', '*.*.*', '--first-parent', '--long', '--tags'],
519 520 521 522 523
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).called(1);
  });

524
  testUsingContext('determine does not fetch tags on dev/stable/beta', () {
525
    final MockProcessUtils processUtils = MockProcessUtils();
526 527 528 529 530
    when(processUtils.runSync(
      <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(RunResult(ProcessResult(105, 0, 'dev', ''), <String>['git', 'fetch']));
531 532 533 534
    when(processUtils.runSync(
      <String>['git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
535
    )).thenReturn(RunResult(ProcessResult(106, 0, '', ''), <String>['git', 'fetch']));
536
    when(processUtils.runSync(
537
      <String>['git', 'describe', '--match', '*.*.*', '--first-parent', '--long', '--tags'],
538 539
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
540
    )).thenReturn(RunResult(ProcessResult(107, 0, 'v0.1.2-3-1234abcd', ''), <String>['git', 'describe']));
541 542 543 544 545 546 547 548
    when(processUtils.runSync(
      <String>['git', 'tag', '--contains', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(
      RunResult(ProcessResult(108, 0, '', ''),
      <String>['git', 'tag', '--contains', 'HEAD'],
    ));
549 550 551 552 553 554 555 556 557 558 559 560 561 562

    GitTagVersion.determine(processUtils, workingDirectory: '.', fetchTags: true);

    verify(processUtils.runSync(
      <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).called(1);
    verifyNever(processUtils.runSync(
      <String>['git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    ));
    verify(processUtils.runSync(
563
      <String>['git', 'describe', '--match', '*.*.*', '--first-parent', '--long', '--tags'],
564 565 566 567 568 569 570 571 572 573 574 575 576
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).called(1);
  });

  testUsingContext('determine calls fetch --tags on master', () {
    final MockProcessUtils processUtils = MockProcessUtils();
    when(processUtils.runSync(
      <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(RunResult(ProcessResult(108, 0, 'master', ''), <String>['git', 'fetch']));
    when(processUtils.runSync(
577
      <String>['git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags', '-f'],
578 579 580 581
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(RunResult(ProcessResult(109, 0, '', ''), <String>['git', 'fetch']));
    when(processUtils.runSync(
582 583 584 585 586 587 588 589
      <String>['git', 'tag', '--contains', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(
      RunResult(ProcessResult(110, 0, '', ''),
      <String>['git', 'tag', '--contains', 'HEAD'],
    ));
    when(processUtils.runSync(
590
      <String>['git', 'describe', '--match', '*.*.*', '--first-parent', '--long', '--tags'],
591 592
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
593
    )).thenReturn(RunResult(ProcessResult(111, 0, 'v0.1.2-3-1234abcd', ''), <String>['git', 'describe']));
594 595 596

    GitTagVersion.determine(processUtils, workingDirectory: '.', fetchTags: true);

597 598 599 600 601
    verify(processUtils.runSync(
      <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).called(1);
602
    verify(processUtils.runSync(
603
      <String>['git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags', '-f'],
604 605 606 607
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).called(1);
    verify(processUtils.runSync(
608
      <String>['git', 'describe', '--match', '*.*.*', '--first-parent', '--long', '--tags'],
609 610 611 612
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).called(1);
  });
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634

  testUsingContext('determine uses overridden git url', () {
    final MockProcessUtils processUtils = MockProcessUtils();
    when(processUtils.runSync(
      <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(RunResult(ProcessResult(108, 0, 'master', ''), <String>['git', 'fetch']));
    when(processUtils.runSync(
      <String>['git', 'fetch', 'https://githubmirror.com/flutter.git', '--tags', '-f'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(RunResult(ProcessResult(109, 0, '', ''), <String>['git', 'fetch']));
    when(processUtils.runSync(
      <String>['git', 'tag', '--contains', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(
      RunResult(ProcessResult(110, 0, '', ''),
      <String>['git', 'tag', '--contains', 'HEAD'],
    ));
    when(processUtils.runSync(
635
      <String>['git', 'describe', '--match', '*.*.*', '--first-parent', '--long', '--tags'],
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(RunResult(ProcessResult(111, 0, 'v0.1.2-3-1234abcd', ''), <String>['git', 'describe']));

    GitTagVersion.determine(processUtils, workingDirectory: '.', fetchTags: true);

    verify(processUtils.runSync(
      <String>['git', 'fetch', 'https://githubmirror.com/flutter.git', '--tags', '-f'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).called(1);
  }, overrides: <Type, Generator>{
    Platform: () => FakePlatform(environment: <String, String>{
      'FLUTTER_GIT_URL': 'https://githubmirror.com/flutter.git',
    }),
  });
652 653 654
}

void _expectVersionMessage(String message) {
655 656
  expect(testLogger.statusText.trim(), message.trim());
  testLogger.clear();
657 658
}

659 660 661
void fakeData(
  ProcessManager pm,
  Cache cache, {
662
  DateTime localCommitDate,
663
  DateTime remoteCommitDate,
664 665
  VersionCheckStamp stamp,
  String stampJson,
666 667 668
  bool errorOnFetch = false,
  bool expectSetStamp = false,
  bool expectServerPing = false,
669
  String channel = 'master',
670 671
}) {
  ProcessResult success(String standardOutput) {
672
    return ProcessResult(1, 0, standardOutput, '');
673 674 675
  }

  ProcessResult failure(int exitCode) {
676
    return ProcessResult(1, exitCode, '', 'error');
677 678 679
  }

  when(cache.getStampFor(any)).thenAnswer((Invocation invocation) {
680
    expect(invocation.positionalArguments.single, VersionCheckStamp.flutterVersionCheckStampFile);
681

682
    if (stampJson != null) {
683
      return stampJson;
684
    }
685

686
    if (stamp != null) {
687
      return json.encode(stamp.toJson());
688
    }
689

690
    return null;
691 692 693
  });

  when(cache.setStampFor(any, any)).thenAnswer((Invocation invocation) {
694
    expect(invocation.positionalArguments.first, VersionCheckStamp.flutterVersionCheckStampFile);
695 696

    if (expectSetStamp) {
697
      stamp = VersionCheckStamp.fromJson(castStringKeyedMap(json.decode(invocation.positionalArguments[1] as String)));
698
      return;
699 700
    }

701
    throw StateError('Unexpected call to Cache.setStampFor(${invocation.positionalArguments}, ${invocation.namedArguments})');
702 703
  });

704
  final Answering<ProcessResult> syncAnswer = (Invocation invocation) {
705
    bool argsAre(String a1, [ String a2, String a3, String a4, String a5, String a6, String a7, String a8, String a9 ]) {
706
      const ListEquality<String> equality = ListEquality<String>();
707
      final List<String> args = invocation.positionalArguments.single as List<String>;
708
      final List<String> expectedArgs = <String>[a1, a2, a3, a4, a5, a6, a7, a8, a9].where((String arg) => arg != null).toList();
709 710 711
      return equality.equals(args, expectedArgs);
    }

712
    bool listArgsAre(List<String> a) {
713
      return Function.apply(argsAre, a) as bool;
714 715 716
    }

    if (listArgsAre(FlutterVersion.gitLog(<String>['-n', '1', '--pretty=format:%ad', '--date=iso']))) {
717 718 719 720 721
      return success(localCommitDate.toString());
    } else if (argsAre('git', 'remote')) {
      return success('');
    } else if (argsAre('git', 'remote', 'add', '__flutter_version_check__', 'https://github.com/flutter/flutter.git')) {
      return success('');
722 723
    } else if (argsAre('git', 'fetch', '__flutter_version_check__', channel)) {
      if (!expectServerPing) {
724
        fail('Did not expect server ping');
725
      }
726
      return errorOnFetch ? failure(128) : success('');
727 728
    // Careful here!  argsAre accepts 9 arguments and FlutterVersion.gitLog adds 4.
    } else if (remoteCommitDate != null && listArgsAre(FlutterVersion.gitLog(<String>['__flutter_version_check__/$channel', '-n', '1', '--pretty=format:%ad', '--date=iso']))) {
729
      return success(remoteCommitDate.toString());
730 731
    } else if (argsAre('git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags')) {
      return success('');
732 733
    }

734
    throw StateError('Unexpected call to ProcessManager.run(${invocation.positionalArguments}, ${invocation.namedArguments})');
735 736
  };

737 738
  when(pm.runSync(any, workingDirectory: anyNamed('workingDirectory'))).thenAnswer(syncAnswer);
  when(pm.run(any, workingDirectory: anyNamed('workingDirectory'))).thenAnswer((Invocation invocation) async {
739 740
    return syncAnswer(invocation);
  });
741 742 743 744 745

  when(pm.runSync(
    <String>['git', 'rev-parse', '--abbrev-ref', '--symbolic', '@{u}'],
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
746
  )).thenReturn(ProcessResult(101, 0, channel, ''));
747 748 749 750
  when(pm.runSync(
    <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
751
  )).thenReturn(ProcessResult(102, 0, 'branch', ''));
752
  when(pm.runSync(
753
    FlutterVersion.gitLog(<String>['-n', '1', '--pretty=format:%H']),
754 755
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
756
  )).thenReturn(ProcessResult(103, 0, '1234abcd', ''));
757
  when(pm.runSync(
758
    FlutterVersion.gitLog(<String>['-n', '1', '--pretty=format:%ar']),
759 760
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
761
  )).thenReturn(ProcessResult(104, 0, '1 second ago', ''));
762 763 764 765 766
  when(pm.runSync(
    <String>['git', 'fetch', 'https://github.com/flutter/flutter', '--tags'],
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
  )).thenReturn(ProcessResult(105, 0, '', ''));
767
  when(pm.runSync(
768 769 770 771 772
    <String>['git', 'tag', '--contains', 'HEAD'],
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
  )).thenReturn(ProcessResult(106, 0, '', ''));
  when(pm.runSync(
773
    <String>['git', 'describe', '--match', '*.*.*', '--first-parent', '--long', '--tags'],
774 775
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
776
  )).thenReturn(ProcessResult(107, 0, 'v0.1.2-3-1234abcd', ''));
777 778 779
}

class MockProcessManager extends Mock implements ProcessManager {}
780
class MockProcessUtils extends Mock implements ProcessUtils {}
781
class MockCache extends Mock implements Cache {}