resident_runner_test.dart 91 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
6

7
import 'package:dds/dds.dart' as dds;
8
import 'package:file/memory.dart';
9
import 'package:file_testing/file_testing.dart';
10
import 'package:flutter_tools/src/application_package.dart';
11
import 'package:flutter_tools/src/artifacts.dart';
12
import 'package:flutter_tools/src/asset.dart';
13
import 'package:flutter_tools/src/base/command_help.dart';
14
import 'package:flutter_tools/src/base/common.dart';
15
import 'package:flutter_tools/src/base/dds.dart';
16
import 'package:flutter_tools/src/base/file_system.dart';
17
import 'package:flutter_tools/src/base/io.dart' as io;
18 19
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
20
import 'package:flutter_tools/src/build_info.dart';
21
import 'package:flutter_tools/src/build_system/targets/shader_compiler.dart';
22
import 'package:flutter_tools/src/compile.dart';
23
import 'package:flutter_tools/src/convert.dart';
24
import 'package:flutter_tools/src/devfs.dart';
25
import 'package:flutter_tools/src/device.dart';
26 27
import 'package:flutter_tools/src/device_port_forwarder.dart';
import 'package:flutter_tools/src/features.dart';
28
import 'package:flutter_tools/src/globals.dart' as globals;
29
import 'package:flutter_tools/src/reporting/reporting.dart';
30
import 'package:flutter_tools/src/resident_devtools_handler.dart';
31
import 'package:flutter_tools/src/resident_runner.dart';
32
import 'package:flutter_tools/src/run_cold.dart';
33
import 'package:flutter_tools/src/run_hot.dart';
34
import 'package:flutter_tools/src/version.dart';
35
import 'package:flutter_tools/src/vmservice.dart';
36
import 'package:package_config/package_config.dart';
37
import 'package:test/fake.dart';
38
import 'package:vm_service/vm_service.dart' as vm_service;
39

40
import '../src/common.dart';
41
import '../src/context.dart';
42
import '../src/fake_vm_services.dart';
43
import '../src/fakes.dart';
44
import '../src/testbed.dart';
45

46 47 48 49 50 51 52
final vm_service.Isolate fakeUnpausedIsolate = vm_service.Isolate(
  id: '1',
  pauseEvent: vm_service.Event(
    kind: vm_service.EventKind.kResume,
    timestamp: 0
  ),
  breakpoints: <vm_service.Breakpoint>[],
53
  extensionRPCs: <String>[],
54 55 56 57 58 59 60
  libraries: <vm_service.LibraryRef>[
    vm_service.LibraryRef(
      id: '1',
      uri: 'file:///hello_world/main.dart',
      name: '',
    ),
  ],
61 62 63 64 65 66
  livePorts: 0,
  name: 'test',
  number: '1',
  pauseOnExit: false,
  runnable: true,
  startTime: 0,
67
  isSystemIsolate: false,
68
  isolateFlags: <vm_service.IsolateFlag>[],
69 70 71 72 73 74 75 76
);

final vm_service.Isolate fakePausedIsolate = vm_service.Isolate(
  id: '1',
  pauseEvent: vm_service.Event(
    kind: vm_service.EventKind.kPauseException,
    timestamp: 0
  ),
77 78 79 80 81 82
  breakpoints: <vm_service.Breakpoint>[
    vm_service.Breakpoint(
      breakpointNumber: 123,
      id: 'test-breakpoint',
      location: vm_service.SourceLocation(
        tokenPos: 0,
83
        script: vm_service.ScriptRef(id: 'test-script', uri: 'foo.dart'),
84
      ),
85
      enabled: true,
86 87 88
      resolved: true,
    ),
  ],
89 90 91 92 93 94 95
  libraries: <vm_service.LibraryRef>[],
  livePorts: 0,
  name: 'test',
  number: '1',
  pauseOnExit: false,
  runnable: true,
  startTime: 0,
96
  isSystemIsolate: false,
97
  isolateFlags: <vm_service.IsolateFlag>[],
98 99
);

100 101 102 103 104 105 106 107 108 109 110
final vm_service.VM fakeVM = vm_service.VM(
  isolates: <vm_service.IsolateRef>[fakeUnpausedIsolate],
  pid: 1,
  hostCPU: '',
  isolateGroups: <vm_service.IsolateGroupRef>[],
  targetCPU: '',
  startTime: 0,
  name: 'dart',
  architectureBits: 64,
  operatingSystem: '',
  version: '',
111 112
  systemIsolateGroups: <vm_service.IsolateGroupRef>[],
  systemIsolates: <vm_service.IsolateRef>[],
113 114
);

115 116 117 118 119
final FlutterView fakeFlutterView = FlutterView(
  id: 'a',
  uiIsolate: fakeUnpausedIsolate,
);

120 121 122 123 124 125 126 127 128
final FakeVmServiceRequest listViews = FakeVmServiceRequest(
  method: kListViewsMethod,
  jsonResponse: <String, Object>{
    'views': <Object>[
      fakeFlutterView.toJson(),
    ],
  },
);

129 130 131 132 133 134 135 136 137
const FakeVmServiceRequest setAssetBundlePath = FakeVmServiceRequest(
  method: '_flutter.setAssetBundlePath',
  args: <String, Object>{
    'viewId': 'a',
    'assetDirectory': 'build/flutter_assets',
    'isolateId': '1',
  }
);

138 139 140 141 142 143 144 145
const FakeVmServiceRequest evict = FakeVmServiceRequest(
  method: 'ext.flutter.evict',
  args: <String, Object>{
    'value': 'asset',
    'isolateId': '1',
  }
);

146 147 148 149 150 151 152 153
const FakeVmServiceRequest evictShader = FakeVmServiceRequest(
  method: 'ext.ui.window.reinitializeShader',
  args: <String, Object>{
    'assetKey': 'foo.frag',
    'isolateId': '1',
  }
);

154 155
final Uri testUri = Uri.parse('foo://bar');

156
void main() {
157 158 159 160 161 162
  late Testbed testbed;
  late FakeFlutterDevice flutterDevice;
  late FakeDevFS devFS;
  late ResidentRunner residentRunner;
  late FakeDevice device;
  FakeVmServiceHost? fakeVmServiceHost;
163 164 165

  setUp(() {
    testbed = Testbed(setup: () {
166 167
      globals.fs.file('.packages')
        .writeAsStringSync('\n');
168
      globals.fs.file(globals.fs.path.join('build', 'app.dill'))
169 170
        ..createSync(recursive: true)
        ..writeAsStringSync('ABC');
171 172
      residentRunner = HotRunner(
        <FlutterDevice>[
173
          flutterDevice,
174 175 176
        ],
        stayResident: false,
        debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
177
        target: 'main.dart',
178
        devtoolsHandler: createNoOpHandler,
179 180
      );
    });
181 182 183 184 185 186 187
    device = FakeDevice();
    devFS = FakeDevFS();
    flutterDevice = FakeFlutterDevice()
      ..testUri = testUri
      ..vmServiceHost = (() => fakeVmServiceHost)
      ..device = device
      .._devFS = devFS;
188 189
  });

190
  testUsingContext('ResidentRunner can attach to device successfully', () => testbed.run(() async {
191 192 193 194
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
195 196
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
197
    final Future<int?> result = residentRunner.attach(
198 199 200
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
201
    );
202
    final Future<DebugConnectionInfo> connectionInfo = futureConnectionInfo.future;
203 204

    expect(await result, 0);
205
    expect(futureConnectionInfo.isCompleted, true);
206
    expect((await connectionInfo).baseUri, 'foo://bar');
207
    expect(futureAppStart.isCompleted, true);
208
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
209
  }));
210

211
  testUsingContext('ResidentRunner suppresses errors for the initial compilation', () => testbed.run(() async {
212 213 214 215 216 217
    globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      .createSync(recursive: true);
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
218 219
    final FakeResidentCompiler residentCompiler = FakeResidentCompiler()
      ..nextOutput = const CompilerOutput('foo', 0 ,<Uri>[]);
220 221
    residentRunner = HotRunner(
      <FlutterDevice>[
222
        flutterDevice,
223 224 225
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
226
      target: 'main.dart',
227
      devtoolsHandler: createNoOpHandler,
228
    );
229
    flutterDevice.generator = residentCompiler;
230

231
    expect(await residentRunner.run(enableDevTools: true), 0);
232
    expect(residentCompiler.didSuppressErrors, true);
233
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
234
  }));
235

236 237 238 239 240
  // Regression test for https://github.com/flutter/flutter/issues/60613
  testUsingContext('ResidentRunner calls appFailedToStart if initial compilation fails', () => testbed.run(() async {
    globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      .createSync(recursive: true);
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
241 242
    final FakeResidentCompiler residentCompiler = FakeResidentCompiler()
      ..nextOutput = const CompilerOutput('foo', 1 ,<Uri>[]);
243 244
    residentRunner = HotRunner(
      <FlutterDevice>[
245
        flutterDevice,
246 247 248
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
249
      target: 'main.dart',
250
      devtoolsHandler: createNoOpHandler,
251
    );
252
    flutterDevice.generator = residentCompiler;
253 254 255 256 257 258 259 260 261 262 263 264 265

    expect(await residentRunner.run(), 1);
    // Completing this future ensures that the daemon can exit correctly.
    expect(await residentRunner.waitForAppToFinish(), 1);
  }));

  // Regression test for https://github.com/flutter/flutter/issues/60613
  testUsingContext('ResidentRunner calls appFailedToStart if initial compilation fails - cold mode', () => testbed.run(() async {
    globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      .createSync(recursive: true);
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
    residentRunner = ColdRunner(
      <FlutterDevice>[
266
        flutterDevice,
267 268 269
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.release),
270
      target: 'main.dart',
271
      devtoolsHandler: createNoOpHandler,
272
    );
273
    flutterDevice.runColdCode = 1;
274 275 276 277 278 279 280 281 282 283 284 285 286

    expect(await residentRunner.run(), 1);
    // Completing this future ensures that the daemon can exit correctly.
    expect(await residentRunner.waitForAppToFinish(), 1);
  }));

  // Regression test for https://github.com/flutter/flutter/issues/60613
  testUsingContext('ResidentRunner calls appFailedToStart if exception is thrown - cold mode', () => testbed.run(() async {
    globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      .createSync(recursive: true);
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
    residentRunner = ColdRunner(
      <FlutterDevice>[
287
        flutterDevice,
288 289 290
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.release),
291
      target: 'main.dart',
292
      devtoolsHandler: createNoOpHandler,
293
    );
294 295
    flutterDevice.runColdError = Exception('BAD STUFF');

296 297 298 299 300 301

    expect(await residentRunner.run(), 1);
    // Completing this future ensures that the daemon can exit correctly.
    expect(await residentRunner.waitForAppToFinish(), 1);
  }));

302
  testUsingContext('ResidentRunner does not suppressErrors if running with an applicationBinary', () => testbed.run(() async {
303 304 305 306 307 308
    globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      .createSync(recursive: true);
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
309 310
    final FakeResidentCompiler residentCompiler = FakeResidentCompiler()
      ..nextOutput = const CompilerOutput('foo', 0 ,<Uri>[]);
311 312
    residentRunner = HotRunner(
      <FlutterDevice>[
313
        flutterDevice,
314
      ],
315
      applicationBinary: globals.fs.file('app-debug.apk'),
316 317
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
318
      target: 'main.dart',
319
      devtoolsHandler: createNoOpHandler,
320
    );
321
    flutterDevice.generator = residentCompiler;
322

323
    expect(await residentRunner.run(enableDevTools: true), 0);
324
    expect(residentCompiler.didSuppressErrors, false);
325
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
326
  }));
327

328
  testUsingContext('ResidentRunner can attach to device successfully with --fast-start', () => testbed.run(() async {
329
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
330 331 332
      listViews,
      listViews,
      listViews,
333 334
      FakeVmServiceRequest(
        method: 'getIsolate',
335
        args: <String, Object?>{
336 337 338 339 340 341
          'isolateId': fakeUnpausedIsolate.id,
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'getVM',
342
        jsonResponse: vm_service.VM.parse(<String, Object>{})!.toJson(),
343
      ),
344
      listViews,
345
      const FakeVmServiceRequest(
346 347 348 349 350
        method: 'streamListen',
        args: <String, Object>{
          'streamId': 'Isolate',
        }
      ),
351
      FakeVmServiceRequest(
352 353
        method: kRunInViewMethod,
        args: <String, Object>{
354
          'viewId': fakeFlutterView.id,
355
          'mainScript': 'main.dart.dill',
356 357 358 359 360 361 362 363 364 365 366
          'assetDirectory': 'build/flutter_assets',
        }
      ),
      FakeVmServiceStreamResponse(
        streamId: 'Isolate',
        event: vm_service.Event(
          timestamp: 0,
          kind: vm_service.EventKind.kIsolateRunnable,
        )
      ),
    ]);
367 368
    residentRunner = HotRunner(
      <FlutterDevice>[
369
        flutterDevice,
370 371
      ],
      stayResident: false,
372 373 374 375 376
      debuggingOptions: DebuggingOptions.enabled(
        BuildInfo.debug,
        fastStart: true,
        startPaused: true,
      ),
377
      target: 'main.dart',
378
      devtoolsHandler: createNoOpHandler,
379
    );
380 381
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
382
    final Future<int?> result = residentRunner.attach(
383 384 385
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
386
    );
387
    final Future<DebugConnectionInfo> connectionInfo = futureConnectionInfo.future;
388 389

    expect(await result, 0);
390
    expect(futureConnectionInfo.isCompleted, true);
391
    expect((await connectionInfo).baseUri, 'foo://bar');
392
    expect(futureAppStart.isCompleted, true);
393
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
394
  }));
395

396
  testUsingContext('ResidentRunner can handle an RPC exception from hot reload', () => testbed.run(() async {
397 398 399 400 401
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
      listViews,
    ]);
402 403
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
404
    unawaited(residentRunner.attach(
405 406 407
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
408
    ));
409
    await futureAppStart.future;
410
    flutterDevice.reportError = vm_service.RPCError('something bad happened', 666, '');
411

412
    final OperationResult result = await residentRunner.restart();
413 414
    expect(result.fatal, true);
    expect(result.code, 1);
415
    expect((globals.flutterUsage as TestUsage).events, contains(
416 417 418 419 420
      TestUsageEvent('hot', 'exception', parameters: CustomDimensions(
        hotEventTargetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm),
        hotEventSdkName: 'Android',
        hotEventEmulator: false,
        hotEventFullRestart: false,
421
        fastReassemble: false,
422
      )),
423
    ));
424
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
425
  }, overrides: <Type, Generator>{
426
    Usage: () => TestUsage(),
427
  }));
