pub_get_test.dart 25.2 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 'package:file/file.dart';
import 'package:file/memory.dart';
9
import 'package:flutter_tools/src/base/bot_detector.dart';
10
import 'package:flutter_tools/src/base/common.dart';
11
import 'package:flutter_tools/src/base/file_system.dart';
12
import 'package:flutter_tools/src/base/io.dart';
13
import 'package:flutter_tools/src/base/logger.dart';
14
import 'package:flutter_tools/src/base/platform.dart';
15
import 'package:flutter_tools/src/cache.dart';
16
import 'package:flutter_tools/src/dart/pub.dart';
17
import 'package:flutter_tools/src/reporting/reporting.dart';
18
import 'package:mockito/mockito.dart';
19
import 'package:process/process.dart';
20
import 'package:fake_async/fake_async.dart';
21

22 23
import '../../src/common.dart';
import '../../src/context.dart';
24
import '../../src/mocks.dart' as mocks;
25 26

void main() {
27
  setUpAll(() {
28
    Cache.flutterRoot = '';
29
  });
30

31 32 33 34
  tearDown(() {
    MockDirectory.findCache = false;
  });

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
  testWithoutContext('checkUpToDate skips pub get if the package config is newer than the pubspec '
    'and the current framework version is the same as the last version', () async {
    final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[]);
    final BufferLogger logger = BufferLogger.test();
    final MemoryFileSystem fileSystem = MemoryFileSystem.test();

    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('pubspec.lock').createSync();
    fileSystem.file('.dart_tool/package_config.json').createSync(recursive: true);
    fileSystem.file('.dart_tool/version').writeAsStringSync('a');
    fileSystem.file('version').writeAsStringSync('a');

    final Pub pub = Pub(
      fileSystem: fileSystem,
      logger: logger,
      processManager: processManager,
51
      usage: TestUsage(),
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
      platform: FakePlatform(
        environment: const <String, String>{},
      ),
      botDetector: const BotDetectorAlwaysNo(),
    );

    await pub.get(
      context: PubContext.pubGet,
      checkUpToDate: true,
    );

    expect(logger.traceText, contains('Skipping pub get: version match.'));
  });

  testWithoutContext('checkUpToDate does not skip pub get if the package config is newer than the pubspec '
    'but the current framework version is not the same as the last version', () async {
    final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
      const FakeCommand(command: <String>[
        'bin/cache/dart-sdk/bin/pub',
        '--verbosity=warning',
        'get',
        '--no-precompile',
      ])
    ]);
    final BufferLogger logger = BufferLogger.test();
    final MemoryFileSystem fileSystem = MemoryFileSystem.test();

    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('pubspec.lock').createSync();
    fileSystem.file('.dart_tool/package_config.json').createSync(recursive: true);
    fileSystem.file('.dart_tool/version').writeAsStringSync('a');
    fileSystem.file('version').writeAsStringSync('b');

    final Pub pub = Pub(
      fileSystem: fileSystem,
      logger: logger,
      processManager: processManager,
89
      usage: TestUsage(),
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
      platform: FakePlatform(
        environment: const <String, String>{},
      ),
      botDetector: const BotDetectorAlwaysNo(),
    );

    await pub.get(
      context: PubContext.pubGet,
      checkUpToDate: true,
    );

    expect(processManager.hasRemainingExpectations, false);
    expect(fileSystem.file('.dart_tool/version').readAsStringSync(), 'b');
  });

  testWithoutContext('checkUpToDate does not skip pub get if the package config is newer than the pubspec '
    'but the current framework version does not exist yet', () async {
    final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
      const FakeCommand(command: <String>[
        'bin/cache/dart-sdk/bin/pub',
        '--verbosity=warning',
        'get',
        '--no-precompile',
      ])
    ]);
    final BufferLogger logger = BufferLogger.test();
    final MemoryFileSystem fileSystem = MemoryFileSystem.test();

    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('pubspec.lock').createSync();
    fileSystem.file('.dart_tool/package_config.json').createSync(recursive: true);
    fileSystem.file('version').writeAsStringSync('b');

    final Pub pub = Pub(
      fileSystem: fileSystem,
      logger: logger,
      processManager: processManager,
127
      usage: TestUsage(),
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
      platform: FakePlatform(
        environment: const <String, String>{},
      ),
      botDetector: const BotDetectorAlwaysNo(),
    );

    await pub.get(
      context: PubContext.pubGet,
      checkUpToDate: true,
    );

    expect(processManager.hasRemainingExpectations, false);
    expect(fileSystem.file('.dart_tool/version').readAsStringSync(), 'b');
  });

  testWithoutContext('checkUpToDate does not skip pub get if the package config does not exist', () async {
    final MemoryFileSystem fileSystem = MemoryFileSystem.test();
    final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
      FakeCommand(command: const <String>[
        'bin/cache/dart-sdk/bin/pub',
        '--verbosity=warning',
        'get',
        '--no-precompile',
      ], onRun: () {
        fileSystem.file('.dart_tool/package_config.json').createSync(recursive: true);
      })
    ]);
    final BufferLogger logger = BufferLogger.test();

    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('pubspec.lock').createSync();
    fileSystem.file('version').writeAsStringSync('b');

    final Pub pub = Pub(
      fileSystem: fileSystem,
      logger: logger,
      processManager: processManager,
165
      usage: TestUsage(),
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
      platform: FakePlatform(
        environment: const <String, String>{},
      ),
      botDetector: const BotDetectorAlwaysNo(),
    );

    await pub.get(
      context: PubContext.pubGet,
      checkUpToDate: true,
    );

    expect(processManager.hasRemainingExpectations, false);
    expect(fileSystem.file('.dart_tool/version').readAsStringSync(), 'b');
  });

  testWithoutContext('checkUpToDate does not skip pub get if the pubspec.lock does not exist', () async {
    final MemoryFileSystem fileSystem = MemoryFileSystem.test();
    final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
      const FakeCommand(command: <String>[
        'bin/cache/dart-sdk/bin/pub',
        '--verbosity=warning',
        'get',
        '--no-precompile',
      ]),
    ]);
    final BufferLogger logger = BufferLogger.test();

    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('version').writeAsStringSync('b');
    fileSystem.file('.dart_tool/package_config.json').createSync(recursive: true);
    fileSystem.file('.dart_tool/version').writeAsStringSync('b');

    final Pub pub = Pub(
      fileSystem: fileSystem,
      logger: logger,
      processManager: processManager,
202
      usage: TestUsage(),
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
      platform: FakePlatform(
        environment: const <String, String>{},
      ),
      botDetector: const BotDetectorAlwaysNo(),
    );

    await pub.get(
      context: PubContext.pubGet,
      checkUpToDate: true,
    );

    expect(processManager.hasRemainingExpectations, false);
    expect(fileSystem.file('.dart_tool/version').readAsStringSync(), 'b');
  });

  testWithoutContext('checkUpToDate does not skip pub get if the package config is older that the pubspec', () async {
    final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
      const FakeCommand(command: <String>[
        'bin/cache/dart-sdk/bin/pub',
        '--verbosity=warning',
        'get',
        '--no-precompile',
      ])
    ]);
    final BufferLogger logger = BufferLogger.test();
    final MemoryFileSystem fileSystem = MemoryFileSystem.test();

    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('pubspec.lock').createSync();
    fileSystem.file('.dart_tool/package_config.json')
      ..createSync(recursive: true)
      ..setLastModifiedSync(DateTime(1991));
    fileSystem.file('version').writeAsStringSync('b');

    final Pub pub = Pub(
      fileSystem: fileSystem,
      logger: logger,
      processManager: processManager,
241
      usage: TestUsage(),
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
      platform: FakePlatform(
        environment: const <String, String>{},
      ),
      botDetector: const BotDetectorAlwaysNo(),
    );

    await pub.get(
      context: PubContext.pubGet,
      checkUpToDate: true,
    );

    expect(processManager.hasRemainingExpectations, false);
    expect(fileSystem.file('.dart_tool/version').readAsStringSync(), 'b');
  });

  testWithoutContext('checkUpToDate does not skip pub get if the pubspec.lock is older that the pubspec', () async {
    final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
      const FakeCommand(command: <String>[
        'bin/cache/dart-sdk/bin/pub',
        '--verbosity=warning',
        'get',
        '--no-precompile',
      ])
    ]);
    final BufferLogger logger = BufferLogger.test();
    final MemoryFileSystem fileSystem = MemoryFileSystem.test();

    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('pubspec.lock')
      ..createSync()
      ..setLastModifiedSync(DateTime(1991));
    fileSystem.file('.dart_tool/package_config.json')
      .createSync(recursive: true);
    fileSystem.file('version').writeAsStringSync('b');
    fileSystem.file('.dart_tool/version').writeAsStringSync('b');

    final Pub pub = Pub(
      fileSystem: fileSystem,
      logger: logger,
      processManager: processManager,
282
      usage: TestUsage(),
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
      platform: FakePlatform(
        environment: const <String, String>{},
      ),
      botDetector: const BotDetectorAlwaysNo(),
    );

    await pub.get(
      context: PubContext.pubGet,
      checkUpToDate: true,
    );

    expect(processManager.hasRemainingExpectations, false);
    expect(fileSystem.file('.dart_tool/version').readAsStringSync(), 'b');
  });

