hot_test.dart 25.3 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
import 'package:file/memory.dart';
8
import 'package:flutter_tools/src/application_package.dart';
9
import 'package:flutter_tools/src/artifacts.dart';
10
import 'package:flutter_tools/src/asset.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/platform.dart';
14
import 'package:flutter_tools/src/build_info.dart';
15
import 'package:flutter_tools/src/compile.dart';
16
import 'package:flutter_tools/src/devfs.dart';
17
import 'package:flutter_tools/src/device.dart';
18
import 'package:flutter_tools/src/reporting/reporting.dart';
19
import 'package:flutter_tools/src/resident_devtools_handler.dart';
20
import 'package:flutter_tools/src/resident_runner.dart';
21
import 'package:flutter_tools/src/run_hot.dart';
22
import 'package:flutter_tools/src/vmservice.dart';
23
import 'package:meta/meta.dart';
24
import 'package:package_config/package_config.dart';
25
import 'package:test/fake.dart';
26
import 'package:vm_service/vm_service.dart' as vm_service;
27

28 29
import '../src/common.dart';
import '../src/context.dart';
30
import '../src/fakes.dart';
31

32
void main() {
33 34
  group('validateReloadReport', () {
    testUsingContext('invalid', () async {
35
      expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{
36 37 38
        'type': 'ReloadReport',
        'success': false,
        'details': <String, dynamic>{},
39 40
      })), false);
      expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{
41 42 43 44 45 46
        'type': 'ReloadReport',
        'success': false,
        'details': <String, dynamic>{
          'notices': <Map<String, dynamic>>[
          ],
        },
47 48
      })), false);
      expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{
49 50 51 52 53 54 55
        'type': 'ReloadReport',
        'success': false,
        'details': <String, dynamic>{
          'notices': <String, dynamic>{
            'message': 'error',
          },
        },
56 57
      })), false);
      expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{
58 59 60 61 62
        'type': 'ReloadReport',
        'success': false,
        'details': <String, dynamic>{
          'notices': <Map<String, dynamic>>[],
        },
63 64
      })), false);
      expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{
65 66 67 68
        'type': 'ReloadReport',
        'success': false,
        'details': <String, dynamic>{
          'notices': <Map<String, dynamic>>[
69
            <String, dynamic>{'message': false},
70 71
          ],
        },
72 73
      })), false);
      expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{
74 75 76 77
        'type': 'ReloadReport',
        'success': false,
        'details': <String, dynamic>{
          'notices': <Map<String, dynamic>>[
78
            <String, dynamic>{'message': <String>['error']},
79 80
          ],
        },
81 82
      })), false);
      expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{
83 84 85 86
        'type': 'ReloadReport',
        'success': false,
        'details': <String, dynamic>{
          'notices': <Map<String, dynamic>>[
87 88
            <String, dynamic>{'message': 'error'},
            <String, dynamic>{'message': <String>['error']},
89 90
          ],
        },
91 92
      })), false);
      expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{
93 94 95 96
        'type': 'ReloadReport',
        'success': false,
        'details': <String, dynamic>{
          'notices': <Map<String, dynamic>>[
97
            <String, dynamic>{'message': 'error'},
98 99
          ],
        },
100 101
      })), false);
      expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{
102 103
        'type': 'ReloadReport',
        'success': true,
104 105 106 107 108 109 110 111 112
      })), true);
    });

    testWithoutContext('ReasonForCancelling toString has a hint for specific errors', () {
      final ReasonForCancelling reasonForCancelling = ReasonForCancelling(
        message: 'Const class cannot remove fields',
      );

      expect(reasonForCancelling.toString(), contains('Try performing a hot restart instead.'));
113 114
    });
  });