428

429 430 431 432 433
  testUsingContext('ResidentRunner fails its operation if the device initialization is not complete', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
434 435
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
436
    unawaited(residentRunner.attach(
437 438
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
439
    ));
440
    await futureAppStart.future;
441
    flutterDevice._devFS = null;
442

443
    final OperationResult result = await residentRunner.restart();
444 445 446
    expect(result.fatal, false);
    expect(result.code, 1);
    expect(result.message, contains('Device initialization has not completed.'));
447
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
448
  }));
449

450 451 452 453 454 455
  testUsingContext('ResidentRunner can handle an reload-barred exception from hot reload', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
      listViews,
    ]);
456 457
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
458
    unawaited(residentRunner.attach(
459 460 461
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
462
    ));
463
    await futureAppStart.future;
464
    flutterDevice.reportError = vm_service.RPCError('something bad happened', kIsolateReloadBarred, '');
465

466
    final OperationResult result = await residentRunner.restart();
467 468 469
    expect(result.fatal, true);
    expect(result.code, kIsolateReloadBarred);
    expect(result.message, contains('Unable to hot reload application due to an unrecoverable error'));
470 471

    expect((globals.flutterUsage as TestUsage).events, contains(
472 473 474 475 476
      TestUsageEvent('hot', 'reload-barred', parameters: CustomDimensions(
        hotEventTargetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm),
        hotEventSdkName: 'Android',
        hotEventEmulator: false,
        hotEventFullRestart: false,
477
        fastReassemble: false,
478
      )),
479
    ));
480
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
481
  }, overrides: <Type, Generator>{
482
    Usage: () => TestUsage(),
483
  }));
484

485 486 487 488 489 490 491 492
  testUsingContext('ResidentRunner reports hot reload event with null safety analytics', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
      listViews,
    ]);
    residentRunner = HotRunner(
      <FlutterDevice>[
493
        flutterDevice,
494 495
      ],
      stayResident: false,
496
      target: 'main.dart',
497 498 499 500 501
      debuggingOptions: DebuggingOptions.enabled(const BuildInfo(
        BuildMode.debug, '', treeShakeIcons: false, extraFrontEndOptions: <String>[
        '--enable-experiment=non-nullable',
        ],
      )),
502
      devtoolsHandler: createNoOpHandler,
503
    );
504 505
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
506
    unawaited(residentRunner.attach(
507 508 509
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
510
    ));
511
    await futureAppStart.future;
512
    flutterDevice.reportError = vm_service.RPCError('something bad happened', 666, '');
513

514
    final OperationResult result = await residentRunner.restart();
515 516
    expect(result.fatal, true);
    expect(result.code, 1);
517 518

    expect((globals.flutterUsage as TestUsage).events, contains(
519 520 521 522 523
      TestUsageEvent('hot', 'exception', parameters: CustomDimensions(
        hotEventTargetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm),
        hotEventSdkName: 'Android',
        hotEventEmulator: false,
        hotEventFullRestart: false,
524
        fastReassemble: false,
525
      )),
526
    ));
527
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
528
  }, overrides: <Type, Generator>{
529
    Usage: () => TestUsage(),
530 531
  }));

532 533 534 535 536 537 538 539 540 541 542 543 544 545
  testUsingContext('ResidentRunner does not reload sources if no sources changed', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
     listViews,
      listViews,
      listViews,
      FakeVmServiceRequest(
        method: 'getIsolate',
        args: <String, Object>{
          'isolateId': '1',
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'ext.flutter.reassemble',
546
        args: <String, Object?>{
547 548 549 550 551 552
          'isolateId': fakeUnpausedIsolate.id,
        },
      ),
    ]);
    residentRunner = HotRunner(
      <FlutterDevice>[
553
        flutterDevice,
554 555 556
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
557
      target: 'main.dart',
558
      devtoolsHandler: createNoOpHandler,
559
    );
560 561
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
562
    unawaited(residentRunner.attach(
563 564 565
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
566
    ));
567
    await futureAppStart.future;
568
    flutterDevice.report =  UpdateFSReport(success: true);
569

570
    final OperationResult result = await residentRunner.restart();
571 572

    expect(result.code, 0);
573
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
574
  }));
575

576 577 578 579 580
  testUsingContext('ResidentRunner reports error with missing entrypoint file', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
      listViews,
581 582 583 584 585 586
      FakeVmServiceRequest(
        method: 'getVM',
        jsonResponse: vm_service.VM.parse(<String, Object>{
          'isolates': <Object>[
            fakeUnpausedIsolate.toJson(),
          ],
587
        })!.toJson(),
588 589 590 591 592 593
      ),
      const FakeVmServiceRequest(
        method: 'reloadSources',
        args: <String, Object>{
          'isolateId': '1',
          'pause': false,
594
          'rootLibUri': 'main.dart.incremental.dill',
595 596 597 598 599 600 601 602 603
        },
        jsonResponse: <String, Object>{
          'type': 'ReloadReport',
          'success': true,
          'details': <String, Object>{
            'loadedLibraryCount': 1,
          },
        },
      ),
604 605 606 607 608 609 610 611 612
      FakeVmServiceRequest(
        method: 'getIsolate',
        args: <String, Object>{
          'isolateId': '1',
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'ext.flutter.reassemble',
613
        args: <String, Object?>{
614 615 616 617
          'isolateId': fakeUnpausedIsolate.id,
        },
      ),
    ]);
618 619
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
620
    unawaited(residentRunner.attach(
621 622 623
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
624
    ));
625
    await futureAppStart.future;
626
    flutterDevice.report =  UpdateFSReport(success: true, invalidatedSourcesCount: 1);
627

628
    final OperationResult result = await residentRunner.restart();
629 630 631 632 633

    expect(globals.fs.file(globals.fs.path.join('lib', 'main.dart')), isNot(exists));
    expect(testLogger.errorText, contains('The entrypoint file (i.e. the file with main())'));
    expect(result.fatal, false);
    expect(result.code, 0);
634
  }));
635

636 637 638 639 640 641 642 643 644 645 646
   testUsingContext('ResidentRunner resets compilation time on reload reject', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
      listViews,
      FakeVmServiceRequest(
        method: 'getVM',
        jsonResponse: vm_service.VM.parse(<String, Object>{
          'isolates': <Object>[
            fakeUnpausedIsolate.toJson(),
          ],
647
        })!.toJson(),
648 649 650 651 652 653
      ),
      const FakeVmServiceRequest(
        method: 'reloadSources',
        args: <String, Object>{
          'isolateId': '1',
          'pause': false,
654
          'rootLibUri': 'main.dart.incremental.dill',
655 656 657 658 659 660
        },
        jsonResponse: <String, Object>{
          'type': 'ReloadReport',
          'success': false,
          'notices': <Object>[
            <String, Object>{
661 662
              'message': 'Failed to hot reload',
            },
663 664 665 666 667 668 669 670 671 672 673 674 675 676
          ],
          'details': <String, Object>{},
        },
      ),
      listViews,
      FakeVmServiceRequest(
        method: 'getIsolate',
        args: <String, Object>{
          'isolateId': '1',
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'ext.flutter.reassemble',
677
        args: <String, Object?>{
678 679 680 681
          'isolateId': fakeUnpausedIsolate.id,
        },
      ),
    ]);
682 683
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
684
    unawaited(residentRunner.attach(
685 686 687
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
688
    ));
689
    await futureAppStart.future;
690
    flutterDevice.report =  UpdateFSReport(success: true, invalidatedSourcesCount: 1);
691

692
    final OperationResult result = await residentRunner.restart();
693 694 695 696

    expect(result.fatal, false);
    expect(result.message, contains('Reload rejected: Failed to hot reload')); // contains error message from reload report.
    expect(result.code, 1);
697
    expect(devFS.lastCompiled, null);
698
  }));
699

