version_test.dart 35.4 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
// @dart = 2.8

7 8
import 'dart:convert';

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

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

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

void main() {
29 30
  MockProcessManager mockProcessManager;
  MockCache mockCache;
31
  FakeProcessManager processManager;
32 33

  setUp(() {
34
    processManager = FakeProcessManager.list(<FakeCommand>[]);
35 36
    mockProcessManager = MockProcessManager();
    mockCache = MockCache();
37
  });
38

39 40 41 42 43 44 45 46 47
  testUsingContext('Channel enum and string transform to each other', () {
    for (final Channel channel in Channel.values) {
      expect(getNameForChannel(channel), kOfficialChannels.toList()[channel.index]);
    }
    expect(kOfficialChannels.toList().map((String str) => getChannelForName(str)).toList(),
      Channel.values);
  });

  for (final String channel in kOfficialChannels) {
48 49 50
    DateTime getChannelUpToDateVersion() {
      return _testClock.ago(FlutterVersion.versionAgeConsideredUpToDate(channel) ~/ 2);
    }
51

52 53 54
    DateTime getChannelOutOfDateVersion() {
      return _testClock.ago(FlutterVersion.versionAgeConsideredUpToDate(channel) * 2);
    }
55

56 57 58 59 60
    group('$FlutterVersion for $channel', () {
      setUpAll(() {
        Cache.disableLocking();
        FlutterVersion.timeToPauseToLetUserReadTheMessage = Duration.zero;
      });
61

62 63 64 65 66 67 68 69 70 71 72
      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,
        );
73 74 75 76 77 78 79

        processManager.addCommand(const FakeCommand(
          command: <String>['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%H'],
          stdout: '1234abcd',
        ));

        processManager.addCommand(const FakeCommand(
80
          command: <String>['git', 'tag', '--points-at', '1234abcd'],
81 82 83
        ));

        processManager.addCommand(const FakeCommand(
84
          command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', '1234abcd'],
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
          stdout: '0.1.2-3-1234abcd',
        ));

        processManager.addCommand(FakeCommand(
          command: const <String>['git', 'rev-parse', '--abbrev-ref', '--symbolic', '@{u}'],
          stdout: channel,
        ));

        processManager.addCommand(FakeCommand(
          command: const <String>['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%ad', '--date=iso'],
          stdout: getChannelUpToDateVersion().toString(),
        ));

        processManager.addCommand(const FakeCommand(
          command: <String>['git', 'remote'],
        ));

        processManager.addCommand(const FakeCommand(
          command: <String>['git', 'remote', 'add', '__flutter_version_check__', 'https://github.com/flutter/flutter.git'],
        ));

        processManager.addCommand(FakeCommand(
          command: <String>['git', 'fetch', '__flutter_version_check__', channel],
        ));

        processManager.addCommand(FakeCommand(
          command: <String>['git', '-c', 'log.showSignature=false', 'log', '__flutter_version_check__/$channel', '-n', '1', '--pretty=format:%ad', '--date=iso'],
          stdout: getChannelOutOfDateVersion().toString(),
        ));
        processManager.addCommand(const FakeCommand(
          command: <String>['git', 'remote'],
        ));

118
        await globals.flutterVersion.checkFlutterVersionFreshness();
119
        _expectVersionMessage('');
120
        expect(processManager.hasRemainingExpectations, isFalse);
121
      }, overrides: <Type, Generator>{
122
        FlutterVersion: () => FlutterVersion(clock: _testClock),
123
        ProcessManager: () => processManager,
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
        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,
        );
141
        final FlutterVersion version = globals.flutterVersion;
142 143 144 145

        await version.checkFlutterVersionFreshness();
        _expectVersionMessage('');
      }, overrides: <Type, Generator>{
146
        FlutterVersion: () => FlutterVersion(clock: _testClock),
147 148 149 150 151 152 153 154 155 156
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('does not ping server when version stamp is up-to-date', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          localCommitDate: getChannelOutOfDateVersion(),
          stamp: VersionCheckStamp(
157
            lastTimeVersionWasChecked: _stampUpToDate,
158 159 160 161 162 163
            lastKnownRemoteVersion: getChannelUpToDateVersion(),
          ),
          expectSetStamp: true,
          channel: channel,
        );

164
        final FlutterVersion version = globals.flutterVersion;
165 166 167
        await version.checkFlutterVersionFreshness();
        _expectVersionMessage(FlutterVersion.newVersionAvailableMessage());
      }, overrides: <Type, Generator>{
168
        FlutterVersion: () => FlutterVersion(clock: _testClock),
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        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,
        );

186
        final FlutterVersion version = globals.flutterVersion;
187 188 189 190 191 192 193
        await version.checkFlutterVersionFreshness();
        _expectVersionMessage(FlutterVersion.newVersionAvailableMessage());
        expect((await VersionCheckStamp.load()).lastTimeWarningWasPrinted, _testClock.now());

        await version.checkFlutterVersionFreshness();
        _expectVersionMessage('');
      }, overrides: <Type, Generator>{
194
        FlutterVersion: () => FlutterVersion(clock: _testClock),
195 196 197 198 199 200 201 202 203 204 205 206 207 208
        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,
        );
