hot_test.dart 26.1 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

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/build_system/targets/shader_compiler.dart';
16
import 'package:flutter_tools/src/compile.dart';
17
import 'package:flutter_tools/src/devfs.dart';
18
import 'package:flutter_tools/src/device.dart';
19
import 'package:flutter_tools/src/project.dart';
20
import 'package:flutter_tools/src/reporting/reporting.dart';
21
import 'package:flutter_tools/src/resident_devtools_handler.dart';
22
import 'package:flutter_tools/src/resident_runner.dart';
23
import 'package:flutter_tools/src/run_hot.dart';
24
import 'package:flutter_tools/src/vmservice.dart';
25
import 'package:package_config/package_config.dart';
26
import 'package:test/fake.dart';
27
import 'package:vm_service/vm_service.dart' as vm_service;
28

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

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

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

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

127
    group('fails to setup', () {
128
      late TestHotRunnerConfig failingTestingConfig;
129 130 131 132 133 134 135 136 137 138 139 140 141
      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>[
142 143
          FlutterDevice(device, generator: residentCompiler, buildInfo: BuildInfo.debug, developmentShaderCompiler: const FakeShaderCompiler())
            ..devFS = FakeDevFs(),
144 145 146 147 148 149 150 151 152 153 154 155 156 157
        ];
        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,
158
        Platform: () => FakePlatform(),
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
        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: (
177 178 179
            List<FlutterDevice?> flutterDevices,
            Map<FlutterDevice?, List<FlutterView>> viewCache,
            void Function(String message)? onSlow,
180
            String reloadMessage,
181
            String? fastReassembleClassName,
182
          ) async => ReassembleResult(
183
              <FlutterView?, FlutterVmService?>{null: null},
184 185 186
              false,
              true,
            ),
187
        ).restart();
188 189 190 191 192 193 194
        expect(result.isOk, false);
        expect(result.message, 'setupHotReload failed');
        expect(failingTestingConfig.updateDevFSCompleteCalled, false);
      }, overrides: <Type, Generator>{
        HotRunnerConfig: () => failingTestingConfig,
        Artifacts: () => Artifacts.test(),
        FileSystem: () => fileSystem,
195
        Platform: () => FakePlatform(),
196 197
        ProcessManager: () => FakeProcessManager.any(),
      });
198
    });
199

200
    group('shutdown hook tests', () {
201
      late TestHotRunnerConfig shutdownTestingConfig;
202 203

      setUp(() {
204
        shutdownTestingConfig = TestHotRunnerConfig();
205 206 207
      });

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

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

252
    group('successful hot restart', () {
253
      late TestHotRunnerConfig testingConfig;
254 255 256 257 258 259 260 261 262 263 264
      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,
        ];
265

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

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

282
        (fakeFlutterDevice.devFS! as FakeDevFs).baseUri = Uri.parse('file:///base_uri');
283

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        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,
299
            fastReassemble: false,
300 301 302 303 304 305 306 307 308 309 310 311 312 313
            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,
314
        Platform: () => FakePlatform(),
315 316 317
        ProcessManager: () => FakeProcessManager.any(),
        Usage: () => testUsage,
      });
318 319
    });

320
    group('successful hot reload', () {
321
      late TestHotRunnerConfig testingConfig;
322 323 324 325 326 327 328 329 330 331 332
      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,
        ];
333

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

343 344 345 346 347 348 349 350
        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),
          },
        );
351

352
        (fakeFlutterDevice.devFS! as FakeDevFs).baseUri = Uri.parse('file:///base_uri');
353

354 355 356 357 358 359 360 361
        final OperationResult result = await HotRunner(
          devices,
          debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
          target: 'main.dart',
          devtoolsHandler: createNoOpHandler,
          stopwatchFactory: fakeStopwatchFactory,
          reloadSourcesHelper: (
            HotRunner hotRunner,
362 363
            List<FlutterDevice?> flutterDevices,
            bool? pause,
364
            Map<String, dynamic> firstReloadDetails,
365 366 367 368
            String? targetPlatform,
            String? sdkName,
            bool? emulator,
            String? reason,
369 370 371 372 373 374 375 376
          ) async {
            firstReloadDetails['finalLibraryCount'] = 2;
            firstReloadDetails['receivedLibraryCount'] = 3;
            firstReloadDetails['receivedClassesCount'] = 4;
            firstReloadDetails['receivedProceduresCount'] = 5;
            return OperationResult.ok;
          },
          reassembleHelper: (
377 378 379
            List<FlutterDevice?> flutterDevices,
            Map<FlutterDevice?, List<FlutterView>> viewCache,
            void Function(String message)? onSlow,
380
            String reloadMessage,
381
            String? fastReassembleClassName,
382
          ) async => ReassembleResult(
383
              <FlutterView?, FlutterVmService?>{null: null},
384 385 386
              false,
              true,
            ),
387
        ).restart();
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 415 416

        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,
417
        Platform: () => FakePlatform(),