298
  testWithoutContext('pub get 69', () async {
299
    String error;
300

301 302 303 304 305 306
    final MockProcessManager processMock = MockProcessManager(69);
    final BufferLogger logger = BufferLogger.test();
    final Pub pub = Pub(
      fileSystem: MockFileSystem(),
      logger: logger,
      processManager: processMock,
307
      usage: TestUsage(),
308 309 310 311 312
      platform: FakePlatform(
        environment: const <String, String>{},
      ),
      botDetector: const BotDetectorAlwaysNo(),
    );
313

314
    FakeAsync().run((FakeAsync time) {
Josh Soref's avatar
Josh Soref committed
315
      expect(processMock.lastPubEnvironment, isNull);
316
      expect(logger.statusText, '');
317
      pub.get(context: PubContext.flutterTests).then((void value) {
318
        error = 'test completed unexpectedly';
319 320
      }, onError: (dynamic thrownError) {
        error = 'test failed unexpectedly: $thrownError';
321 322
      });
      time.elapse(const Duration(milliseconds: 500));
323
      expect(logger.statusText,
324
        'Running "flutter pub get" in /...\n'
325
        'pub get failed (server unavailable) -- attempting retry 1 in 1 second...\n',
326
      );
Josh Soref's avatar
Josh Soref committed
327
      expect(processMock.lastPubEnvironment, contains('flutter_cli:flutter_tests'));
328
      expect(processMock.lastPubCache, isNull);
329
      time.elapse(const Duration(milliseconds: 500));
330
      expect(logger.statusText,
331
        'Running "flutter pub get" in /...\n'
332 333
        'pub get failed (server unavailable) -- attempting retry 1 in 1 second...\n'
        'pub get failed (server unavailable) -- attempting retry 2 in 2 seconds...\n',
334 335
      );
      time.elapse(const Duration(seconds: 1));
336
      expect(logger.statusText,
337
        'Running "flutter pub get" in /...\n'
338 339
        'pub get failed (server unavailable) -- attempting retry 1 in 1 second...\n'
        'pub get failed (server unavailable) -- attempting retry 2 in 2 seconds...\n',
340 341
      );
      time.elapse(const Duration(seconds: 100)); // from t=0 to t=100
342
      expect(logger.statusText,
343
        'Running "flutter pub get" in /...\n'
344 345 346 347 348 349 350
        'pub get failed (server unavailable) -- attempting retry 1 in 1 second...\n'
        'pub get failed (server unavailable) -- attempting retry 2 in 2 seconds...\n'
        'pub get failed (server unavailable) -- attempting retry 3 in 4 seconds...\n' // at t=1
        'pub get failed (server unavailable) -- attempting retry 4 in 8 seconds...\n' // at t=5
        'pub get failed (server unavailable) -- attempting retry 5 in 16 seconds...\n' // at t=13
        'pub get failed (server unavailable) -- attempting retry 6 in 32 seconds...\n' // at t=29
        'pub get failed (server unavailable) -- attempting retry 7 in 64 seconds...\n', // at t=61
351 352
      );
      time.elapse(const Duration(seconds: 200)); // from t=0 to t=200
353
      expect(logger.statusText,
354
        'Running "flutter pub get" in /...\n'
355 356 357 358 359 360 361 362 363 364
        'pub get failed (server unavailable) -- attempting retry 1 in 1 second...\n'
        'pub get failed (server unavailable) -- attempting retry 2 in 2 seconds...\n'
        'pub get failed (server unavailable) -- attempting retry 3 in 4 seconds...\n'
        'pub get failed (server unavailable) -- attempting retry 4 in 8 seconds...\n'
        'pub get failed (server unavailable) -- attempting retry 5 in 16 seconds...\n'
        'pub get failed (server unavailable) -- attempting retry 6 in 32 seconds...\n'
        'pub get failed (server unavailable) -- attempting retry 7 in 64 seconds...\n'
        'pub get failed (server unavailable) -- attempting retry 8 in 64 seconds...\n' // at t=39
        'pub get failed (server unavailable) -- attempting retry 9 in 64 seconds...\n' // at t=103
        'pub get failed (server unavailable) -- attempting retry 10 in 64 seconds...\n', // at t=167
365 366
      );
    });
367
    expect(logger.errorText, isEmpty);
368
    expect(error, isNull);
369 370
  });