700
  testUsingContext('ResidentRunner can send target platform to analytics from hot reload', () => testbed.run(() async {
701
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
702 703
      listViews,
      listViews,
704
      listViews,
705 706 707 708 709 710
      FakeVmServiceRequest(
        method: 'getVM',
        jsonResponse: vm_service.VM.parse(<String, Object>{
          'isolates': <Object>[
            fakeUnpausedIsolate.toJson(),
          ],
711
        })!.toJson(),
712 713 714 715 716 717
      ),
      const FakeVmServiceRequest(
        method: 'reloadSources',
        args: <String, Object>{
          'isolateId': '1',
          'pause': false,
718
          'rootLibUri': 'main.dart.incremental.dill',
719 720 721 722 723 724 725 726 727
        },
        jsonResponse: <String, Object>{
          'type': 'ReloadReport',
          'success': true,
          'details': <String, Object>{
            'loadedLibraryCount': 1,
          },
        },
      ),
728 729 730 731 732 733 734 735
      FakeVmServiceRequest(
        method: 'getIsolate',
        args: <String, Object>{
          'isolateId': '1',
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
736
        method: 'ext.flutter.reassemble',
737
        args: <String, Object?>{
738
          'isolateId': fakeUnpausedIsolate.id,
739 740 741
        },
      ),
    ]);
742 743
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
744
    unawaited(residentRunner.attach(
745 746 747
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
748
    ));
749
    await futureAppStart.future;
750

751
    final OperationResult result = await residentRunner.restart();
752 753
    expect(result.fatal, false);
    expect(result.code, 0);
754 755 756 757

    final TestUsageEvent event = (globals.flutterUsage as TestUsage).events.first;
    expect(event.category, 'hot');
    expect(event.parameter, 'reload');
758
    expect(event.parameters?.hotEventTargetPlatform, getNameForTargetPlatform(TargetPlatform.android_arm));
759
  }, overrides: <Type, Generator>{
760
    Usage: () => TestUsage(),
761
  }));
762

763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
  testUsingContext('ResidentRunner can perform fast reassemble', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      FakeVmServiceRequest(
        method: 'getVM',
        jsonResponse: fakeVM.toJson(),
      ),
      listViews,
      listViews,
      FakeVmServiceRequest(
        method: 'getVM',
        jsonResponse: fakeVM.toJson(),
      ),
      const FakeVmServiceRequest(
        method: 'reloadSources',
        args: <String, Object>{
          'isolateId': '1',
          'pause': false,
781
          'rootLibUri': 'main.dart.incremental.dill',
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
        },
        jsonResponse: <String, Object>{
          'type': 'ReloadReport',
          'success': true,
          'details': <String, Object>{
            'loadedLibraryCount': 1,
          },
        },
      ),
      FakeVmServiceRequest(
        method: 'getIsolate',
        args: <String, Object>{
          'isolateId': '1',
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'ext.flutter.fastReassemble',
800
        args: <String, Object?>{
801
          'isolateId': fakeUnpausedIsolate.id,
802
          'className': 'FOO',
803 804 805
        },
      ),
    ]);
806
    final FakeDelegateFlutterDevice flutterDevice = FakeDelegateFlutterDevice(
807
      device,
808 809
      BuildInfo.debug,
      FakeResidentCompiler(),
810
      devFS,
811
    )..vmService = fakeVmServiceHost!.vmService;
812 813 814 815 816 817
    residentRunner = HotRunner(
      <FlutterDevice>[
        flutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
818
      target: 'main.dart',
819
      devtoolsHandler: createNoOpHandler,
820
    );
821
    devFS.nextUpdateReport = UpdateFSReport(
822 823 824 825
      success: true,
      fastReassembleClassName: 'FOO',
      invalidatedSourcesCount: 1,
    );
826

827 828
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
829
    unawaited(residentRunner.attach(
830 831 832
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
833 834
    ));

835
    await futureAppStart.future;
836
    final OperationResult result = await residentRunner.restart();
837 838 839

    expect(result.fatal, false);
    expect(result.code, 0);
840 841 842 843

    final TestUsageEvent event = (globals.flutterUsage as TestUsage).events.first;
    expect(event.category, 'hot');
    expect(event.parameter, 'reload');
844
    expect(event.parameters?.fastReassemble, true);
845 846
  }, overrides: <Type, Generator>{
    FileSystem: () => MemoryFileSystem.test(),
847
    Platform: () => FakePlatform(),
848
    ProjectFileInvalidator: () => FakeProjectFileInvalidator(),
849
    Usage: () => TestUsage(),
850
    FeatureFlags: () => TestFeatureFlags(isSingleWidgetReloadEnabled: true),
851
  }));
852

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
  testUsingContext('ResidentRunner reports hot reload time details', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      FakeVmServiceRequest(
        method: 'getVM',
        jsonResponse: fakeVM.toJson(),
      ),
      listViews,
      listViews,
      FakeVmServiceRequest(
        method: 'getVM',
        jsonResponse: fakeVM.toJson(),
      ),
      const FakeVmServiceRequest(
        method: 'reloadSources',
        args: <String, Object>{
          'isolateId': '1',
          'pause': false,
          'rootLibUri': 'main.dart.incremental.dill',
        },
        jsonResponse: <String, Object>{
          'type': 'ReloadReport',
          'success': true,
          'details': <String, Object>{
            'loadedLibraryCount': 1,
            'finalLibraryCount': 42,
          },
        },
      ),
      FakeVmServiceRequest(
        method: 'getIsolate',
        args: <String, Object>{
          'isolateId': '1',
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'ext.flutter.fastReassemble',
891
        args: <String, Object?>{
892 893 894 895 896 897 898 899 900 901
          'isolateId': fakeUnpausedIsolate.id,
          'className': 'FOO',
        },
      ),
    ]);
    final FakeDelegateFlutterDevice flutterDevice = FakeDelegateFlutterDevice(
      device,
      BuildInfo.debug,
      FakeResidentCompiler(),
      devFS,
902
    )..vmService = fakeVmServiceHost!.vmService;
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
    residentRunner = HotRunner(
      <FlutterDevice>[
        flutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      target: 'main.dart',
      devtoolsHandler: createNoOpHandler,
    );
    devFS.nextUpdateReport = UpdateFSReport(
      success: true,
      fastReassembleClassName: 'FOO',
      invalidatedSourcesCount: 1,
    );

    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
    unawaited(residentRunner.attach(
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
    ));

    await futureAppStart.future;
    await residentRunner.restart();

    // The actual test: Expect to have compile, reload and reassemble times.
    expect(
        testLogger.statusText,
        contains(RegExp(r'Reloaded 1 of 42 libraries in \d+ms '
            r'\(compile: \d+ ms, reload: \d+ ms, reassemble: \d+ ms\)\.')));
  }, overrides: <Type, Generator>{
    FileSystem: () => MemoryFileSystem.test(),
    Platform: () => FakePlatform(),
    ProjectFileInvalidator: () => FakeProjectFileInvalidator(),
    Usage: () => TestUsage(),
    FeatureFlags: () => TestFeatureFlags(isSingleWidgetReloadEnabled: true),
  }));

942
  testUsingContext('ResidentRunner can send target platform to analytics from full restart', () => testbed.run(() async {
943
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
944 945 946
      listViews,
      listViews,
      listViews,
947 948
      FakeVmServiceRequest(
        method: 'getIsolate',
949
        args: <String, Object?>{
950 951 952 953 954 955
          'isolateId': fakeUnpausedIsolate.id,
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'getVM',
956
        jsonResponse: vm_service.VM.parse(<String, Object>{})!.toJson(),
957
      ),
958
      listViews,
959
      const FakeVmServiceRequest(
960 961 962 963 964
        method: 'streamListen',
        args: <String, Object>{
          'streamId': 'Isolate',
        },
      ),
965
      FakeVmServiceRequest(
966 967
        method: kRunInViewMethod,
        args: <String, Object>{
968
          'viewId': fakeFlutterView.id,
969
          'mainScript': 'main.dart.dill',
970 971 972 973 974 975 976 977 978
          'assetDirectory': 'build/flutter_assets',
        },
      ),
      FakeVmServiceStreamResponse(
        streamId: 'Isolate',
        event: vm_service.Event(
          timestamp: 0,
          kind: vm_service.EventKind.kIsolateRunnable,
        )
979
      ),
980
    ]);
981 982
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
983
    unawaited(residentRunner.attach(
984 985 986
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
987 988 989 990 991
    ));

    final OperationResult result = await residentRunner.restart(fullRestart: true);
    expect(result.fatal, false);
    expect(result.code, 0);
992 993 994 995

    final TestUsageEvent event = (globals.flutterUsage as TestUsage).events.first;
    expect(event.category, 'hot');
    expect(event.parameter, 'restart');
996 997
    expect(event.parameters?.hotEventTargetPlatform, getNameForTargetPlatform(TargetPlatform.android_arm));
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
998
  }, overrides: <Type, Generator>{
999
    Usage: () => TestUsage(),
1000
  }));
1001

1002
  testUsingContext('ResidentRunner can remove breakpoints and exception-pause-mode from paused isolate during hot restart', () => testbed.run(() async {
1003 1004 1005 1006 1007 1008
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
      listViews,
      FakeVmServiceRequest(
        method: 'getIsolate',
1009
        args: <String, Object?>{
1010 1011 1012 1013 1014 1015
          'isolateId': fakeUnpausedIsolate.id,
        },
        jsonResponse: fakePausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'getVM',
1016
        jsonResponse: vm_service.VM.parse(<String, Object>{})!.toJson(),
1017
      ),
1018
      const FakeVmServiceRequest(
1019
        method: 'setIsolatePauseMode',
1020 1021
        args: <String, String>{
          'isolateId': '1',
1022
          'exceptionPauseMode': 'None',
1023 1024
        }
      ),
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
      const FakeVmServiceRequest(
        method: 'removeBreakpoint',
        args: <String, String>{
          'isolateId': '1',
          'breakpointId': 'test-breakpoint',
        }
      ),
      const FakeVmServiceRequest(
        method: 'resume',
        args: <String, String>{
          'isolateId': '1',
        }
      ),
      listViews,
      const FakeVmServiceRequest(
        method: 'streamListen',
        args: <String, Object>{
          'streamId': 'Isolate',
        },
      ),
      FakeVmServiceRequest(
        method: kRunInViewMethod,
        args: <String, Object>{
          'viewId': fakeFlutterView.id,
1049
          'mainScript': 'main.dart.dill',
1050 1051 1052 1053 1054 1055 1056 1057
          'assetDirectory': 'build/flutter_assets',
        },
      ),
      FakeVmServiceStreamResponse(
        streamId: 'Isolate',
        event: vm_service.Event(
          timestamp: 0,
          kind: vm_service.EventKind.kIsolateRunnable,
1058 1059
        ),
      ),
1060
    ]);
1061 1062
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
1063
    unawaited(residentRunner.attach(
1064 1065 1066
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
1067 1068 1069 1070 1071
    ));

    final OperationResult result = await residentRunner.restart(fullRestart: true);

    expect(result.isOk, true);
1072
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
1073
  }));
1074