418 419 420 421 422 423
        ProcessManager: () => FakeProcessManager.any(),
        Usage: () => testUsage,
      });
    });

    group('hot restart that failed to sync dev fs', () {
424
      late TestHotRunnerConfig testingConfig;
425 426 427 428 429 430 431 432 433 434 435
      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,
        ];
436
        fakeFlutterDevice.updateDevFSReportCallback = () async => throw Exception('updateDevFS failed');
437 438 439 440 441 442 443 444

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

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

    group('hot reload that failed to sync dev fs', () {
458
      late TestHotRunnerConfig testingConfig;
459 460 461 462 463 464 465 466 467 468 469
      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,
        ];
470
        fakeFlutterDevice.updateDevFSReportCallback = () async => throw Exception('updateDevFS failed');
471 472 473 474 475 476 477 478

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

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

  group('hot attach', () {
493
    late FileSystem fileSystem;
494 495

    setUp(() {
496
      fileSystem = MemoryFileSystem.test();
497 498
    });

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

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

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

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

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

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

547 548 549 550 551
      expect(device1.disposed, true);
      expect(device2.disposed, true);

      expect(flutterDevice1.stoppedEchoingDeviceLog, true);
      expect(flutterDevice2.stoppedEchoingDeviceLog, true);
552 553
    });
  });
554 555
}

556 557 558
class FakeDevFs extends Fake implements DevFS {
  @override
  Future<void> destroy() async { }
559 560 561 562 563

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

  @override
564
  DateTime? lastCompiled;
565 566

  @override
567
  PackageConfig? lastPackageConfig;
568 569 570 571

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

572 573 574
  @override
  Set<String> shaderPathsToEvict= <String>{};

575 576 577
  @override
  Set<String> scenePathsToEvict= <String>{};

578
  @override
579
  Uri? baseUri;
580 581
}

582 583 584
// 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
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
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;
602

603 604 605 606 607 608
  @override
  Future<String> get sdkNameAndVersion async => 'Tester';

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

609 610 611
  @override
  String get name => 'Fake Device';

612 613
  @override
  Future<bool> stopApp(
614
    ApplicationPackage? app, {
615
    String? userIdentifier,
616 617 618 619 620 621 622
  }) async {
    return true;
  }

  @override
  Future<void> dispose() async {
    disposed = true;
623 624 625
  }
}

626 627 628 629
class FakeFlutterDevice extends Fake implements FlutterDevice {
  FakeFlutterDevice(this.device);

  bool stoppedEchoingDeviceLog = false;
630
  late Future<UpdateFSReport> Function() updateDevFSReportCallback;
631 632 633 634 635 636 637 638 639 640

  @override
  final FakeDevice device;

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

  @override
641
  DevFS? devFS = FakeDevFs();
642 643 644 645 646

  @override
  FlutterVmService get vmService => FakeFlutterVmService();

  @override
647
  ResidentCompiler? generator;
648 649 650

  @override
  Future<UpdateFSReport> updateDevFS({
651 652 653 654
    Uri? mainUri,
    String? target,
    AssetBundle? bundle,
    DateTime? firstBuildTime,
655 656 657
    bool bundleFirstUpload = false,
    bool bundleDirty = false,
    bool fullRestart = false,
658 659 660 661 662
    String? projectRootPath,
    String? pathToReload,
    required String dillOutputPath,
    required List<Uri> invalidatedFiles,
    required PackageConfig packageConfig,
663
  }) => updateDevFSReportCallback();
664
}
665

666 667
class TestFlutterDevice extends FlutterDevice {
  TestFlutterDevice({
668 669 670
    required Device device,
    required this.exception,
    required ResidentCompiler generator,
671
  })  : super(device, buildInfo: BuildInfo.debug, generator: generator, developmentShaderCompiler: const FakeShaderCompiler());
672 673 674 675 676 677

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

  @override
  Future<void> connect({
678 679 680 681
    ReloadSources? reloadSources,
    Restart? restart,
    CompileExpression? compileExpression,
    GetSkSLMethod? getSkSLMethod,
682
    FlutterProject? flutterProject,
683
    PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
684
    bool disableServiceAuthCodes = false,
685
    bool enableDds = true,
686
    bool cacheStartupProfile = false,
687 688 689
    bool? ipv6 = false,
    int? hostVmServicePort,
    int? ddsPort,
690
    bool allowExistingDdsInstance = false,
691 692 693 694 695
  }) async {
    throw exception;
  }
}

696
class TestHotRunnerConfig extends HotRunnerConfig {
697
  TestHotRunnerConfig({this.successfulHotRestartSetup, this.successfulHotReloadSetup});
698 699
  bool? successfulHotRestartSetup;
  bool? successfulHotReloadSetup;
700
  bool shutdownHookCalled = false;
701
  bool updateDevFSCompleteCalled = false;
702

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

  @override
710
  Future<bool?> setupHotReload() async {
711 712 713 714 715 716 717
    assert(successfulHotReloadSetup != null, 'setupHotReload is not expected to be called in this test.');
    return successfulHotReloadSetup;
  }

  @override
  void updateDevFSComplete() {
    updateDevFSCompleteCalled = true;
718
  }
719 720 721 722 723

  @override
  Future<void> runPreShutdownOperations() async {
    shutdownHookCalled = true;
  }
724
}
725 726 727 728 729

class FakeResidentCompiler extends Fake implements ResidentCompiler {
  @override
  void accept() {}
}
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

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>[];
}
750 751 752 753 754

class FakeShaderCompiler implements DevelopmentShaderCompiler {
  const FakeShaderCompiler();

  @override
755 756 757 758
  void configureCompiler(
    TargetPlatform? platform, {
    required ImpellerStatus impellerStatus,
  }) { }
759 760 761 762 763 764

  @override
  Future<DevFSContent> recompileShader(DevFSContent inputShader) {
    throw UnimplementedError();
  }
}