371 372 373 374 375 376
  testWithoutContext('pub get 66 shows message from pub', () async {
    final BufferLogger logger = BufferLogger.test();
    final Pub pub = Pub(
      platform: FakePlatform(environment: const <String, String>{}),
      fileSystem: MockFileSystem(),
      logger: logger,
377
      usage: TestUsage(),
378 379 380
      botDetector: const BotDetectorAlwaysNo(),
      processManager: MockProcessManager(66, stderr: 'err1\nerr2\nerr3\n', stdout: 'out1\nout2\nout3\n'),
    );
381
    try {
382
      await pub.get(context: PubContext.flutterTests);
383 384 385 386
      throw AssertionError('pubGet did not fail');
    } on ToolExit catch (error) {
      expect(error.message, 'pub get failed (66; err3)');
    }
387
    expect(logger.statusText,
388 389 390 391 392
      'Running "flutter pub get" in /...\n'
      'out1\n'
      'out2\n'
      'out3\n'
    );
393
    expect(logger.errorText,
394 395 396 397 398 399
      'err1\n'
      'err2\n'
      'err3\n'
    );
  });

400
  testWithoutContext('pub cache in root is used', () async {
401
    String error;
402 403 404 405
    final MockProcessManager processMock = MockProcessManager(69);
    final MockFileSystem fsMock = MockFileSystem();
    final Pub pub = Pub(
      platform: FakePlatform(environment: const <String, String>{}),
406
      usage: TestUsage(),
407 408 409 410 411
      fileSystem: fsMock,
      logger: BufferLogger.test(),
      processManager: processMock,
      botDetector: const BotDetectorAlwaysNo(),
    );
412

413
    FakeAsync().run((FakeAsync time) {
414
      MockDirectory.findCache = true;
Josh Soref's avatar
Josh Soref committed
415
      expect(processMock.lastPubEnvironment, isNull);
416
      expect(processMock.lastPubCache, isNull);
417
      pub.get(context: PubContext.flutterTests).then((void value) {
418 419 420 421 422
        error = 'test completed unexpectedly';
      }, onError: (dynamic thrownError) {
        error = 'test failed unexpectedly: $thrownError';
      });
      time.elapse(const Duration(milliseconds: 500));
423

424
      expect(processMock.lastPubCache, equals(fsMock.path.join(Cache.flutterRoot, '.pub-cache')));
425 426 427 428
      expect(error, isNull);
    });
  });