115 116

  group('hotRestart', () {
117
    final FakeResidentCompiler residentCompiler = FakeResidentCompiler();
118
    FileSystem fileSystem;
119
    TestUsage testUsage;
120 121

    setUp(() {
122
      fileSystem = MemoryFileSystem.test();
123
      testUsage = TestUsage();
124 125
    });

126 127 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
    group('fails to setup', () {
      TestHotRunnerConfig failingTestingConfig;
      setUp(() {
        failingTestingConfig = TestHotRunnerConfig(
          successfulHotRestartSetup: false,
          successfulHotReloadSetup: false,
        );
      });

      testUsingContext('setupHotRestart function fails', () async {
        fileSystem.file('.packages')
          ..createSync(recursive: true)
          ..writeAsStringSync('\n');
        final FakeDevice device = FakeDevice();
        final List<FlutterDevice> devices = <FlutterDevice>[
          FlutterDevice(device, generator: residentCompiler, buildInfo: BuildInfo.debug)..devFS = FakeDevFs(),
        ];
        final OperationResult result = await HotRunner(
          devices,
          debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
          target: 'main.dart',
          devtoolsHandler: createNoOpHandler,
        ).restart(fullRestart: true);
        expect(result.isOk, false);
        expect(result.message, 'setupHotRestart failed');
        expect(failingTestingConfig.updateDevFSCompleteCalled, false);
      }, overrides: <Type, Generator>{
        HotRunnerConfig: () => failingTestingConfig,
        Artifacts: () => Artifacts.test(),
        FileSystem: () => fileSystem,
156
        Platform: () => FakePlatform(),
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
        ProcessManager: () => FakeProcessManager.any(),
      });

      testUsingContext('setupHotReload function fails', () async {
        fileSystem.file('.packages')
          ..createSync(recursive: true)
          ..writeAsStringSync('\n');
        final FakeDevice device = FakeDevice();
        final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device);
        final List<FlutterDevice> devices = <FlutterDevice>[
          fakeFlutterDevice,
        ];
        final OperationResult result = await HotRunner(
          devices,
          debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
          target: 'main.dart',
          devtoolsHandler: createNoOpHandler,
          reassembleHelper: (
            List<FlutterDevice> flutterDevices,
            Map<FlutterDevice, List<FlutterView>> viewCache,
            void Function(String message) onSlow,
            String reloadMessage,
            String fastReassembleClassName,
          ) async => ReassembleResult(
              <FlutterView, FlutterVmService>{null: null},
              false,
              true,
            ),
185
        ).restart();
186 187 188 189 190 191 192
        expect(result.isOk, false);
        expect(result.message, 'setupHotReload failed');
        expect(failingTestingConfig.updateDevFSCompleteCalled, false);
      }, overrides: <Type, Generator>{
        HotRunnerConfig: () => failingTestingConfig,
        Artifacts: () => Artifacts.test(),
        FileSystem: () => fileSystem,
193
        Platform: () => FakePlatform(),
194 195
        ProcessManager: () => FakeProcessManager.any(),
      });
196
    });
197

198 199 200 201
    group('shutdown hook tests', () {
      TestHotRunnerConfig shutdownTestingConfig;

      setUp(() {
202
        shutdownTestingConfig = TestHotRunnerConfig();
203 204 205
      });

      testUsingContext('shutdown hook called after signal', () async {
206
        fileSystem.file('.packages')
207 208
          ..createSync(recursive: true)
          ..writeAsStringSync('\n');
209
        final FakeDevice device = FakeDevice();
210
        final List<FlutterDevice> devices = <FlutterDevice>[
211
          FlutterDevice(device, generator: residentCompiler, buildInfo: BuildInfo.debug),
212
        ];
213 214
        await HotRunner(
          devices,
215 216
          debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
          target: 'main.dart',
217
        ).cleanupAfterSignal();
218
        expect(shutdownTestingConfig.shutdownHookCalled, true);
219
      }, overrides: <Type, Generator>{
220
        HotRunnerConfig: () => shutdownTestingConfig,
221 222
        Artifacts: () => Artifacts.test(),
        FileSystem: () => fileSystem,
223
        Platform: () => FakePlatform(),
224
        ProcessManager: () => FakeProcessManager.any(),
225 226 227
      });

      testUsingContext('shutdown hook called after app stop', () async {
228
        fileSystem.file('.packages')
229 230
          ..createSync(recursive: true)
          ..writeAsStringSync('\n');
231
        final FakeDevice device = FakeDevice();
232
        final List<FlutterDevice> devices = <FlutterDevice>[
233
          FlutterDevice(device, generator: residentCompiler, buildInfo: BuildInfo.debug),
234
        ];
235 236
        await HotRunner(
          devices,
237 238
          debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
          target: 'main.dart',
239
        ).preExit();
240
        expect(shutdownTestingConfig.shutdownHookCalled, true);
241
      }, overrides: <Type, Generator>{
242
        HotRunnerConfig: () => shutdownTestingConfig,
243 244
        Artifacts: () => Artifacts.test(),
        FileSystem: () => fileSystem,
245
        Platform: () => FakePlatform(),
246
        ProcessManager: () => FakeProcessManager.any(),
247 248
      });
    });
249

250 251 252 253 254 255 256 257 258 259 260 261 262
    group('successful hot restart', () {
      TestHotRunnerConfig testingConfig;
      setUp(() {
        testingConfig = TestHotRunnerConfig(
          successfulHotRestartSetup: true,
        );
      });
      testUsingContext('correctly tracks time spent for analytics for hot restart', () async {
        final FakeDevice device = FakeDevice();
        final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device);
        final List<FlutterDevice> devices = <FlutterDevice>[
          fakeFlutterDevice,
        ];
263

264 265 266 267 268 269 270 271
        fakeFlutterDevice.updateDevFSReportCallback = () async => UpdateFSReport(
          success: true,
          invalidatedSourcesCount: 2,
          syncedBytes: 4,
          scannedSourcesCount: 8,
          compileDuration: const Duration(seconds: 16),
          transferDuration: const Duration(seconds: 32),
        );
272

273 274 275 276 277 278
        final FakeStopwatchFactory fakeStopwatchFactory = FakeStopwatchFactory(
          stopwatches: <String, Stopwatch>{
            'fullRestartHelper': FakeStopwatch()..elapsed = const Duration(seconds: 64),
            'updateDevFS': FakeStopwatch()..elapsed = const Duration(seconds: 128),
          },
        );
279

280
        (fakeFlutterDevice.devFS as FakeDevFs).baseUri = Uri.parse('file:///base_uri');
281

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
        final OperationResult result = await HotRunner(
          devices,
          debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
          target: 'main.dart',
          devtoolsHandler: createNoOpHandler,
          stopwatchFactory: fakeStopwatchFactory,
        ).restart(fullRestart: true);

        expect(result.isOk, true);
        expect(testUsage.events, <TestUsageEvent>[
          const TestUsageEvent('hot', 'restart', parameters: CustomDimensions(
            hotEventTargetPlatform: 'flutter-tester',
            hotEventSdkName: 'Tester',
            hotEventEmulator: false,
            hotEventFullRestart: true,
297
            fastReassemble: false,
298 299 300 301 302 303 304 305 306 307 308 309 310 311
            hotEventOverallTimeInMs: 64000,
            hotEventSyncedBytes: 4,
            hotEventInvalidatedSourcesCount: 2,
            hotEventTransferTimeInMs: 32000,
            hotEventCompileTimeInMs: 16000,
            hotEventFindInvalidatedTimeInMs: 128000,
            hotEventScannedSourcesCount: 8,
          )),
        ]);
        expect(testingConfig.updateDevFSCompleteCalled, true);
      }, overrides: <Type, Generator>{
        HotRunnerConfig: () => testingConfig,
        Artifacts: () => Artifacts.test(),
        FileSystem: () => fileSystem,
312
        Platform: () => FakePlatform(),
313 314 315
        ProcessManager: () => FakeProcessManager.any(),
        Usage: () => testUsage,
      });
316 317
    });