1075 1076 1077 1078 1079 1080 1081
  testUsingContext('ResidentRunner will alternative the name of the dill file uploaded for a hot restart', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
      listViews,
      FakeVmServiceRequest(
        method: 'getIsolate',
1082
        args: <String, Object?>{
1083 1084 1085 1086 1087 1088
          'isolateId': fakeUnpausedIsolate.id,
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'getVM',
1089
        jsonResponse: vm_service.VM.parse(<String, Object>{})!.toJson(),
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
      ),
      listViews,
      const FakeVmServiceRequest(
        method: 'streamListen',
        args: <String, Object>{
          'streamId': 'Isolate',
        },
      ),
      FakeVmServiceRequest(
        method: kRunInViewMethod,
        args: <String, Object>{
          'viewId': fakeFlutterView.id,
1102
          'mainScript': 'main.dart.dill',
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
          'assetDirectory': 'build/flutter_assets',
        },
      ),
      FakeVmServiceStreamResponse(
        streamId: 'Isolate',
        event: vm_service.Event(
          timestamp: 0,
          kind: vm_service.EventKind.kIsolateRunnable,
        ),
      ),
      listViews,
      FakeVmServiceRequest(
        method: 'getIsolate',
1116
        args: <String, Object?>{
1117 1118 1119 1120 1121 1122
          'isolateId': fakeUnpausedIsolate.id,
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'getVM',
1123
        jsonResponse: vm_service.VM.parse(<String, Object>{})!.toJson(),
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
      ),
      listViews,
      const FakeVmServiceRequest(
        method: 'streamListen',
        args: <String, Object>{
          'streamId': 'Isolate',
        },
      ),
      FakeVmServiceRequest(
        method: kRunInViewMethod,
        args: <String, Object>{
          'viewId': fakeFlutterView.id,
1136
          'mainScript': 'main.dart.swap.dill',
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
          'assetDirectory': 'build/flutter_assets',
        },
      ),
      FakeVmServiceStreamResponse(
        streamId: 'Isolate',
        event: vm_service.Event(
          timestamp: 0,
          kind: vm_service.EventKind.kIsolateRunnable,
        ),
      ),
      listViews,
      FakeVmServiceRequest(
        method: 'getIsolate',
1150
        args: <String, Object?>{
1151 1152 1153 1154 1155 1156
          'isolateId': fakeUnpausedIsolate.id,
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'getVM',
1157
        jsonResponse: vm_service.VM.parse(<String, Object>{})!.toJson(),
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
      ),
      listViews,
      const FakeVmServiceRequest(
        method: 'streamListen',
        args: <String, Object>{
          'streamId': 'Isolate',
        },
      ),
      FakeVmServiceRequest(
        method: kRunInViewMethod,
        args: <String, Object>{
          'viewId': fakeFlutterView.id,
1170
          'mainScript': 'main.dart.dill',
1171 1172 1173 1174 1175 1176 1177 1178 1179
          'assetDirectory': 'build/flutter_assets',
        },
      ),
      FakeVmServiceStreamResponse(
        streamId: 'Isolate',
        event: vm_service.Event(
          timestamp: 0,
          kind: vm_service.EventKind.kIsolateRunnable,
        ),
1180
      ),
1181
    ]);
1182 1183
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
1184
    unawaited(residentRunner.attach(
1185 1186 1187
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
1188 1189 1190 1191 1192 1193
    ));

    await residentRunner.restart(fullRestart: true);
    await residentRunner.restart(fullRestart: true);
    await residentRunner.restart(fullRestart: true);

1194
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
1195
  }));
1196

1197
  testUsingContext('ResidentRunner Can handle an RPC exception from hot restart', () => testbed.run(() async {
1198 1199 1200 1201
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
1202 1203
    final Completer<DebugConnectionInfo> futureConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> futureAppStart = Completer<void>.sync();
1204
    unawaited(residentRunner.attach(
1205 1206 1207
      appStartedCompleter: futureAppStart,
      connectionInfoCompleter: futureConnectionInfo,
      enableDevTools: true,
1208
    ));
1209
    await futureAppStart.future;
1210
    flutterDevice.reportError = vm_service.RPCError('something bad happened', 666, '');
1211 1212 1213 1214

    final OperationResult result = await residentRunner.restart(fullRestart: true);
    expect(result.fatal, true);
    expect(result.code, 1);
1215 1216

    expect((globals.flutterUsage as TestUsage).events, contains(
1217 1218 1219 1220 1221
      TestUsageEvent('hot', 'exception', parameters: CustomDimensions(
        hotEventTargetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm),
        hotEventSdkName: 'Android',
        hotEventEmulator: false,
        hotEventFullRestart: true,
1222
        fastReassemble: false,
1223
      )),
1224
    ));
1225
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
1226
  }, overrides: <Type, Generator>{
1227
    Usage: () => TestUsage(),
1228
  }));
1229

1230
  testUsingContext('ResidentRunner uses temp directory when there is no output dill path', () => testbed.run(() {
1231
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1232
    expect(residentRunner.artifactDirectory.path, contains('flutter_tool.'));
1233 1234 1235

    final ResidentRunner otherRunner = HotRunner(
      <FlutterDevice>[
1236
        flutterDevice,
1237 1238 1239
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
1240
      dillOutputPath: globals.fs.path.join('foobar', 'app.dill'),
1241
      target: 'main.dart',
1242
      devtoolsHandler: createNoOpHandler,
1243 1244 1245 1246
    );
    expect(otherRunner.artifactDirectory.path, contains('foobar'));
  }));

1247
  testUsingContext('ResidentRunner deletes artifact directory on preExit', () => testbed.run(() async {
1248
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1249
    residentRunner.artifactDirectory.childFile('app.dill').createSync();
1250 1251
    await residentRunner.preExit();

1252
    expect(residentRunner.artifactDirectory, isNot(exists));
1253 1254
  }));

1255
  testUsingContext('ResidentRunner can run source generation', () => testbed.run(() async {
1256 1257
    final File arbFile = globals.fs.file(globals.fs.path.join('lib', 'l10n', 'app_en.arb'))
      ..createSync(recursive: true);
1258 1259
    arbFile.writeAsStringSync('''
{
1260 1261 1262 1263 1264
  "helloWorld": "Hello, World!",
  "@helloWorld": {
    "description": "Sample description"
  }
}''');
1265
    globals.fs.file('l10n.yaml').createSync();
1266
    globals.fs.file('pubspec.yaml').writeAsStringSync('flutter:\n  generate: true\n');
1267

1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
    // Create necessary files for [DartPluginRegistrantTarget]
    final File packageConfig = globals.fs.directory('.dart_tool')
        .childFile('package_config.json');
    packageConfig.createSync(recursive: true);
    packageConfig.writeAsStringSync('''
{
  "configVersion": 2,
  "packages": [
    {
      "name": "path_provider_linux",
      "rootUri": "../../../path_provider_linux",
      "packageUri": "lib/",
      "languageVersion": "2.12"
    }
  ]
}
''');
1285 1286
    // Start from an empty dart_plugin_registrant.dart file.
    globals.fs.directory('.dart_tool').childDirectory('flutter_build').childFile('dart_plugin_registrant.dart').createSync(recursive: true);
1287

1288 1289 1290
    await residentRunner.runSourceGenerators();

    expect(testLogger.errorText, isEmpty);
1291
    expect(testLogger.statusText, isEmpty);
1292 1293
  }));

1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
  testUsingContext('generated main uses correct target', () => testbed.run(() async {
    final File arbFile = globals.fs.file(globals.fs.path.join('lib', 'l10n', 'app_en.arb'))
      ..createSync(recursive: true);
    arbFile.writeAsStringSync('''
{
  "helloWorld": "Hello, World!",
  "@helloWorld": {
    "description": "Sample description"
  }
}''');
    globals.fs.file('l10n.yaml').createSync();
    globals.fs.file('pubspec.yaml').writeAsStringSync('''
flutter:
  generate: true

dependencies:
  flutter:
    sdk: flutter
  path_provider_linux: 1.0.0
''');

    // Create necessary files for [DartPluginRegistrantTarget], including a
    // plugin that will trigger generation.
    final File packageConfig = globals.fs.directory('.dart_tool')
        .childFile('package_config.json');
    packageConfig.createSync(recursive: true);
    packageConfig.writeAsStringSync('''
{
  "configVersion": 2,
  "packages": [
    {
      "name": "path_provider_linux",
      "rootUri": "../path_provider_linux",
      "packageUri": "lib/",
      "languageVersion": "2.12"
    }
  ]
}
''');
    globals.fs.file('.packages').writeAsStringSync('''
path_provider_linux:/path_provider_linux/lib/
''');
    final Directory fakePluginDir = globals.fs.directory('path_provider_linux');
    final File pluginPubspec = fakePluginDir.childFile('pubspec.yaml');
    pluginPubspec.createSync(recursive: true);
    pluginPubspec.writeAsStringSync('''
name: path_provider_linux

flutter:
  plugin:
    implements: path_provider
    platforms:
      linux:
        dartPluginClass: PathProviderLinux
''');

    residentRunner = HotRunner(
        <FlutterDevice>[
          flutterDevice,
        ],
        stayResident: false,
        debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
        target: 'custom_main.dart',
        devtoolsHandler: createNoOpHandler,
      );
    await residentRunner.runSourceGenerators();

    final File generatedMain = globals.fs.directory('.dart_tool')
        .childDirectory('flutter_build')
1363
        .childFile('dart_plugin_registrant.dart');
1364

1365
    expect(generatedMain.existsSync(), isTrue);
1366 1367 1368 1369
    expect(testLogger.errorText, isEmpty);
    expect(testLogger.statusText, isEmpty);
  }));

1370
  testUsingContext('ResidentRunner can run source generation - generation fails', () => testbed.run(() async {
1371 1372 1373 1374
    // Intentionally define arb file with wrong name. generate_localizations defaults
    // to app_en.arb.
    final File arbFile = globals.fs.file(globals.fs.path.join('lib', 'l10n', 'foo.arb'))
      ..createSync(recursive: true);
1375 1376
    arbFile.writeAsStringSync('''
{
1377 1378 1379 1380 1381
  "helloWorld": "Hello, World!",
  "@helloWorld": {
    "description": "Sample description"
  }
}''');
1382
    globals.fs.file('l10n.yaml').createSync();
1383
    globals.fs.file('pubspec.yaml').writeAsStringSync('flutter:\n  generate: true\n');
1384 1385 1386

    await residentRunner.runSourceGenerators();

1387 1388
    expect(testLogger.errorText, allOf(contains('Exception')));
    expect(testLogger.statusText, isEmpty);
1389 1390
  }));

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
  testUsingContext('ResidentRunner generates files when l10n.yaml exists', () => testbed.run(() async {
    globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      .createSync(recursive: true);
    final File arbFile = globals.fs.file(globals.fs.path.join('lib', 'l10n', 'app_en.arb'))
      ..createSync(recursive: true);
    arbFile.writeAsStringSync('''
{
  "helloWorld": "Hello, World!",
  "@helloWorld": {
    "description": "Sample description"
  }
}''');
    globals.fs.file('l10n.yaml').createSync();
    globals.fs.file('pubspec.yaml').writeAsStringSync('flutter:\n  generate: true\n');

    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
    final FakeResidentCompiler residentCompiler = FakeResidentCompiler()
      ..nextOutput = const CompilerOutput('foo', 1 ,<Uri>[]);
    residentRunner = HotRunner(
      <FlutterDevice>[
        flutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      target: 'main.dart',
      devtoolsHandler: createNoOpHandler,
    );
    flutterDevice.generator = residentCompiler;

    await residentRunner.run();

    final File generatedLocalizationsFile = globals.fs.directory('.dart_tool')
      .childDirectory('flutter_gen')
      .childDirectory('gen_l10n')
      .childFile('app_localizations.dart');
    expect(generatedLocalizationsFile.existsSync(), isTrue);

    // Completing this future ensures that the daemon can exit correctly.
    expect(await residentRunner.waitForAppToFinish(), 1);
  }));

1432
  testUsingContext('ResidentRunner printHelpDetails hot runner', () => testbed.run(() {
1433
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1434 1435 1436

    residentRunner.printHelp(details: true);

1437 1438
    final CommandHelp commandHelp = residentRunner.commandHelp;

1439 1440 1441 1442
    // supports service protocol
    expect(residentRunner.supportsServiceProtocol, true);
    // isRunningDebug
    expect(residentRunner.isRunningDebug, true);
1443 1444
    // does support SkSL
    expect(residentRunner.supportsWriteSkSL, true);
1445 1446 1447 1448
    // commands
    expect(testLogger.statusText, equals(
        <dynamic>[
          'Flutter run key commands.',
1449 1450
          commandHelp.r,
          commandHelp.R,
1451
          commandHelp.v,
1452 1453 1454 1455 1456 1457 1458 1459
          commandHelp.s,
          commandHelp.w,
          commandHelp.t,
          commandHelp.L,
          commandHelp.S,
          commandHelp.U,
          commandHelp.i,
          commandHelp.p,
1460
          commandHelp.I,
1461
          commandHelp.o,
1462
          commandHelp.b,
1463 1464
          commandHelp.P,
          commandHelp.a,
1465 1466
          commandHelp.M,
          commandHelp.g,
1467
          commandHelp.j,
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
          commandHelp.hWithDetails,
          commandHelp.c,
          commandHelp.q,
          '',
          '💪 Running with sound null safety 💪',
          '',
          'An Observatory debugger and profiler on FakeDevice is available at: null',
          '',
        ].join('\n')
    ));
  }));

  testUsingContext('ResidentRunner printHelp hot runner', () => testbed.run(() {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);

    residentRunner.printHelp(details: false);

    final CommandHelp commandHelp = residentRunner.commandHelp;

    // supports service protocol
    expect(residentRunner.supportsServiceProtocol, true);
    // isRunningDebug
    expect(residentRunner.isRunningDebug, true);
    // does support SkSL
    expect(residentRunner.supportsWriteSkSL, true);
    // commands
    expect(testLogger.statusText, equals(
        <dynamic>[
          'Flutter run key commands.',
          commandHelp.r,
          commandHelp.R,
          commandHelp.hWithoutDetails,
          commandHelp.c,
          commandHelp.q,
1502 1503 1504
          '',
          '💪 Running with sound null safety 💪',
          '',
1505
          'An Observatory debugger and profiler on FakeDevice is available at: null',
1506
          '',
1507 1508
        ].join('\n')
    ));
1509 1510
  }));

1511 1512 1513 1514
  testUsingContext('ResidentRunner printHelpDetails cold runner', () => testbed.run(() {
    fakeVmServiceHost = null;
    residentRunner = ColdRunner(
      <FlutterDevice>[
1515
        flutterDevice,
1516 1517 1518
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.disabled(BuildInfo.release),
1519
      target: 'main.dart',
1520
      devtoolsHandler: createNoOpHandler,
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
    );
    residentRunner.printHelp(details: true);

    final CommandHelp commandHelp = residentRunner.commandHelp;

    // does not supports service protocol
    expect(residentRunner.supportsServiceProtocol, false);
    // isRunningDebug
    expect(residentRunner.isRunningDebug, false);
    // does support SkSL
    expect(residentRunner.supportsWriteSkSL, false);
    // commands
    expect(testLogger.statusText, equals(
        <dynamic>[
          'Flutter run key commands.',
1536
          commandHelp.v,
1537
          commandHelp.s,
1538 1539 1540
          commandHelp.hWithDetails,
          commandHelp.c,
          commandHelp.q,
1541
          '',
1542 1543 1544 1545 1546 1547 1548 1549
        ].join('\n')
    ));
  }));

  testUsingContext('ResidentRunner printHelp cold runner', () => testbed.run(() {
    fakeVmServiceHost = null;
    residentRunner = ColdRunner(
      <FlutterDevice>[
1550
        flutterDevice,
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.disabled(BuildInfo.release),
      target: 'main.dart',
      devtoolsHandler: createNoOpHandler,
    );
    residentRunner.printHelp(details: false);

    final CommandHelp commandHelp = residentRunner.commandHelp;

    // does not supports service protocol
    expect(residentRunner.supportsServiceProtocol, false);
    // isRunningDebug
    expect(residentRunner.isRunningDebug, false);
    // does support SkSL
    expect(residentRunner.supportsWriteSkSL, false);
    // commands
    expect(testLogger.statusText, equals(
        <dynamic>[
          'Flutter run key commands.',
          commandHelp.hWithoutDetails,
1572 1573
          commandHelp.c,
          commandHelp.q,
1574
          '',
1575 1576 1577 1578
        ].join('\n')
    ));
  }));

1579
  testUsingContext('ResidentRunner handles writeSkSL returning no data', () => testbed.run(() async {
1580
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
1581 1582
      listViews,
      FakeVmServiceRequest(
1583 1584
        method: kGetSkSLsMethod,
        args: <String, Object>{
1585
          'viewId': fakeFlutterView.id,
1586 1587
        },
        jsonResponse: <String, Object>{
1588
          'SkSLs': <String, Object>{},
1589
        }
1590
      ),
1591
    ]);
1592 1593
    await residentRunner.writeSkSL();

1594
    expect(testLogger.statusText, contains('No data was received'));
1595
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
1596 1597
  }));

1598
  testUsingContext('ResidentRunner can write SkSL data to a unique file with engine revision, platform, and device name', () => testbed.run(() async {
1599
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
1600
      listViews,
1601
      FakeVmServiceRequest(
1602 1603
        method: kGetSkSLsMethod,
        args: <String, Object>{
1604
          'viewId': fakeFlutterView.id,
1605 1606 1607 1608
        },
        jsonResponse: <String, Object>{
          'SkSLs': <String, Object>{
            'A': 'B',
1609 1610 1611
          },
        },
      ),
1612
    ]);
1613 1614
    await residentRunner.writeSkSL();

1615 1616 1617
    expect(testLogger.statusText, contains('flutter_01.sksl.json'));
    expect(globals.fs.file('flutter_01.sksl.json'), exists);
    expect(json.decode(globals.fs.file('flutter_01.sksl.json').readAsStringSync()), <String, Object>{
1618
      'platform': 'android',
1619
      'name': 'FakeDevice',
1620
      'engineRevision': 'abcdefg',
1621
      'data': <String, Object>{'A': 'B'},
1622
    });
1623
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
1624 1625 1626 1627
  }, overrides: <Type, Generator>{
    FileSystemUtils: () => FileSystemUtils(
      fileSystem: globals.fs,
      platform: globals.platform,
1628
    ),
1629
    FlutterVersion: () => FakeFlutterVersion(engineRevision: 'abcdefg'),
1630 1631
  }));