209
        final FlutterVersion version = globals.flutterVersion;
210

211 212
        await version.checkFlutterVersionFreshness();
        _expectVersionMessage(FlutterVersion.newVersionAvailableMessage());
213

214 215 216 217 218 219 220 221 222 223 224
        // 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>{
225
        FlutterVersion: () => FlutterVersion(clock: _testClock),
226 227 228 229 230 231 232 233 234 235
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('pings server when version stamp is out-of-date', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          localCommitDate: getChannelOutOfDateVersion(),
          stamp: VersionCheckStamp(
236
            lastTimeVersionWasChecked: _stampOutOfDate,
237
            lastKnownRemoteVersion: _testClock.ago(const Duration(days: 2)),
238 239 240 241 242 243
          ),
          remoteCommitDate: getChannelUpToDateVersion(),
          expectSetStamp: true,
          expectServerPing: true,
          channel: channel,
        );
244
        final FlutterVersion version = globals.flutterVersion;
245 246 247 248

        await version.checkFlutterVersionFreshness();
        _expectVersionMessage(FlutterVersion.newVersionAvailableMessage());
      }, overrides: <Type, Generator>{
249
        FlutterVersion: () => FlutterVersion(clock: _testClock),
250 251 252 253 254 255
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('does not print warning when unable to connect to server if not out of date', () async {
        fakeData(
256 257
          mockProcessManager,
          mockCache,
258
          localCommitDate: getChannelUpToDateVersion(),
259 260
          errorOnFetch: true,
          expectServerPing: true,
261 262 263
          expectSetStamp: true,
          channel: channel,
        );
264
        final FlutterVersion version = globals.flutterVersion;
265 266 267 268

        await version.checkFlutterVersionFreshness();
        _expectVersionMessage('');
      }, overrides: <Type, Generator>{
269
        FlutterVersion: () => FlutterVersion(clock: _testClock),
270 271 272 273 274 275 276 277 278 279 280 281 282 283
        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,
        );
284
        final FlutterVersion version = globals.flutterVersion;
285 286 287 288

        await version.checkFlutterVersionFreshness();
        _expectVersionMessage(FlutterVersion.versionOutOfDateMessage(_testClock.now().difference(getChannelOutOfDateVersion())));
      }, overrides: <Type, Generator>{
289
        FlutterVersion: () => FlutterVersion(clock: _testClock),
290 291 292 293 294 295 296 297 298 299 300 301 302 303
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('versions comparison', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          localCommitDate: getChannelOutOfDateVersion(),
          errorOnFetch: true,
          expectServerPing: true,
          expectSetStamp: true,
          channel: channel,
        );
304
        final FlutterVersion version = globals.flutterVersion;
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

        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>{
323
        FlutterVersion: () => FlutterVersion(clock: _testClock),
324 325
        ProcessManager: () => mockProcessManager,
      });
326 327
    });