318 319 320 321 322 323 324 325 326 327 328 329 330
    group('successful hot reload', () {
      TestHotRunnerConfig testingConfig;
      setUp(() {
        testingConfig = TestHotRunnerConfig(
          successfulHotReloadSetup: true,
        );
      });
      testUsingContext('correctly tracks time spent for analytics for hot reload', () async {
        final FakeDevice device = FakeDevice();
        final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device);
        final List<FlutterDevice> devices = <FlutterDevice>[
          fakeFlutterDevice,
        ];
331

332 333 334 335 336 337 338 339
        fakeFlutterDevice.updateDevFSReportCallback = () async => UpdateFSReport(
          success: true,
          invalidatedSourcesCount: 6,
          syncedBytes: 8,
          scannedSourcesCount: 16,
          compileDuration: const Duration(seconds: 16),
          transferDuration: const Duration(seconds: 32),
        );
340

341 342 343 344 345 346 347 348
        final FakeStopwatchFactory fakeStopwatchFactory = FakeStopwatchFactory(
          stopwatches: <String, Stopwatch>{
            'updateDevFS': FakeStopwatch()..elapsed = const Duration(seconds: 64),
            'reloadSources:reload': FakeStopwatch()..elapsed = const Duration(seconds: 128),
            'reloadSources:reassemble': FakeStopwatch()..elapsed = const Duration(seconds: 256),
            'reloadSources:vm': FakeStopwatch()..elapsed = const Duration(seconds: 512),
          },
        );
349

350
        (fakeFlutterDevice.devFS as FakeDevFs).baseUri = Uri.parse('file:///base_uri');
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
        final OperationResult result = await HotRunner(
          devices,
          debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
          target: 'main.dart',
          devtoolsHandler: createNoOpHandler,
          stopwatchFactory: fakeStopwatchFactory,
          reloadSourcesHelper: (
            HotRunner hotRunner,
            List<FlutterDevice> flutterDevices,
            bool pause,
            Map<String, dynamic> firstReloadDetails,
            String targetPlatform,
            String sdkName,
            bool emulator,
            String reason,
          ) async {
            firstReloadDetails['finalLibraryCount'] = 2;
            firstReloadDetails['receivedLibraryCount'] = 3;
            firstReloadDetails['receivedClassesCount'] = 4;
            firstReloadDetails['receivedProceduresCount'] = 5;
            return OperationResult.ok;
          },
          reassembleHelper: (
            List<FlutterDevice> flutterDevices,
            Map<FlutterDevice, List<FlutterView>> viewCache,
            void Function(String message) onSlow,
            String reloadMessage,
            String fastReassembleClassName,
          ) async => ReassembleResult(
              <FlutterView, FlutterVmService>{null: null},
              false,
              true,
            ),
385
        ).restart();
386 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 413 414

        expect(result.isOk, true);
        expect(testUsage.events, <TestUsageEvent>[
          const TestUsageEvent('hot', 'reload', parameters: CustomDimensions(
            hotEventFinalLibraryCount: 2,
            hotEventSyncedLibraryCount: 3,
            hotEventSyncedClassesCount: 4,
            hotEventSyncedProceduresCount: 5,
            hotEventSyncedBytes: 8,
            hotEventInvalidatedSourcesCount: 6,
            hotEventTransferTimeInMs: 32000,
            hotEventOverallTimeInMs: 128000,
            hotEventTargetPlatform: 'flutter-tester',
            hotEventSdkName: 'Tester',
            hotEventEmulator: false,
            hotEventFullRestart: false,
            fastReassemble: false,
            hotEventCompileTimeInMs: 16000,
            hotEventFindInvalidatedTimeInMs: 64000,
            hotEventScannedSourcesCount: 16,
            hotEventReassembleTimeInMs: 256000,
            hotEventReloadVMTimeInMs: 512000,
          )),
        ]);
        expect(testingConfig.updateDevFSCompleteCalled, true);
      }, overrides: <Type, Generator>{
        HotRunnerConfig: () => testingConfig,
        Artifacts: () => Artifacts.test(),
        FileSystem: () => fileSystem,
415
        Platform: () => FakePlatform(),
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
        ProcessManager: () => FakeProcessManager.any(),
        Usage: () => testUsage,
      });
    });

    group('hot restart that failed to sync dev fs', () {
      TestHotRunnerConfig testingConfig;
      setUp(() {
        testingConfig = TestHotRunnerConfig(
          successfulHotRestartSetup: true,
        );
      });
      testUsingContext('still calls the devfs complete callback', () async {
        final FakeDevice device = FakeDevice();
        final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device);
        final List<FlutterDevice> devices = <FlutterDevice>[
          fakeFlutterDevice,
        ];
434
        fakeFlutterDevice.updateDevFSReportCallback = () async => throw Exception('updateDevFS failed');
435 436 437 438 439 440 441 442

        final HotRunner runner = HotRunner(
          devices,
          debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
          target: 'main.dart',
          devtoolsHandler: createNoOpHandler,
        );

443
        await expectLater(runner.restart(fullRestart: true), throwsA(isA<Exception>().having((Exception e) => e.toString(), 'message', 'Exception: updateDevFS failed')));
444 445 446 447 448
        expect(testingConfig.updateDevFSCompleteCalled, true);
      }, overrides: <Type, Generator>{
        HotRunnerConfig: () => testingConfig,
        Artifacts: () => Artifacts.test(),
        FileSystem: () => fileSystem,
449
        Platform: () => FakePlatform(),
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
        ProcessManager: () => FakeProcessManager.any(),
        Usage: () => testUsage,
      });
    });

    group('hot reload that failed to sync dev fs', () {
      TestHotRunnerConfig testingConfig;
      setUp(() {
        testingConfig = TestHotRunnerConfig(
          successfulHotReloadSetup: true,
        );
      });
      testUsingContext('still calls the devfs complete callback', () async {
        final FakeDevice device = FakeDevice();
        final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device);
        final List<FlutterDevice> devices = <FlutterDevice>[
          fakeFlutterDevice,
        ];
468
        fakeFlutterDevice.updateDevFSReportCallback = () async => throw Exception('updateDevFS failed');
469 470 471 472 473 474 475 476

        final HotRunner runner = HotRunner(
          devices,
          debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
          target: 'main.dart',
          devtoolsHandler: createNoOpHandler,
        );

477
        await expectLater(runner.restart(), throwsA(isA<Exception>().having((Exception e) => e.toString(), 'message', 'Exception: updateDevFS failed')));
478 479 480 481 482
        expect(testingConfig.updateDevFSCompleteCalled, true);
      }, overrides: <Type, Generator>{
        HotRunnerConfig: () => testingConfig,
        Artifacts: () => Artifacts.test(),
        FileSystem: () => fileSystem,
483
        Platform: () => FakePlatform(),
484 485 486
        ProcessManager: () => FakeProcessManager.any(),
        Usage: () => testUsage,
      });
487
    });