429 430 431 432 433 434
  testWithoutContext('pub cache in environment is used', () async {
    final MockProcessManager processMock = MockProcessManager(69);
    final Pub pub = Pub(
      fileSystem: MockFileSystem(),
      logger: BufferLogger.test(),
      processManager: processMock,
435
      usage: TestUsage(),
436 437 438 439 440 441 442
      botDetector: const BotDetectorAlwaysNo(),
      platform: FakePlatform(
        environment: const <String, String>{
          'PUB_CACHE': 'custom/pub-cache/path',
        },
      ),
    );
443

444
    FakeAsync().run((FakeAsync time) {
445
      MockDirectory.findCache = true;
Josh Soref's avatar
Josh Soref committed
446
      expect(processMock.lastPubEnvironment, isNull);
447
      expect(processMock.lastPubCache, isNull);
448 449

      String error;
450
      pub.get(context: PubContext.flutterTests).then((void value) {
451 452 453 454 455
        error = 'test completed unexpectedly';
      }, onError: (dynamic thrownError) {
        error = 'test failed unexpectedly: $thrownError';
      });
      time.elapse(const Duration(milliseconds: 500));
456

457
      expect(processMock.lastPubCache, equals('custom/pub-cache/path'));
458 459
      expect(error, isNull);
    });
460
  });