1632 1633 1634 1635 1636 1637 1638
  testUsingContext('ResidentRunner ignores DevtoolsLauncher when attaching with enableDevTools: false - cold mode', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
    residentRunner = ColdRunner(
      <FlutterDevice>[
1639
        flutterDevice,
1640 1641 1642 1643
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.profile, vmserviceOutFile: 'foo'),
      target: 'main.dart',
1644
      devtoolsHandler: createNoOpHandler,
1645 1646
    );

1647
    final Future<int?> result = residentRunner.attach();
1648
    expect(await result, 0);
1649
  }));
1650

1651
  testUsingContext('FlutterDevice can exit from a release mode isolate with no VmService', () => testbed.run(() async {
1652
    final TestFlutterDevice flutterDevice = TestFlutterDevice(
1653
      device,
1654 1655 1656 1657
    );

    await flutterDevice.exitApps();

1658
    expect(device.appStopped, true);
1659 1660
  }));

1661 1662
  testUsingContext('FlutterDevice will exit an un-paused isolate using stopApp', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1663
    final TestFlutterDevice flutterDevice = TestFlutterDevice(
1664
      device,
1665
    );
1666
    flutterDevice.vmService = fakeVmServiceHost!.vmService;
1667

1668 1669 1670
    final Future<void> exitFuture = flutterDevice.exitApps();

    await expectLater(exitFuture, completes);
1671
    expect(device.appStopped, true);
1672
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
1673
  }));
1674

1675
  testUsingContext('HotRunner writes vm service file when providing debugging option', () => testbed.run(() async {
1676 1677 1678
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
1679
    ], wsAddress: testUri);
1680
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
1681 1682
    residentRunner = HotRunner(
      <FlutterDevice>[
1683
        flutterDevice,
1684 1685 1686
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug, vmserviceOutFile: 'foo'),
1687
      target: 'main.dart',
1688
      devtoolsHandler: createNoOpHandler,
1689
    );
1690

1691
    await residentRunner.run(enableDevTools: true);
1692

1693
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
1694
    expect(await globals.fs.file('foo').readAsString(), testUri.toString());
1695
  }));
1696

1697
  testUsingContext('HotRunner copies compiled app.dill to cache during startup', () => testbed.run(() async {
1698 1699 1700
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
1701
    ], wsAddress: testUri);
1702 1703 1704
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
    residentRunner = HotRunner(
      <FlutterDevice>[
1705
        flutterDevice,
1706 1707
      ],
      stayResident: false,
1708 1709 1710 1711 1712 1713 1714
      debuggingOptions: DebuggingOptions.enabled(
        const BuildInfo(
          BuildMode.debug,
          null,
          treeShakeIcons: false,
        )
      ),
1715
      target: 'main.dart',
1716
      devtoolsHandler: createNoOpHandler,
1717 1718
    );
    residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC');
1719

1720
    await residentRunner.run(enableDevTools: true);
1721 1722

    expect(await globals.fs.file(globals.fs.path.join('build', 'cache.dill')).readAsString(), 'ABC');
1723
  }));
1724

1725 1726 1727 1728
  testUsingContext('HotRunner copies compiled app.dill to cache during startup with dart defines', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
1729
    ], wsAddress: testUri);
1730 1731 1732
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
    residentRunner = HotRunner(
      <FlutterDevice>[
1733
        flutterDevice,
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(
        const BuildInfo(
          BuildMode.debug,
          '',
          treeShakeIcons: false,
          dartDefines: <String>['a', 'b'],
        )
      ),
1744
      target: 'main.dart',
1745
      devtoolsHandler: createNoOpHandler,
1746 1747
    );
    residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC');
1748

1749
    await residentRunner.run(enableDevTools: true);
1750 1751 1752

    expect(await globals.fs.file(globals.fs.path.join(
      'build', '187ef4436122d1cc2f40dc2b92f0eba0.cache.dill')).readAsString(), 'ABC');
1753
  }));
1754

1755 1756 1757 1758
  testUsingContext('HotRunner copies compiled app.dill to cache during startup with null safety', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
1759
    ], wsAddress: testUri);
1760 1761 1762
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
    residentRunner = HotRunner(
      <FlutterDevice>[
1763
        flutterDevice,
1764 1765 1766 1767 1768 1769 1770
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(
        const BuildInfo(
          BuildMode.debug,
          '',
          treeShakeIcons: false,
1771
          extraFrontEndOptions: <String>['--enable-experiment=non-nullable']
1772 1773
        )
      ),
1774
      target: 'main.dart',
1775
      devtoolsHandler: createNoOpHandler,
1776 1777
    );
    residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC');
1778

1779
    await residentRunner.run(enableDevTools: true);
1780 1781

    expect(await globals.fs.file(globals.fs.path.join(
1782
      'build', 'cache.dill')).readAsString(), 'ABC');
1783
  }));
1784

1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
  testUsingContext('HotRunner copies compiled app.dill to cache during startup with track-widget-creation', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ], wsAddress: testUri);
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
    residentRunner = HotRunner(
      <FlutterDevice>[
        flutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      target: 'main.dart',
      devtoolsHandler: createNoOpHandler,
    );
    residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC');

    await residentRunner.run(enableDevTools: true);

    expect(await globals.fs.file(globals.fs.path.join(
      'build', 'cache.dill.track.dill')).readAsString(), 'ABC');
  }));