488
  });
489 490

  group('hot attach', () {
491
    FileSystem fileSystem;
492 493

    setUp(() {
494
      fileSystem = MemoryFileSystem.test();
495 496
    });

nt4f04uNd's avatar
nt4f04uNd committed
497
    testUsingContext('Exits with code 2 when HttpException is thrown '
498
      'during VM service connection', () async {
499
      fileSystem.file('.packages')
500 501 502
        ..createSync(recursive: true)
        ..writeAsStringSync('\n');

503
      final FakeResidentCompiler residentCompiler = FakeResidentCompiler();
504
      final FakeDevice device = FakeDevice();
505 506
      final List<FlutterDevice> devices = <FlutterDevice>[
        TestFlutterDevice(
507
          device: device,
508 509
          generator: residentCompiler,
          exception: const HttpException('Connection closed before full header was received, '
510
              'uri = http://127.0.0.1:63394/5ZmLv8A59xY=/ws'),
511 512 513 514 515
        ),
      ];

      final int exitCode = await HotRunner(devices,
        debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
516
        target: 'main.dart',
517
      ).attach(needsFullRestart: false);
518 519
      expect(exitCode, 2);
    }, overrides: <Type, Generator>{
520
      HotRunnerConfig: () => TestHotRunnerConfig(),
521 522
      Artifacts: () => Artifacts.test(),
      FileSystem: () => fileSystem,
523
      Platform: () => FakePlatform(),
524
      ProcessManager: () => FakeProcessManager.any(),
525 526
    });
  });