328 329 330 331 332 333
    group('$VersionCheckStamp for $channel', () {
      void _expectDefault(VersionCheckStamp stamp) {
        expect(stamp.lastKnownRemoteVersion, isNull);
        expect(stamp.lastTimeVersionWasChecked, isNull);
        expect(stamp.lastTimeWarningWasPrinted, isNull);
      }
334

335 336 337 338
      testUsingContext('loads blank when stamp file missing', () async {
        fakeData(mockProcessManager, mockCache, channel: channel);
        _expectDefault(await VersionCheckStamp.load());
      }, overrides: <Type, Generator>{
339
        FlutterVersion: () => FlutterVersion(clock: _testClock),
340 341 342 343 344 345 346 347
        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>{
348
        FlutterVersion: () => FlutterVersion(clock: _testClock),
349 350 351 352 353 354 355 356 357 358 359 360 361
        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>{
362
        FlutterVersion: () => FlutterVersion(clock: _testClock),
363 364 365 366 367 368 369 370 371
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });

      testUsingContext('loads valid JSON', () async {
        fakeData(
          mockProcessManager,
          mockCache,
          stampJson: '''
372
      {
373 374
        "lastKnownRemoteVersion": "${_testClock.ago(const Duration(days: 1))}",
        "lastTimeVersionWasChecked": "${_testClock.ago(const Duration(days: 2))}",
375 376
        "lastTimeWarningWasPrinted": "${_testClock.now()}"
      }
377 378 379 380 381 382 383 384 385
      ''',
          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>{
386
        FlutterVersion: () => FlutterVersion(clock: _testClock),
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
        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>{
413
        FlutterVersion: () => FlutterVersion(clock: _testClock),
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
        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>{
444
        FlutterVersion: () => FlutterVersion(clock: _testClock),
445 446 447
        ProcessManager: () => mockProcessManager,
        Cache: () => mockCache,
      });
448
    });
449
  }
450 451 452

  testUsingContext('GitTagVersion', () {
    const String hash = 'abcdef';
453 454
    GitTagVersion gitTagVersion;

455 456 457 458
    // 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');
459 460 461
    expect(gitTagVersion.devVersion, 4);
    expect(gitTagVersion.devPatch, 5);

462 463 464 465 466 467 468 469 470 471 472 473
    // 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');
474 475 476 477 478
    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');
479
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.4-0.0.pre.13');
480
    expect(gitTagVersion.gitTag, '1.2.3');
481 482 483
    expect(gitTagVersion.devVersion, null);
    expect(gitTagVersion.devPatch, null);

484 485 486 487
    // 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');
488 489 490
    expect(gitTagVersion.devVersion, 4);
    expect(gitTagVersion.devPatch, 5);

491
    // new tag release format, stable channel
492
    gitTagVersion = GitTagVersion.parse('1.2.3-13-g$hash');
493
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.4-0.0.pre.13');
494
    expect(gitTagVersion.gitTag, '1.2.3');
495 496 497
    expect(gitTagVersion.devVersion, null);
    expect(gitTagVersion.devPatch, null);

498
    expect(GitTagVersion.parse('98.76.54-32-g$hash').frameworkVersionFor(hash), '98.76.55-0.0.pre.32');
499
    expect(GitTagVersion.parse('10.20.30-0-g$hash').frameworkVersionFor(hash), '10.20.30');
500
    expect(testLogger.traceText, '');
501
    expect(GitTagVersion.parse('v1.2.3+hotfix.1-4-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
502
    expect(GitTagVersion.parse('x1.2.3-4-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
503
    expect(GitTagVersion.parse('1.0.0-unknown-0-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
504
    expect(GitTagVersion.parse('beta-1-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
505
    expect(GitTagVersion.parse('1.2.3-4-gx$hash').frameworkVersionFor(hash), '0.0.0-unknown');
506 507
    expect(testLogger.statusText, '');
    expect(testLogger.errorText, '');
508 509
    expect(
      testLogger.traceText,
510
      'Could not interpret results of "git describe": v1.2.3+hotfix.1-4-gabcdef\n'
511
      'Could not interpret results of "git describe": x1.2.3-4-gabcdef\n'
512
      'Could not interpret results of "git describe": 1.0.0-unknown-0-gabcdef\n'
513
      'Could not interpret results of "git describe": beta-1-gabcdef\n'
514
      'Could not interpret results of "git describe": 1.2.3-4-gxabcdef\n',
515 516
    );
  });
517

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
  testUsingContext('determine reports correct stable version if HEAD is at a tag', () {
    const String stableTag = '1.2.3';
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(
      <FakeCommand>[
        const FakeCommand(
          command: <String>['git', 'tag', '--points-at', 'HEAD'],
          stdout: stableTag,
        ),
      ],
    );
    final ProcessUtils processUtils = ProcessUtils(
      processManager: fakeProcessManager,
      logger: BufferLogger.test(),
    );
    final GitTagVersion gitTagVersion = GitTagVersion.determine(processUtils, workingDirectory: '.');
    expect(gitTagVersion.frameworkVersionFor('abcd1234'), stableTag);
  });

  testUsingContext('determine favors stable tag over dev tag if both idenitfy HEAD', () {
    const String stableTag = '1.2.3';
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(
      <FakeCommand>[
        const FakeCommand(
          command: <String>['git', 'tag', '--points-at', 'HEAD'],
          // This tests the unlikely edge case where a dev release made it to stable without any cherry picks
          stdout: '1.2.3-6.0.pre\n$stableTag',
        ),
      ],
    );
    final ProcessUtils processUtils = ProcessUtils(
      processManager: fakeProcessManager,
      logger: BufferLogger.test(),
    );
    final GitTagVersion gitTagVersion = GitTagVersion.determine(processUtils, workingDirectory: '.');
    expect(gitTagVersion.frameworkVersionFor('abcd1234'), stableTag);
  });

  testUsingContext('determine reports correct git describe version if HEAD is not at a tag', () {
    const String devTag = '1.2.3-2.0.pre';
    const String headRevision = 'abcd1234';
    const String commitsAhead = '12';
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(
      <FakeCommand>[
        const FakeCommand(
          command: <String>['git', 'tag', '--points-at', 'HEAD'],
          stdout: '', // no tag
        ),
        const FakeCommand(
566
          command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
567 568 569 570 571 572 573 574 575 576 577
          stdout: '$devTag-$commitsAhead-g$headRevision',
        ),
      ],
    );
    final ProcessUtils processUtils = ProcessUtils(
      processManager: fakeProcessManager,
      logger: BufferLogger.test(),
    );
    final GitTagVersion gitTagVersion = GitTagVersion.determine(processUtils, workingDirectory: '.');
    // reported version should increment the number after the dash
    expect(gitTagVersion.frameworkVersionFor(headRevision), '1.2.3-3.0.pre.12');
578 579
  });

580 581 582 583 584 585 586 587
  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(
588
      <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
589 590 591
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(RunResult(ProcessResult(106, 0, 'v0.1.2-3-1234abcd', ''), <String>['git', 'describe']));
592
    when(processUtils.runSync(
593
      <String>['git', 'tag', '--points-at', 'HEAD'],
594 595 596 597
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(
      RunResult(ProcessResult(110, 0, '', ''),
598
      <String>['git', 'tag', '--points-at', 'HEAD'],
599
    ));
600 601 602

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

603 604 605 606 607
    verifyNever(processUtils.runSync(
      <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    ));
608 609 610 611 612 613
    verifyNever(processUtils.runSync(
      <String>['git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    ));
    verify(processUtils.runSync(
614
      <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
615 616 617 618 619
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).called(1);
  });

620
  testUsingContext('determine does not fetch tags on dev/stable/beta', () {
621
    final MockProcessUtils processUtils = MockProcessUtils();
622 623 624 625 626
    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']));
627 628 629 630
    when(processUtils.runSync(
      <String>['git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
631
    )).thenReturn(RunResult(ProcessResult(106, 0, '', ''), <String>['git', 'fetch']));
632
    when(processUtils.runSync(
633
      <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
634 635
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
636
    )).thenReturn(RunResult(ProcessResult(107, 0, 'v0.1.2-3-1234abcd', ''), <String>['git', 'describe']));
637
    when(processUtils.runSync(
638
      <String>['git', 'tag', '--points-at', 'HEAD'],
639 640 641 642
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(
      RunResult(ProcessResult(108, 0, '', ''),
643
      <String>['git', 'tag', '--points-at', 'HEAD'],
644
    ));
645 646 647 648 649 650 651 652 653 654 655 656 657 658

    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(
659
      <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
660 661 662 663 664 665 666 667 668 669 670 671 672
      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(
673
      <String>['git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags', '-f'],
674 675 676 677
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(RunResult(ProcessResult(109, 0, '', ''), <String>['git', 'fetch']));
    when(processUtils.runSync(
678
      <String>['git', 'tag', '--points-at', 'HEAD'],
679 680 681 682
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(
      RunResult(ProcessResult(110, 0, '', ''),
683
      <String>['git', 'tag', '--points-at', 'HEAD'],
684 685
    ));
    when(processUtils.runSync(
686
      <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
687 688
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
689
    )).thenReturn(RunResult(ProcessResult(111, 0, 'v0.1.2-3-1234abcd', ''), <String>['git', 'describe']));
690 691 692

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

693 694 695 696 697
    verify(processUtils.runSync(
      <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).called(1);
698
    verify(processUtils.runSync(
699
      <String>['git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags', '-f'],
700 701 702 703
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).called(1);
    verify(processUtils.runSync(
704
      <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
705 706 707 708
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).called(1);
  });
709 710 711 712 713 714 715 716 717 718 719 720 721 722

  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(
723
      <String>['git', 'tag', '--points-at', 'HEAD'],
724 725 726 727
      workingDirectory: anyNamed('workingDirectory'),
      environment: anyNamed('environment'),
    )).thenReturn(
      RunResult(ProcessResult(110, 0, '', ''),
728
      <String>['git', 'tag', '--points-at', 'HEAD'],
729 730
    ));
    when(processUtils.runSync(
731
      <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
      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',
    }),
  });
748 749 750
}

void _expectVersionMessage(String message) {
751 752
  expect(testLogger.statusText.trim(), message.trim());
  testLogger.clear();
753 754
}

755 756 757
void fakeData(
  ProcessManager pm,
  Cache cache, {
758
  DateTime localCommitDate,
759
  DateTime remoteCommitDate,
760 761
  VersionCheckStamp stamp,
  String stampJson,
762 763 764
  bool errorOnFetch = false,
  bool expectSetStamp = false,
  bool expectServerPing = false,
765
  String channel = 'master',
766 767
}) {
  ProcessResult success(String standardOutput) {
768
    return ProcessResult(1, 0, standardOutput, '');
769 770 771
  }

  ProcessResult failure(int exitCode) {
772
    return ProcessResult(1, exitCode, '', 'error');
773 774 775
  }

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

778
    if (stampJson != null) {
779
      return stampJson;
780
    }
781

782
    if (stamp != null) {
783
      return json.encode(stamp.toJson());
784
    }
785

786
    return null;
787 788 789
  });

  when(cache.setStampFor(any, any)).thenAnswer((Invocation invocation) {
790
    expect(invocation.positionalArguments.first, VersionCheckStamp.flutterVersionCheckStampFile);
791 792

    if (expectSetStamp) {
793
      stamp = VersionCheckStamp.fromJson(castStringKeyedMap(json.decode(invocation.positionalArguments[1] as String)));
794
      return;
795 796
    }

797
    throw StateError('Unexpected call to Cache.setStampFor(${invocation.positionalArguments}, ${invocation.namedArguments})');
798 799
  });

800
  ProcessResult syncAnswer(Invocation invocation) {
801
    bool argsAre(String a1, [ String a2, String a3, String a4, String a5, String a6, String a7, String a8, String a9 ]) {
802
      const ListEquality<String> equality = ListEquality<String>();
803
      final List<String> args = invocation.positionalArguments.single as List<String>;
804
      final List<String> expectedArgs = <String>[a1, a2, a3, a4, a5, a6, a7, a8, a9].where((String arg) => arg != null).toList();
805 806 807
      return equality.equals(args, expectedArgs);
    }

808
    bool listArgsAre(List<String> a) {
809
      return Function.apply(argsAre, a) as bool;
810 811 812
    }

    if (listArgsAre(FlutterVersion.gitLog(<String>['-n', '1', '--pretty=format:%ad', '--date=iso']))) {
813 814 815 816 817
      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('');
818 819
    } else if (argsAre('git', 'fetch', '__flutter_version_check__', channel)) {
      if (!expectServerPing) {
820
        fail('Did not expect server ping');
821
      }
822
      return errorOnFetch ? failure(128) : success('');
823 824
    // 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']))) {
825
      return success(remoteCommitDate.toString());
826 827
    } else if (argsAre('git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags')) {
      return success('');
828 829
    }

830
    throw StateError('Unexpected call to ProcessManager.run(${invocation.positionalArguments}, ${invocation.namedArguments})');
831
  }
832

833 834
  when(pm.runSync(any, workingDirectory: anyNamed('workingDirectory'))).thenAnswer(syncAnswer);
  when(pm.run(any, workingDirectory: anyNamed('workingDirectory'))).thenAnswer((Invocation invocation) async {
835 836
    return syncAnswer(invocation);
  });
837 838 839 840 841

  when(pm.runSync(
    <String>['git', 'rev-parse', '--abbrev-ref', '--symbolic', '@{u}'],
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
842
  )).thenReturn(ProcessResult(101, 0, channel, ''));
843 844 845 846
  when(pm.runSync(
    <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
847
  )).thenReturn(ProcessResult(102, 0, 'branch', ''));
848
  when(pm.runSync(
849
    FlutterVersion.gitLog(<String>['-n', '1', '--pretty=format:%H']),
850 851
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
852
  )).thenReturn(ProcessResult(103, 0, '1234abcd', ''));
853
  when(pm.runSync(
854
    FlutterVersion.gitLog(<String>['-n', '1', '--pretty=format:%ar']),
855 856
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
857
  )).thenReturn(ProcessResult(104, 0, '1 second ago', ''));
858 859 860 861 862
  when(pm.runSync(
    <String>['git', 'fetch', 'https://github.com/flutter/flutter', '--tags'],
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
  )).thenReturn(ProcessResult(105, 0, '', ''));
863
  when(pm.runSync(
864
    <String>['git', 'tag', '--points-at', '1234abcd'],
865 866 867 868
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
  )).thenReturn(ProcessResult(106, 0, '', ''));
  when(pm.runSync(
869
    <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', '1234abcd'],
870 871
    workingDirectory: anyNamed('workingDirectory'),
    environment: anyNamed('environment'),
872
  )).thenReturn(ProcessResult(107, 0, 'v0.1.2-3-1234abcd', ''));
873 874 875
}

class MockProcessManager extends Mock implements ProcessManager {}
876
class MockProcessUtils extends Mock implements ProcessUtils {}
877
class MockCache extends Mock implements Cache {}