1808
  testUsingContext('HotRunner does not copy app.dill if a dillOutputPath is given', () => testbed.run(() async {
1809 1810 1811
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
1812
    ], wsAddress: testUri);
1813 1814 1815
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
    residentRunner = HotRunner(
      <FlutterDevice>[
1816
        flutterDevice,
1817 1818 1819 1820
      ],
      stayResident: false,
      dillOutputPath: 'test',
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
1821
      target: 'main.dart',
1822
      devtoolsHandler: createNoOpHandler,
1823 1824
    );
    residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC');
1825

1826
    await residentRunner.run(enableDevTools: true);
1827 1828

    expect(globals.fs.file(globals.fs.path.join('build', 'cache.dill')), isNot(exists));
1829
  }));
1830

1831
  testUsingContext('HotRunner copies compiled app.dill to cache during startup with --track-widget-creation', () => testbed.run(() async {
1832 1833 1834
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
1835
    ], wsAddress: testUri);
1836 1837 1838
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
    residentRunner = HotRunner(
      <FlutterDevice>[
1839
        flutterDevice,
1840 1841 1842 1843 1844 1845 1846 1847
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(const BuildInfo(
        BuildMode.debug,
        '',
        treeShakeIcons: false,
        trackWidgetCreation: true,
      )),
1848
      target: 'main.dart',
1849
      devtoolsHandler: createNoOpHandler,
1850 1851
    );
    residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC');
1852

1853
    await residentRunner.run(enableDevTools: true);
1854 1855

    expect(await globals.fs.file(globals.fs.path.join('build', 'cache.dill.track.dill')).readAsString(), 'ABC');
1856
  }));
1857

1858
  testUsingContext('HotRunner calls device dispose', () => testbed.run(() async {
1859 1860 1861
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
1862
    ], wsAddress: testUri);
1863
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
1864 1865
    residentRunner = HotRunner(
      <FlutterDevice>[
1866
        flutterDevice,
1867 1868 1869
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
1870
      target: 'main.dart',
1871
      devtoolsHandler: createNoOpHandler,
1872 1873 1874
    );

    await residentRunner.run();
1875
    expect(device.disposed, true);
1876
  }));
1877

1878
  testUsingContext('HotRunner handles failure to write vmservice file', () => testbed.run(() async {
1879 1880 1881 1882
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
1883
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
1884 1885
    residentRunner = HotRunner(
      <FlutterDevice>[
1886
        flutterDevice,
1887 1888 1889
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug, vmserviceOutFile: 'foo'),
1890
      target: 'main.dart',
1891
      devtoolsHandler: createNoOpHandler,
1892
    );
1893

1894
    await residentRunner.run(enableDevTools: true);
1895

1896
    expect(testLogger.errorText, contains('Failed to write vmservice-out-file at foo'));
1897
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
1898
  }, overrides: <Type, Generator>{
1899
    FileSystem: () => ThrowingForwardingFileSystem(MemoryFileSystem.test()),
1900
  }));
1901

1902
  testUsingContext('ColdRunner writes vm service file when providing debugging option', () => testbed.run(() async {
1903 1904
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
1905
    ], wsAddress: testUri);
1906
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
1907 1908
    residentRunner = ColdRunner(
      <FlutterDevice>[
1909
        flutterDevice,
1910 1911 1912
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.profile, vmserviceOutFile: 'foo'),
1913
      target: 'main.dart',
1914
      devtoolsHandler: createNoOpHandler,
1915
    );
1916

1917
    await residentRunner.run(enableDevTools: true);
1918

1919
    expect(await globals.fs.file('foo').readAsString(), testUri.toString());
1920
    expect(fakeVmServiceHost?.hasRemainingExpectations, false);
1921
  }));
1922

1923
  testUsingContext('FlutterDevice uses dartdevc configuration when targeting web', () async {
1924
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1925
    final FakeDevice device = FakeDevice(targetPlatform: TargetPlatform.web_javascript);
1926
    final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create(
1927
      device,
1928 1929 1930 1931 1932 1933
      buildInfo: const BuildInfo(
        BuildMode.debug,
        '',
        treeShakeIcons: false,
        nullSafetyMode: NullSafetyMode.unsound,
      ),
1934
      target: null,
1935
      platform: FakePlatform(),
1936
    )).generator as DefaultResidentCompiler?;
1937

1938
    expect(residentCompiler!.initializeFromDill,
1939
      globals.fs.path.join(getBuildDirectory(), 'fbbe6a61fb7a1de317d381f8df4814e5.cache.dill'));
1940
    expect(residentCompiler.librariesSpec,
1941
      globals.fs.file(globals.artifacts!.getHostArtifact(HostArtifact.flutterWebLibrariesJson))
1942
        .uri.toString());
1943 1944
    expect(residentCompiler.targetModel, TargetModel.dartdevc);
    expect(residentCompiler.sdkRoot,
1945
      '${globals.artifacts!.getHostArtifact(HostArtifact.flutterWebSdk).path}/');
1946
    expect(residentCompiler.platformDill, 'file:///HostArtifact.webPlatformKernelFolder/ddc_outline.dill');
1947 1948 1949 1950 1951 1952 1953 1954
  }, overrides: <Type, Generator>{
    Artifacts: () => Artifacts.test(),
    FileSystem: () => MemoryFileSystem.test(),
    ProcessManager: () => FakeProcessManager.any(),
  });

  testUsingContext('FlutterDevice uses dartdevc configuration when targeting web with null-safety autodetected', () async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1955
    final FakeDevice device = FakeDevice(targetPlatform: TargetPlatform.web_javascript);
1956

1957
    final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create(
1958
      device,
1959 1960 1961 1962 1963 1964 1965
      buildInfo: const BuildInfo(
        BuildMode.debug,
        '',
        treeShakeIcons: false,
        extraFrontEndOptions: <String>['--enable-experiment=non-nullable'],
      ),
      target: null,
1966
      platform: FakePlatform(),
1967
    )).generator as DefaultResidentCompiler?;
1968

1969
    expect(residentCompiler!.initializeFromDill,
1970
      globals.fs.path.join(getBuildDirectory(), '80b1a4cf4e7b90e1ab5f72022a0bc624.cache.dill'));
1971
    expect(residentCompiler.librariesSpec,
1972
      globals.fs.file(globals.artifacts!.getHostArtifact(HostArtifact.flutterWebLibrariesJson))
1973 1974 1975
        .uri.toString());
    expect(residentCompiler.targetModel, TargetModel.dartdevc);
    expect(residentCompiler.sdkRoot,
1976
      '${globals.artifacts!.getHostArtifact(HostArtifact.flutterWebSdk).path}/');
1977
    expect(residentCompiler.platformDill, 'file:///HostArtifact.webPlatformKernelFolder/ddc_outline_sound.dill');
1978 1979 1980 1981
  }, overrides: <Type, Generator>{
    Artifacts: () => Artifacts.test(),
    FileSystem: () => MemoryFileSystem.test(),
    ProcessManager: () => FakeProcessManager.any(),
1982
  });
1983

1984 1985
  testUsingContext('FlutterDevice passes flutter-widget-cache flag when feature is enabled', () async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1986
    final FakeDevice device = FakeDevice();
1987

1988
    final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create(
1989
      device,
1990 1991 1992 1993 1994 1995
      buildInfo: const BuildInfo(
        BuildMode.debug,
        '',
        treeShakeIcons: false,
        extraFrontEndOptions: <String>[],
      ),
1996 1997
      target: null, platform: FakePlatform(),
    )).generator as DefaultResidentCompiler?;
1998

1999
    expect(residentCompiler!.extraFrontEndOptions,
2000 2001 2002 2003 2004
      contains('--flutter-widget-cache'));
  }, overrides: <Type, Generator>{
    Artifacts: () => Artifacts.test(),
    FileSystem: () => MemoryFileSystem.test(),
    ProcessManager: () => FakeProcessManager.any(),
2005
    FeatureFlags: () => TestFeatureFlags(isSingleWidgetReloadEnabled: true),
2006 2007
  });

2008
   testUsingContext('FlutterDevice passes alternative-invalidation-strategy flag', () async {
2009
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
2010
    final FakeDevice device = FakeDevice();
2011

2012

2013
    final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create(
2014
      device,
2015 2016 2017 2018 2019 2020
      buildInfo: const BuildInfo(
        BuildMode.debug,
        '',
        treeShakeIcons: false,
        extraFrontEndOptions: <String>[],
      ),
2021 2022
      target: null, platform: FakePlatform(),
    )).generator as DefaultResidentCompiler?;
2023

2024
    expect(residentCompiler!.extraFrontEndOptions,
2025 2026 2027 2028 2029 2030 2031
      contains('--enable-experiment=alternative-invalidation-strategy'));
  }, overrides: <Type, Generator>{
    Artifacts: () => Artifacts.test(),
    FileSystem: () => MemoryFileSystem.test(),
    ProcessManager: () => FakeProcessManager.any(),
  });

2032 2033
   testUsingContext('FlutterDevice passes initializeFromDill parameter if specified', () async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
2034
    final FakeDevice device = FakeDevice();
2035

2036
    final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create(
2037
      device,
2038 2039 2040 2041 2042 2043 2044
      buildInfo: const BuildInfo(
        BuildMode.debug,
        '',
        treeShakeIcons: false,
        extraFrontEndOptions: <String>[],
        initializeFromDill: '/foo/bar.dill',
      ),
2045 2046
      target: null, platform: FakePlatform(),
    )).generator as DefaultResidentCompiler?;
2047

2048
    expect(residentCompiler!.initializeFromDill, '/foo/bar.dill');
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
    expect(residentCompiler.assumeInitializeFromDillUpToDate, false);
  }, overrides: <Type, Generator>{
    Artifacts: () => Artifacts.test(),
    FileSystem: () => MemoryFileSystem.test(),
    ProcessManager: () => FakeProcessManager.any(),
  });

   testUsingContext('FlutterDevice passes assumeInitializeFromDillUpToDate parameter if specified', () async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
    final FakeDevice device = FakeDevice();

2060
    final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create(
2061 2062 2063 2064 2065 2066 2067 2068
      device,
      buildInfo: const BuildInfo(
        BuildMode.debug,
        '',
        treeShakeIcons: false,
        extraFrontEndOptions: <String>[],
        assumeInitializeFromDillUpToDate: true,
      ),
2069 2070
      target: null, platform: FakePlatform(),
    )).generator as DefaultResidentCompiler?;
2071

2072
    expect(residentCompiler!.assumeInitializeFromDillUpToDate, true);
2073 2074 2075 2076 2077 2078
  }, overrides: <Type, Generator>{
    Artifacts: () => Artifacts.test(),
    FileSystem: () => MemoryFileSystem.test(),
    ProcessManager: () => FakeProcessManager.any(),
  });