527 528 529

  group('hot cleanupAtFinish()', () {
    testUsingContext('disposes each device', () async {
530 531 532 533
      final FakeDevice device1 = FakeDevice();
      final FakeDevice device2 = FakeDevice();
      final FakeFlutterDevice flutterDevice1 = FakeFlutterDevice(device1);
      final FakeFlutterDevice flutterDevice2 = FakeFlutterDevice(device2);
534 535

      final List<FlutterDevice> devices = <FlutterDevice>[
536 537
        flutterDevice1,
        flutterDevice2,
538 539 540 541
      ];

      await HotRunner(devices,
        debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
542
        target: 'main.dart',
543 544
      ).cleanupAtFinish();

545 546 547 548 549
      expect(device1.disposed, true);
      expect(device2.disposed, true);

      expect(flutterDevice1.stoppedEchoingDeviceLog, true);
      expect(flutterDevice2.stoppedEchoingDeviceLog, true);
550 551
    });
  });
552 553
}

554 555 556
class FakeDevFs extends Fake implements DevFS {
  @override
  Future<void> destroy() async { }
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571

  @override
  List<Uri> sources = <Uri>[];

  @override
  DateTime lastCompiled;

  @override
  PackageConfig lastPackageConfig;

  @override
  Set<String> assetPathsToEvict = <String>{};

  @override
  Uri baseUri;
572 573
}

574 575 576
// Unfortunately Device, despite not being immutable, has an `operator ==`.
// Until we fix that, we have to also ignore related lints here.
// ignore: avoid_implementing_value_types
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
class FakeDevice extends Fake implements Device {
  bool disposed = false;

  @override
  bool isSupported() => true;

  @override
  bool supportsHotReload = true;

  @override
  bool supportsHotRestart = true;

  @override
  bool supportsFlutterExit = true;

  @override
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.tester;
594

595 596 597 598 599 600
  @override
  Future<String> get sdkNameAndVersion async => 'Tester';