461

462
  testWithoutContext('analytics sent on success', () async {
463
    final FileSystem fileSystem = MemoryFileSystem.test();
464
    final TestUsage usage = TestUsage();
465
    final Pub pub = Pub(
466
      fileSystem: fileSystem,
467 468 469 470 471 472 473 474 475 476
      logger: BufferLogger.test(),
      processManager: MockProcessManager(0),
      botDetector: const BotDetectorAlwaysNo(),
      usage: usage,
      platform: FakePlatform(
        environment: const <String, String>{
          'PUB_CACHE': 'custom/pub-cache/path',
        }
      ),
    );
477
    fileSystem.file('version').createSync();
478 479 480 481
    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('.dart_tool/package_config.json')
      ..createSync(recursive: true)
      ..writeAsStringSync('{"configVersion": 2,"packages": []}');
482

483 484 485 486
    await pub.get(
      context: PubContext.flutterTests,
      generateSyntheticPackage: true,
    );
487 488 489
    expect(usage.events, contains(
      const TestUsageEvent('pub-result', 'flutter-tests', label: 'success'),
    ));
490 491
  });

492 493
  testWithoutContext('package_config_subset file is generated from packages and not timestamp', () async {
    final FileSystem fileSystem = MemoryFileSystem.test();
494
    final TestUsage usage = TestUsage();
495 496 497 498 499 500 501 502 503 504 505 506
    final Pub pub = Pub(
      fileSystem: fileSystem,
      logger: BufferLogger.test(),
      processManager: MockProcessManager(0),
      botDetector: const BotDetectorAlwaysNo(),
      usage: usage,
      platform: FakePlatform(
        environment: const <String, String>{
          'PUB_CACHE': 'custom/pub-cache/path',
        }
      ),
    );
507
    fileSystem.file('version').createSync();
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('.dart_tool/package_config.json')
      ..createSync(recursive: true)
      ..writeAsStringSync('''
      {"configVersion": 2,"packages": [
        {
          "name": "flutter_tools",
          "rootUri": "../",
          "packageUri": "lib/",
          "languageVersion": "2.7"
        }
      ],"generated":"some-time"}
''');

    await pub.get(
      context: PubContext.flutterTests,
      generateSyntheticPackage: true,
    );

    expect(
      fileSystem.file('.dart_tool/package_config_subset').readAsStringSync(),
      'flutter_tools\n'
      '2.7\n'
      'file:///\n'
      'file:///lib/\n'
      '2\n',
    );
  });