2079 2080
  testUsingContext('Handle existing VM service clients DDS error', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
2081
    final FakeDevice device = FakeDevice()
2082
      ..dds = DartDevelopmentService();
2083
    ddsLauncherCallback = (Uri uri, {bool enableAuthCodes = true, bool ipv6 = false, Uri? serviceUri, List<String> cachedUserTags = const <String>[], dds.UriConverter? uriConverter}) {
2084 2085 2086 2087
      expect(uri, Uri(scheme: 'foo', host: 'bar'));
      expect(enableAuthCodes, isTrue);
      expect(ipv6, isFalse);
      expect(serviceUri, Uri(scheme: 'http', host: '127.0.0.1', port: 0));
2088
      expect(cachedUserTags, isEmpty);
2089
      expect(uriConverter, isNull);
2090 2091 2092 2093 2094
      throw FakeDartDevelopmentServiceException(message:
        'Existing VM service clients prevent DDS from taking control.',
      );
    };
    final TestFlutterDevice flutterDevice = TestFlutterDevice(
2095
      device,
2096 2097 2098 2099 2100 2101 2102
      observatoryUris: Stream<Uri>.value(testUri),
    );
    bool caught = false;
    final Completer<void>done = Completer<void>();
    runZonedGuarded(() {
      flutterDevice.connect(allowExistingDdsInstance: true).then((_) => done.complete());
    }, (Object e, StackTrace st) {
2103
      expect(e, isA<ToolExit>());
2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
      expect((e as ToolExit).message,
        contains('Existing VM service clients prevent DDS from taking control.',
      ));
      done.complete();
      caught = true;
    });
    await done.future;
    if (!caught) {
      fail('Expected ToolExit to be thrown.');
    }
2114 2115
  }, overrides: <Type, Generator>{
    VMServiceConnector: () => (Uri httpUri, {
2116 2117 2118 2119 2120 2121 2122 2123
      ReloadSources? reloadSources,
      Restart? restart,
      CompileExpression? compileExpression,
      GetSkSLMethod? getSkSLMethod,
      PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
      io.CompressionOptions? compression,
      Device? device,
      required Logger logger,
2124
    }) async => FakeVmServiceHost(requests: <VmServiceExpectation>[]).vmService,
2125 2126
  }));

2127 2128 2129 2130 2131
  testUsingContext('Host VM service ipv6 defaults', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
    final FakeDevice device = FakeDevice()
      ..dds = DartDevelopmentService();
    final Completer<void>done = Completer<void>();
2132
    ddsLauncherCallback = (Uri uri, {bool enableAuthCodes = true, bool ipv6 = false, Uri? serviceUri, List<String> cachedUserTags = const <String>[], dds.UriConverter? uriConverter}) async {
2133 2134 2135 2136
      expect(uri, Uri(scheme: 'foo', host: 'bar'));
      expect(enableAuthCodes, isFalse);
      expect(ipv6, isTrue);
      expect(serviceUri, Uri(scheme: 'http', host: '::1', port: 0));
2137
      expect(cachedUserTags, isEmpty);
2138
      expect(uriConverter, isNull);
2139
      done.complete();
2140
      return FakeDartDevelopmentService();
2141 2142 2143 2144 2145 2146 2147 2148 2149
    };
    final TestFlutterDevice flutterDevice = TestFlutterDevice(
      device,
      observatoryUris: Stream<Uri>.value(testUri),
    );
    await flutterDevice.connect(allowExistingDdsInstance: true, ipv6: true, disableServiceAuthCodes: true);
    await done.future;
  }, overrides: <Type, Generator>{
    VMServiceConnector: () => (Uri httpUri, {
2150 2151 2152 2153 2154 2155 2156 2157
      ReloadSources? reloadSources,
      Restart? restart,
      CompileExpression? compileExpression,
      GetSkSLMethod? getSkSLMethod,
      PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
      io.CompressionOptions? compression,
      Device? device,
      required Logger logger,
2158 2159 2160
    }) async => FakeVmServiceHost(requests: <VmServiceExpectation>[]).vmService,
  }));

2161 2162 2163 2164 2165
  testUsingContext('Context includes URI converter', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
    final FakeDevice device = FakeDevice()
      ..dds = DartDevelopmentService();
    final Completer<void>done = Completer<void>();
2166 2167 2168 2169 2170 2171 2172 2173
    ddsLauncherCallback = (
      Uri uri, {
      bool enableAuthCodes = false,
      bool ipv6 = false,
      Uri? serviceUri,
      List<String> cachedUserTags = const <String>[],
      dds.UriConverter? uriConverter,
    }) async {
2174 2175 2176 2177 2178 2179 2180
      expect(uri, Uri(scheme: 'foo', host: 'bar'));
      expect(enableAuthCodes, isFalse);
      expect(ipv6, isTrue);
      expect(serviceUri, Uri(scheme: 'http', host: '::1', port: 0));
      expect(cachedUserTags, isEmpty);
      expect(uriConverter, isNotNull);
      done.complete();
2181
      return FakeDartDevelopmentService();
2182 2183 2184 2185 2186 2187 2188 2189 2190
    };
    final TestFlutterDevice flutterDevice = TestFlutterDevice(
      device,
      observatoryUris: Stream<Uri>.value(testUri),
    );
    await flutterDevice.connect(allowExistingDdsInstance: true, ipv6: true, disableServiceAuthCodes: true);
    await done.future;
  }, overrides: <Type, Generator>{
    VMServiceConnector: () => (Uri httpUri, {
2191 2192 2193 2194 2195 2196 2197 2198
      ReloadSources? reloadSources,
      Restart? restart,
      CompileExpression? compileExpression,
      GetSkSLMethod? getSkSLMethod,
      PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
      io.CompressionOptions compression = io.CompressionOptions.compressionDefault,
      Device? device,
      required Logger logger,
2199 2200 2201 2202
    }) async => FakeVmServiceHost(requests: <VmServiceExpectation>[]).vmService,
    dds.UriConverter: () => (String uri) => 'test',
  }));

2203 2204
  testUsingContext('Failed DDS start outputs error message', () => testbed.run(() async {
    // See https://github.com/flutter/flutter/issues/72385 for context.
2205
    final FakeDevice device = FakeDevice()
2206
      ..dds = DartDevelopmentService();
2207 2208 2209 2210 2211 2212 2213 2214
    ddsLauncherCallback = (
      Uri uri, {
      bool enableAuthCodes = false,
      bool ipv6 = false,
      Uri? serviceUri,
      List<String> cachedUserTags = const <String>[],
      dds.UriConverter? uriConverter,
    }) {
2215 2216 2217 2218
      expect(uri, Uri(scheme: 'foo', host: 'bar'));
      expect(enableAuthCodes, isTrue);
      expect(ipv6, isFalse);
      expect(serviceUri, Uri(scheme: 'http', host: '127.0.0.1', port: 0));
2219
      expect(cachedUserTags, isEmpty);
2220
      expect(uriConverter, isNull);
2221 2222 2223
      throw FakeDartDevelopmentServiceException(message: 'No URI');
    };
    final TestFlutterDevice flutterDevice = TestFlutterDevice(
2224
      device,
2225 2226 2227 2228 2229 2230 2231
      observatoryUris: Stream<Uri>.value(testUri),
    );
    bool caught = false;
    final Completer<void>done = Completer<void>();
    runZonedGuarded(() {
      flutterDevice.connect(allowExistingDdsInstance: true).then((_) => done.complete());
    }, (Object e, StackTrace st) {
2232
      expect(e, isA<StateError>());
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
      expect((e as StateError).message, contains('No URI'));
      expect(testLogger.errorText, contains(
        'DDS has failed to start and there is not an existing DDS instance',
      ));
      done.complete();
      caught = true;
    });
    await done.future;
    if (!caught) {
      fail('Expected a StateError to be thrown.');
    }
2244 2245
  }, overrides: <Type, Generator>{
    VMServiceConnector: () => (Uri httpUri, {
2246 2247 2248 2249 2250 2251 2252 2253
      ReloadSources? reloadSources,
      Restart? restart,
      CompileExpression? compileExpression,
      GetSkSLMethod? getSkSLMethod,
      PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
      io.CompressionOptions compression = io.CompressionOptions.compressionDefault,
      Device? device,
      required Logger logger,
2254
    }) async => FakeVmServiceHost(requests: <VmServiceExpectation>[]).vmService,
2255
  }));
2256

2257
  testUsingContext('nextPlatform moves through expected platforms', () {
2258 2259 2260 2261 2262
    expect(nextPlatform('android'), 'iOS');
    expect(nextPlatform('iOS'), 'fuchsia');
    expect(nextPlatform('fuchsia'), 'macOS');
    expect(nextPlatform('macOS'), 'android');
    expect(() => nextPlatform('unknown'), throwsAssertionError);
2263
  });
2264 2265 2266 2267

  testUsingContext('cleanupAtFinish shuts down resident devtools handler', () => testbed.run(() async {
    residentRunner = HotRunner(
      <FlutterDevice>[
2268
        flutterDevice,
2269 2270 2271 2272 2273 2274 2275 2276
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug, vmserviceOutFile: 'foo'),
      target: 'main.dart',
      devtoolsHandler: createNoOpHandler,
    );
    await residentRunner.cleanupAtFinish();

2277
    expect((residentRunner.residentDevtoolsHandler! as NoOpDevtoolsHandler).wasShutdown, true);
2278
  }));
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295

  testUsingContext('HotRunner sets asset directory when first evict assets', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      setAssetBundlePath,
      evict,
    ]);
    residentRunner = HotRunner(
      <FlutterDevice>[
        flutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      target: 'main.dart',
      devtoolsHandler: createNoOpHandler,
    );

2296
    (flutterDevice.devFS! as FakeDevFS).assetPathsToEvict = <String>{'asset'};
2297

2298
    expect(flutterDevice.devFS!.hasSetAssetDirectory, isFalse);
2299
    await (residentRunner as HotRunner).evictDirtyAssets();
2300 2301
    expect(flutterDevice.devFS!.hasSetAssetDirectory, isTrue);
    expect(fakeVmServiceHost!.hasRemainingExpectations, isFalse);
2302 2303
  }));

2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
  testUsingContext('HotRunner sets asset directory when first evict shaders', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      setAssetBundlePath,
      evictShader,
    ]);
    residentRunner = HotRunner(
      <FlutterDevice>[
        flutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      target: 'main.dart',
      devtoolsHandler: createNoOpHandler,
    );

2320
    (flutterDevice.devFS! as FakeDevFS).shaderPathsToEvict = <String>{'foo.frag'};
2321

2322
    expect(flutterDevice.devFS!.hasSetAssetDirectory, false);
2323
    await (residentRunner as HotRunner).evictDirtyAssets();
2324 2325
    expect(flutterDevice.devFS!.hasSetAssetDirectory, true);
    expect(fakeVmServiceHost!.hasRemainingExpectations, false);
2326 2327
  }));

2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
  testUsingContext('HotRunner does not sets asset directory when no assets to evict', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
    ]);
    residentRunner = HotRunner(
      <FlutterDevice>[
        flutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      target: 'main.dart',
      devtoolsHandler: createNoOpHandler,
    );

2341
    expect(flutterDevice.devFS!.hasSetAssetDirectory, false);
2342
    await (residentRunner as HotRunner).evictDirtyAssets();
2343 2344
    expect(flutterDevice.devFS!.hasSetAssetDirectory, false);
    expect(fakeVmServiceHost!.hasRemainingExpectations, false);
2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361
  }));

  testUsingContext('HotRunner does not set asset directory if it has been set before', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      evict,
    ]);
    residentRunner = HotRunner(
      <FlutterDevice>[
        flutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      target: 'main.dart',
      devtoolsHandler: createNoOpHandler,
    );

2362 2363
    (flutterDevice.devFS! as FakeDevFS).assetPathsToEvict = <String>{'asset'};
    flutterDevice.devFS!.hasSetAssetDirectory = true;
2364 2365

    await (residentRunner as HotRunner).evictDirtyAssets();
2366 2367
    expect(flutterDevice.devFS!.hasSetAssetDirectory, true);
    expect(fakeVmServiceHost!.hasRemainingExpectations, false);
2368
  }));
2369 2370
}