  @override
  Future<bool> get isLocalEmulator async => false;

601 602 603
  @override
  String get name => 'Fake Device';

604 605 606 607 608 609 610 611 612 613 614
  @override
  Future<bool> stopApp(
    covariant ApplicationPackage app, {
    String userIdentifier,
  }) async {
    return true;
  }

  @override
  Future<void> dispose() async {
    disposed = true;
615 616 617
  }
}

618 619 620 621
class FakeFlutterDevice extends Fake implements FlutterDevice {
  FakeFlutterDevice(this.device);

  bool stoppedEchoingDeviceLog = false;
622
  Future<UpdateFSReport> Function() updateDevFSReportCallback;
623 624 625 626 627 628 629 630 631 632 633

  @override
  final FakeDevice device;

  @override
  Future<void> stopEchoingDeviceLog() async {
    stoppedEchoingDeviceLog = true;
  }

  @override
  DevFS devFS = FakeDevFs();
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654

  @override
  FlutterVmService get vmService => FakeFlutterVmService();

  @override
  ResidentCompiler generator;

  @override
  Future<UpdateFSReport> updateDevFS({
    Uri mainUri,
    String target,
    AssetBundle bundle,
    DateTime firstBuildTime,
    bool bundleFirstUpload = false,
    bool bundleDirty = false,
    bool fullRestart = false,
    String projectRootPath,
    String pathToReload,
    @required String dillOutputPath,
    @required List<Uri> invalidatedFiles,
    @required PackageConfig packageConfig,
655
  }) => updateDevFSReportCallback();
656
}
657

658 659 660 661
class TestFlutterDevice extends FlutterDevice {
  TestFlutterDevice({
    @required Device device,
    @required this.exception,
662
    @required ResidentCompiler generator,
663
  })  : assert(exception != null),
664
        super(device, buildInfo: BuildInfo.debug, generator: generator);
665 666 667 668 669 670 671 672 673

  /// The exception to throw when the connect method is called.
  final Exception exception;

  @override
  Future<void> connect({
    ReloadSources reloadSources,
    Restart restart,
    CompileExpression compileExpression,
674
    GetSkSLMethod getSkSLMethod,
675
    PrintStructuredErrorLogMethod printStructuredErrorLogMethod,
676
    bool disableServiceAuthCodes = false,
677
    bool enableDds = true,
678
    bool cacheStartupProfile = false,
679
    bool ipv6 = false,
680 681
    int hostVmServicePort,
    int ddsPort,
682
    bool allowExistingDdsInstance = false,
683 684 685 686 687
  }) async {
    throw exception;
  }
}

688
class TestHotRunnerConfig extends HotRunnerConfig {
689 690 691
  TestHotRunnerConfig({this.successfulHotRestartSetup, this.successfulHotReloadSetup});
  bool successfulHotRestartSetup;
  bool successfulHotReloadSetup;
692
  bool shutdownHookCalled = false;
693
  bool updateDevFSCompleteCalled = false;
694

695 696
  @override
  Future<bool> setupHotRestart() async {
697 698 699 700 701 702 703 704 705 706 707 708 709
    assert(successfulHotRestartSetup != null, 'setupHotRestart is not expected to be called in this test.');
    return successfulHotRestartSetup;
  }

  @override
  Future<bool> setupHotReload() async {
    assert(successfulHotReloadSetup != null, 'setupHotReload is not expected to be called in this test.');
    return successfulHotReloadSetup;
  }

  @override
  void updateDevFSComplete() {
    updateDevFSCompleteCalled = true;
710
  }
711 712 713 714 715

  @override
  Future<void> runPreShutdownOperations() async {
    shutdownHookCalled = true;
  }
716
}
717 718 719 720 721

class FakeResidentCompiler extends Fake implements ResidentCompiler {
  @override
  void accept() {}
}
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741

class FakeFlutterVmService extends Fake implements FlutterVmService {
  @override
  vm_service.VmService get service => FakeVmService();

  @override
  Future<List<FlutterView>> getFlutterViews({bool returnEarly = false, Duration delay = const Duration(milliseconds: 50)}) async {
    return <FlutterView>[];
  }
}

class FakeVmService extends Fake implements vm_service.VmService {
  @override
  Future<vm_service.VM> getVM() async => FakeVm();
}

class FakeVm extends Fake implements vm_service.VM {
  @override
  List<vm_service.IsolateRef> get isolates => <vm_service.IsolateRef>[];
}