538
  testWithoutContext('analytics sent on failure', () async {
539
    MockDirectory.findCache = true;
540
    final TestUsage usage = TestUsage();
541 542 543 544 545 546 547 548 549 550 551 552
    final Pub pub = Pub(
      usage: usage,
      fileSystem: MockFileSystem(),
      logger: BufferLogger.test(),
      processManager: MockProcessManager(1),
      botDetector: const BotDetectorAlwaysNo(),
      platform: FakePlatform(
        environment: const <String, String>{
          'PUB_CACHE': 'custom/pub-cache/path',
        },
      ),
    );
553
    try {
554
      await pub.get(context: PubContext.flutterTests);
555 556 557
    } on ToolExit {
      // Ignore.
    }
558

559 560 561
    expect(usage.events, contains(
      const TestUsageEvent('pub-result', 'flutter-tests', label: 'failure'),
    ));
562 563
  });

564
  testWithoutContext('analytics sent on failed version solve', () async {
565
    final TestUsage usage = TestUsage();
566
    final FileSystem fileSystem = MemoryFileSystem.test();
567
    final Pub pub = Pub(
568
      fileSystem: fileSystem,
569 570 571 572 573 574 575 576 577 578 579 580 581
      logger: BufferLogger.test(),
      processManager: MockProcessManager(
        1,
        stderr: 'version solving failed',
      ),
      platform: FakePlatform(
        environment: <String, String>{
          'PUB_CACHE': 'custom/pub-cache/path',
        },
      ),
      usage: usage,
      botDetector: const BotDetectorAlwaysNo(),
    );
582
    fileSystem.file('pubspec.yaml').writeAsStringSync('name: foo');
583

584
    try {
585
      await pub.get(context: PubContext.flutterTests);
586 587 588
    } on ToolExit {
      // Ignore.
    }
589

590 591 592
    expect(usage.events, contains(
      const TestUsageEvent('pub-result', 'flutter-tests', label: 'version-solving-failed'),
    ));
593
  });
594

595 596 597
  testWithoutContext('Pub error handling', () async {
    final BufferLogger logger = BufferLogger.test();
    final MemoryFileSystem fileSystem = MemoryFileSystem.test();
598 599 600
    final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
      FakeCommand(
        command: const <String>[
601
          'bin/cache/dart-sdk/bin/pub',
602 603 604 605 606
          '--verbosity=warning',
          'get',
          '--no-precompile',
        ],
        onRun: () {
607
          fileSystem.file('.dart_tool/package_config.json')
608
            .setLastModifiedSync(DateTime(2002));
609 610 611 612
        }
      ),
      const FakeCommand(
        command: <String>[
613
          'bin/cache/dart-sdk/bin/pub',
614 615 616 617 618 619 620
          '--verbosity=warning',
          'get',
          '--no-precompile',
        ],
      ),
      FakeCommand(
        command: const <String>[
621
          'bin/cache/dart-sdk/bin/pub',
622 623 624 625 626
          '--verbosity=warning',
          'get',
          '--no-precompile',
        ],
        onRun: () {
627
          fileSystem.file('pubspec.yaml')
628
            .setLastModifiedSync(DateTime(2002));
629 630
        }
      ),
631 632
      const FakeCommand(
        command: <String>[
633
          'bin/cache/dart-sdk/bin/pub',
634 635 636 637 638
          '--verbosity=warning',
          'get',
          '--no-precompile',
        ],
      ),
639
    ]);
640
    final Pub pub = Pub(
641
      usage: TestUsage(),
642 643 644 645
      fileSystem: fileSystem,
      logger: logger,
      processManager: processManager,
      platform: FakePlatform(
646 647 648
        operatingSystem: 'linux', // so that the command executed is consistent
        environment: <String, String>{},
      ),
649 650 651
      botDetector: const BotDetectorAlwaysNo()
    );

652
    fileSystem.file('version').createSync();