2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
// NOTE: implements [dds.DartDevelopmentService] and NOT [DartDevelopmentService]
// from package:flutter_tools.
class FakeDartDevelopmentService extends Fake implements dds.DartDevelopmentService {
  @override
  Future<void> get done => Future<void>.value();

  @override
  Uri? get uri => null;
}

2381
class FakeDartDevelopmentServiceException implements dds.DartDevelopmentServiceException {
2382 2383
  FakeDartDevelopmentServiceException({this.message = defaultMessage});

2384 2385 2386 2387
  @override
  final int errorCode = dds.DartDevelopmentServiceException.existingDdsInstanceError;

  @override
2388 2389
  final String message;
  static const String defaultMessage = 'A DDS instance is already connected at http://localhost:8181';
2390 2391
}

2392
class TestFlutterDevice extends FlutterDevice {
2393 2394 2395 2396
  TestFlutterDevice(super.device, { Stream<Uri>? observatoryUris })
    : _observatoryUris = observatoryUris, super(buildInfo: BuildInfo.debug, developmentShaderCompiler: const FakeShaderCompiler());

  final Stream<Uri>? _observatoryUris;
2397

2398
  @override
2399
  Stream<Uri> get observatoryUris => _observatoryUris!;
2400 2401
}

2402
class ThrowingForwardingFileSystem extends ForwardingFileSystem {
2403
  ThrowingForwardingFileSystem(super.delegate);
2404 2405 2406 2407 2408 2409 2410 2411 2412

  @override
  File file(dynamic path) {
    if (path == 'foo') {
      throw const FileSystemException();
    }
    return delegate.file(path);
  }
}
2413

2414
class FakeFlutterDevice extends Fake implements FlutterDevice {
2415 2416
  FakeVmServiceHost? Function()? vmServiceHost;
  Uri? testUri;
2417 2418 2419 2420
  UpdateFSReport report = UpdateFSReport(
    success: true,
    invalidatedSourcesCount: 1,
  );
2421 2422
  Exception? reportError;
  Exception? runColdError;
2423 2424 2425 2426
  int runHotCode = 0;
  int runColdCode = 0;

  @override
2427
  ResidentCompiler? generator;
2428

2429 2430 2431 2432 2433 2434
  @override
  DevelopmentShaderCompiler get developmentShaderCompiler => const FakeShaderCompiler();

  @override
  TargetPlatform get targetPlatform => TargetPlatform.android;

2435
  @override
2436
  Stream<Uri?> get observatoryUris => Stream<Uri?>.value(testUri);
2437 2438

  @override
2439
  FlutterVmService? get vmService => vmServiceHost?.call()?.vmService;
2440

2441
  DevFS? _devFS;
2442 2443

  @override
2444
  DevFS? get devFS => _devFS;
2445 2446

  @override
2447
  set devFS(DevFS? value) { }
2448 2449

  @override
2450
  Device? device;
2451 2452 2453 2454 2455 2456 2457 2458 2459

  @override
  Future<void> stopEchoingDeviceLog() async { }

  @override
  Future<void> initLogReader() async { }

  @override
  Future<Uri> setupDevFS(String fsName, Directory rootDirectory) async {
2460
    return testUri!;
2461 2462 2463
  }

  @override
2464
  Future<int> runHot({required HotRunner hotRunner, String? route}) async {
2465 2466 2467 2468
    return runHotCode;
  }

  @override
2469
  Future<int> runCold({required ColdRunner coldRunner, String? route}) async {
2470
    if (runColdError != null) {
2471
      throw runColdError!;
2472 2473 2474 2475 2476 2477
    }
    return runColdCode;
  }

  @override
  Future<void> connect({
2478 2479 2480 2481 2482 2483 2484
    ReloadSources? reloadSources,
    Restart? restart,
    CompileExpression? compileExpression,
    GetSkSLMethod? getSkSLMethod,
    PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
    int? hostVmServicePort,
    int? ddsPort,
2485 2486
    bool disableServiceAuthCodes = false,
    bool enableDds = true,
2487
    bool cacheStartupProfile = false,
2488
    required bool allowExistingDdsInstance,
2489 2490 2491 2492 2493
    bool ipv6 = false,
  }) async { }

  @override
  Future<UpdateFSReport> updateDevFS({
2494 2495 2496 2497
    required Uri mainUri,
    String? target,
    AssetBundle? bundle,
    DateTime? firstBuildTime,
2498 2499 2500
    bool bundleFirstUpload = false,
    bool bundleDirty = false,
    bool fullRestart = false,
2501 2502 2503 2504 2505
    String? projectRootPath,
    required String pathToReload,
    required String dillOutputPath,
    required List<Uri> invalidatedFiles,
    required PackageConfig packageConfig,
2506 2507
  }) async {
    if (reportError != null) {
2508
      throw reportError!;
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
    }
    return report;
  }

  @override
  Future<void> updateReloadStatus(bool wasReloadSuccessful) async { }
}

class FakeDelegateFlutterDevice extends FlutterDevice {
  FakeDelegateFlutterDevice(
2519
    super.device,
2520 2521 2522
    BuildInfo buildInfo,
    ResidentCompiler residentCompiler,
    this.fakeDevFS,
2523
  ) : super(buildInfo: buildInfo, generator: residentCompiler, developmentShaderCompiler: const FakeShaderCompiler());
2524 2525 2526

  @override
  Future<void> connect({
2527 2528
    ReloadSources? reloadSources,
    Restart? restart,
2529
    bool enableDds = true,
2530
    bool cacheStartupProfile = false,
2531
    bool disableServiceAuthCodes = false,
2532
    bool ipv6 = false,
2533 2534 2535 2536 2537
    CompileExpression? compileExpression,
    GetSkSLMethod? getSkSLMethod,
    int? hostVmServicePort,
    int? ddsPort,
    PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
2538
    bool allowExistingDdsInstance = false,
2539 2540 2541 2542 2543 2544
  }) async { }


  final DevFS fakeDevFS;

  @override
2545
  DevFS? get devFS => fakeDevFS;
2546 2547

  @override
2548
  set devFS(DevFS? value) {}
2549 2550 2551
}

class FakeResidentCompiler extends Fake implements ResidentCompiler {
2552
  CompilerOutput? nextOutput;
2553 2554
  bool didSuppressErrors = false;

2555
  @override
2556
  Future<CompilerOutput?> recompile(
2557
    Uri mainUri,
2558 2559 2560 2561 2562
    List<Uri>? invalidatedFiles, {
    required String outputPath,
    required PackageConfig packageConfig,
    String? projectRootPath,
    required FileSystem fs,
2563
    bool suppressErrors = false,
2564
    bool checkDartPluginRegistry = false,
2565
    File? dartPluginRegistrant,
2566
  }) async {
2567 2568
    didSuppressErrors = suppressErrors;
    return nextOutput ?? const CompilerOutput('foo.dill', 0, <Uri>[]);
2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
  }

  @override
  void accept() { }

  @override
  void reset() { }
}

class FakeProjectFileInvalidator extends Fake implements ProjectFileInvalidator {
  @override
  Future<InvalidationResult> findInvalidated({
2581 2582 2583 2584
    required DateTime? lastCompiled,
    required List<Uri> urisToMonitor,
    required String packagesPath,
    required PackageConfig packageConfig,
2585 2586 2587
    bool asyncScanning = false,
  }) async {
    return InvalidationResult(
2588
      packageConfig: packageConfig,
2589 2590 2591 2592
      uris: <Uri>[Uri.parse('file:///hello_world/main.dart'),
    ]);
  }
}
2593

2594 2595 2596
// 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
2597 2598 2599 2600 2601 2602
class FakeDevice extends Fake implements Device {
  FakeDevice({
    String sdkNameAndVersion = 'Android',
    TargetPlatform targetPlatform = TargetPlatform.android_arm,
    bool isLocalEmulator = false,
    this.supportsHotRestart = true,
2603 2604
    this.supportsScreenshot = true,
    this.supportsFlutterExit = true,
2605 2606 2607 2608 2609 2610 2611 2612
  }) : _isLocalEmulator = isLocalEmulator,
       _targetPlatform = targetPlatform,
       _sdkNameAndVersion = sdkNameAndVersion;

  final bool _isLocalEmulator;
  final TargetPlatform _targetPlatform;
  final String _sdkNameAndVersion;

2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625
  bool disposed = false;
  bool appStopped = false;
  bool failScreenshot = false;

  @override
  bool supportsHotRestart;

  @override
  bool supportsScreenshot;

  @override
  bool supportsFlutterExit;

2626
  @override
2627 2628 2629
  PlatformType get platformType => _targetPlatform == TargetPlatform.web_javascript
    ? PlatformType.web
    : PlatformType.android;
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643

  @override
  Future<String> get sdkNameAndVersion async => _sdkNameAndVersion;

  @override
  Future<TargetPlatform> get targetPlatform async => _targetPlatform;

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

  @override
  String get name => 'FakeDevice';

  @override
2644
  late DartDevelopmentService dds;
2645 2646 2647 2648 2649 2650 2651

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

  @override
2652
  Future<bool> stopApp(ApplicationPackage? app, {String? userIdentifier}) async {
2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
    appStopped = true;
    return true;
  }

  @override
  Future<void> takeScreenshot(File outputFile) async {
    if (failScreenshot) {
      throw Exception();
    }
    outputFile.writeAsBytesSync(List<int>.generate(1024, (int i) => i));
  }

  @override
  FutureOr<DeviceLogReader> getLogReader({
2667
    ApplicationPackage? app,
2668 2669 2670 2671 2672
    bool includePastLogs = false,
  }) => NoOpDeviceLogReader(name);

  @override
  DevicePortForwarder portForwarder = const NoOpDevicePortForwarder();
2673
}
2674 2675 2676

class FakeDevFS extends Fake implements DevFS {
  @override
2677
  DateTime? lastCompiled = DateTime(2000);
2678 2679

  @override
2680
  PackageConfig? lastPackageConfig = PackageConfig.empty;
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693

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

  @override
  Uri baseUri = Uri();

  @override
  Future<void> destroy() async { }

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

2694 2695 2696
  @override
  Set<String> shaderPathsToEvict = <String>{};

2697 2698 2699
  @override
  bool didUpdateFontManifest = false;

2700 2701
  UpdateFSReport nextUpdateReport = UpdateFSReport(success: true);

2702 2703 2704
  @override
  bool hasSetAssetDirectory = false;

2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716
  @override
  Future<Uri> create() async {
    return Uri();
  }

  @override
  void resetLastCompiled() {
    lastCompiled = null;
  }

  @override
  Future<UpdateFSReport> update({
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
    required Uri mainUri,
    required ResidentCompiler generator,
    required bool trackWidgetCreation,
    required String pathToReload,
    required List<Uri> invalidatedFiles,
    required PackageConfig packageConfig,
    required String dillOutputPath,
    required DevelopmentShaderCompiler shaderCompiler,
    DevFSWriter? devFSWriter,
    String? target,
    AssetBundle? bundle,
    DateTime? firstBuildTime,
2729 2730
    bool bundleFirstUpload = false,
    bool fullRestart = false,
2731 2732
    String? projectRootPath,
    File? dartPluginRegistrant,
2733 2734 2735 2736
  }) async {
    return nextUpdateReport;
  }
}
2737 2738 2739 2740 2741

class FakeShaderCompiler implements DevelopmentShaderCompiler {
  const FakeShaderCompiler();

  @override
2742
  void configureCompiler(TargetPlatform? platform, { required bool enableImpeller }) { }
2743 2744 2745 2746 2747 2748

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