653 654 655 656 657 658 659
    // the good scenario: .packages is old, pub updates the file.
    fileSystem.file('.dart_tool/package_config.json')
      ..createSync(recursive: true)
      ..setLastModifiedSync(DateTime(2000));
    fileSystem.file('pubspec.yaml')
      ..createSync()
      ..setLastModifiedSync(DateTime(2001));
660
    await pub.get(context: PubContext.flutterTests); // pub sets date of .packages to 2002
661 662 663 664 665 666 667 668 669 670 671

    expect(logger.statusText, 'Running "flutter pub get" in /...\n');
    expect(logger.errorText, isEmpty);
    expect(fileSystem.file('pubspec.yaml').lastModifiedSync(), DateTime(2001)); // because nothing should touch it
    logger.clear();

    // bad scenario 1: pub doesn't update file; doesn't matter, because we do instead
    fileSystem.file('.dart_tool/package_config.json')
      .setLastModifiedSync(DateTime(2000));
    fileSystem.file('pubspec.yaml')
      .setLastModifiedSync(DateTime(2001));
672
    await pub.get(context: PubContext.flutterTests); // pub does nothing
673 674 675 676 677

    expect(logger.statusText, 'Running "flutter pub get" in /...\n');
    expect(logger.errorText, isEmpty);
    expect(fileSystem.file('pubspec.yaml').lastModifiedSync(), DateTime(2001)); // because nothing should touch it
    logger.clear();
678 679 680 681 682
  });
}

class BotDetectorAlwaysNo implements BotDetector {
  const BotDetectorAlwaysNo();
683

684
  @override
685
  Future<bool> get isRunningOnBot async => false;
686 687
}

688
typedef StartCallback = void Function(List<dynamic> command);
689 690

class MockProcessManager implements ProcessManager {
691
  MockProcessManager(this.fakeExitCode, {
692
    this.stdout = '',
693 694
    this.stderr = '',
  });
695 696

  final int fakeExitCode;
697
  final String stdout;
698
  final String stderr;
699

Josh Soref's avatar
Josh Soref committed
700
  String lastPubEnvironment;
701
  String lastPubCache;
702

703 704 705 706 707
  @override
  Future<Process> start(
    List<dynamic> command, {
    String workingDirectory,
    Map<String, String> environment,
708 709
    bool includeParentEnvironment = true,
    bool runInShell = false,
710
    ProcessStartMode mode = ProcessStartMode.normal,
711
  }) {
Josh Soref's avatar
Josh Soref committed
712
    lastPubEnvironment = environment['PUB_ENVIRONMENT'];
713
    lastPubCache = environment['PUB_CACHE'];
714 715
    return Future<Process>.value(mocks.createMockProcess(
      exitCode: fakeExitCode,
716
      stdout: stdout,
717 718
      stderr: stderr,
    ));
719 720 721 722 723 724
  }

  @override
  dynamic noSuchMethod(Invocation invocation) => null;
}

725
class MockFileSystem extends ForwardingFileSystem {
726
  MockFileSystem() : super(MemoryFileSystem.test());
727

728 729
  @override
  File file(dynamic path) {
730
    return MockFile();
731
  }
732 733 734

  @override
  Directory directory(dynamic path) {
735
    return MockDirectory(path as String);
736
  }
737 738 739 740
}

class MockFile implements File {
  @override
741
  Future<RandomAccessFile> open({ FileMode mode = FileMode.read }) async {
742
    return MockRandomAccessFile();
743 744 745 746 747 748
  }

  @override
  bool existsSync() => true;

  @override
749
  DateTime lastModifiedSync() => DateTime(0);
750 751 752 753 754

  @override
  dynamic noSuchMethod(Invocation invocation) => null;
}

755 756 757 758 759 760
class MockDirectory implements Directory {
  MockDirectory(this.path);

  @override
  final String path;

761 762
  static bool findCache = false;

763 764 765 766 767 768 769
  @override
  bool existsSync() => findCache && path.endsWith('.pub-cache');

  @override
  dynamic noSuchMethod(Invocation invocation) => null;
}

770
class MockRandomAccessFile extends Mock implements RandomAccessFile {}