resident_runner_test.dart 52.3 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:flutter_tools/src/cache.dart';
8
import 'package:vm_service/vm_service.dart' as vm_service;
9
import 'package:file/memory.dart';
10
import 'package:file_testing/file_testing.dart';
11
import 'package:flutter_tools/src/artifacts.dart';
12
import 'package:flutter_tools/src/base/command_help.dart';
13
import 'package:flutter_tools/src/base/common.dart';
14 15
import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/file_system.dart';
16
import 'package:flutter_tools/src/base/io.dart' as io;
17
import 'package:flutter_tools/src/build_info.dart';
18
import 'package:flutter_tools/src/compile.dart';
19
import 'package:flutter_tools/src/convert.dart';
20
import 'package:flutter_tools/src/devfs.dart';
21
import 'package:flutter_tools/src/device.dart';
22
import 'package:flutter_tools/src/globals.dart' as globals;
23
import 'package:flutter_tools/src/project.dart';
24
import 'package:flutter_tools/src/reporting/reporting.dart';
25
import 'package:flutter_tools/src/resident_runner.dart';
26
import 'package:flutter_tools/src/run_cold.dart';
27 28
import 'package:flutter_tools/src/run_hot.dart';
import 'package:flutter_tools/src/vmservice.dart';
29 30
import 'package:mockito/mockito.dart';

31
import '../src/common.dart';
32
import '../src/context.dart';
33
import '../src/testbed.dart';
34

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
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>[],
  exceptionPauseMode: null,
  libraries: <vm_service.LibraryRef>[],
  livePorts: 0,
  name: 'test',
  number: '1',
  pauseOnExit: false,
  runnable: true,
  startTime: 0,
);

final vm_service.Isolate fakePausedIsolate = vm_service.Isolate(
  id: '1',
  pauseEvent: vm_service.Event(
    kind: vm_service.EventKind.kPauseException,
    timestamp: 0
  ),
  breakpoints: <vm_service.Breakpoint>[],
  exceptionPauseMode: null,
  libraries: <vm_service.LibraryRef>[],
  livePorts: 0,
  name: 'test',
  number: '1',
  pauseOnExit: false,
  runnable: true,
  startTime: 0,
);

final FlutterView fakeFlutterView = FlutterView(
  id: 'a',
  uiIsolate: fakeUnpausedIsolate,
);

74 75 76 77 78 79 80 81 82
final FakeVmServiceRequest listViews = FakeVmServiceRequest(
  method: kListViewsMethod,
  jsonResponse: <String, Object>{
    'views': <Object>[
      fakeFlutterView.toJson(),
    ],
  },
);

83
void main() {
84 85 86 87 88 89 90
  final Uri testUri = Uri.parse('foo://bar');
  Testbed testbed;
  MockFlutterDevice mockFlutterDevice;
  MockVMService mockVMService;
  MockDevFS mockDevFS;
  ResidentRunner residentRunner;
  MockDevice mockDevice;
91
  FakeVmServiceHost fakeVmServiceHost;
92 93 94

  setUp(() {
    testbed = Testbed(setup: () {
95
      globals.fs.file('.packages').writeAsStringSync('\n');
96
      globals.fs.file(globals.fs.path.join('build', 'app.dill'))
97 98
        ..createSync(recursive: true)
        ..writeAsStringSync('ABC');
99 100 101 102 103 104 105 106 107 108 109 110
      residentRunner = HotRunner(
        <FlutterDevice>[
          mockFlutterDevice,
        ],
        stayResident: false,
        debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      );
    });
    mockFlutterDevice = MockFlutterDevice();
    mockDevice = MockDevice();
    mockVMService = MockVMService();
    mockDevFS = MockDevFS();
111

112 113 114
    // DevFS Mocks
    when(mockDevFS.lastCompiled).thenReturn(DateTime(2000));
    when(mockDevFS.sources).thenReturn(<Uri>[]);
115
    when(mockDevFS.baseUri).thenReturn(Uri());
116
    when(mockDevFS.destroy()).thenAnswer((Invocation invocation) async { });
117
    when(mockDevFS.assetPathsToEvict).thenReturn(<String>{});
118 119
    // FlutterDevice Mocks.
    when(mockFlutterDevice.updateDevFS(
120 121
      invalidatedFiles: anyNamed('invalidatedFiles'),
      mainUri: anyNamed('mainUri'),
122 123 124 125 126 127 128 129
      target: anyNamed('target'),
      bundle: anyNamed('bundle'),
      firstBuildTime: anyNamed('firstBuildTime'),
      bundleFirstUpload: anyNamed('bundleFirstUpload'),
      bundleDirty: anyNamed('bundleDirty'),
      fullRestart: anyNamed('fullRestart'),
      projectRootPath: anyNamed('projectRootPath'),
      pathToReload: anyNamed('pathToReload'),
130
      dillOutputPath: anyNamed('dillOutputPath'),
131
      packageConfig: anyNamed('packageConfig'),
132 133 134 135 136 137 138 139 140 141
    )).thenAnswer((Invocation invocation) async {
      return UpdateFSReport(
        success: true,
        syncedBytes: 0,
        invalidatedSourcesCount: 0,
      );
    });
    when(mockFlutterDevice.devFS).thenReturn(mockDevFS);
    when(mockFlutterDevice.device).thenReturn(mockDevice);
    when(mockFlutterDevice.stopEchoingDeviceLog()).thenAnswer((Invocation invocation) async { });
142
    when(mockFlutterDevice.observatoryUris).thenAnswer((_) => Stream<Uri>.value(testUri));
143 144 145
    when(mockFlutterDevice.connect(
      reloadSources: anyNamed('reloadSources'),
      restart: anyNamed('restart'),
146
      compileExpression: anyNamed('compileExpression'),
147
      getSkSLMethod: anyNamed('getSkSLMethod'),
148 149 150 151
    )).thenAnswer((Invocation invocation) async { });
    when(mockFlutterDevice.setupDevFS(any, any, packagesFilePath: anyNamed('packagesFilePath')))
      .thenAnswer((Invocation invocation) async {
        return testUri;
152
      });
153 154 155
    when(mockFlutterDevice.vmService).thenAnswer((Invocation invocation) {
      return fakeVmServiceHost.vmService;
    });
156 157 158 159 160 161 162 163 164 165 166 167 168 169
    when(mockFlutterDevice.reloadSources(any, pause: anyNamed('pause'))).thenAnswer((Invocation invocation) async {
      return <Future<vm_service.ReloadReport>>[
        Future<vm_service.ReloadReport>.value(vm_service.ReloadReport.parse(<String, dynamic>{
          'type': 'ReloadReport',
          'success': true,
          'details': <String, dynamic>{
            'loadedLibraryCount': 1,
            'finalLibraryCount': 1,
            'receivedLibraryCount': 1,
            'receivedClassesCount': 1,
            'receivedProceduresCount': 1,
          },
        })),
      ];
170 171 172
    });
  });

173
  testUsingContext('FlutterDevice can list views with a filter', () => testbed.run(() async {
174
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
175
      listViews,
176 177 178 179 180 181 182 183 184 185 186
    ]);
    final MockDevice mockDevice = MockDevice();
    final FlutterDevice flutterDevice = FlutterDevice(
      mockDevice,
      buildInfo: BuildInfo.debug,
      viewFilter: 'b', // Does not match name of `fakeFlutterView`.
    );

    flutterDevice.vmService = fakeVmServiceHost.vmService;
  }));

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

    expect(await result, 0);

    verify(mockFlutterDevice.initLogReader()).called(1);

    expect(onConnectionInfo.isCompleted, true);
    expect((await connectionInfo).baseUri, 'foo://bar');
    expect(onAppStart.isCompleted, true);
207
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
208 209
  }));

210
  testUsingContext('ResidentRunner suppresses errors for the initial compilation', () => testbed.run(() async {
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      .createSync(recursive: true);
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
    final MockResidentCompiler residentCompiler = MockResidentCompiler();
    residentRunner = HotRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
    );
    when(mockFlutterDevice.generator).thenReturn(residentCompiler);
    when(residentCompiler.recompile(
      any,
      any,
      outputPath: anyNamed('outputPath'),
      packageConfig: anyNamed('packageConfig'),
      suppressErrors: true,
    )).thenAnswer((Invocation invocation) async {
      return const CompilerOutput('foo', 0 ,<Uri>[]);
    });
    when(mockFlutterDevice.runHot(
      hotRunner: anyNamed('hotRunner'),
      route: anyNamed('route'),
    )).thenAnswer((Invocation invocation) async {
      return 0;
    });

    expect(await residentRunner.run(), 0);
    verify(residentCompiler.recompile(
      any,
      any,
      outputPath: anyNamed('outputPath'),
      packageConfig: anyNamed('packageConfig'),
      suppressErrors: true,
    )).called(1);
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  }));

253
  testUsingContext('ResidentRunner does not suppressErrors if running with an applicationBinary', () => testbed.run(() async {
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      .createSync(recursive: true);
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
    final MockResidentCompiler residentCompiler = MockResidentCompiler();
    residentRunner = HotRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      applicationBinary: globals.fs.file('app.apk'),
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
    );
    when(mockFlutterDevice.generator).thenReturn(residentCompiler);
    when(residentCompiler.recompile(
      any,
      any,
      outputPath: anyNamed('outputPath'),
      packageConfig: anyNamed('packageConfig'),
      suppressErrors: false,
    )).thenAnswer((Invocation invocation) async {
      return const CompilerOutput('foo', 0, <Uri>[]);
    });
    when(mockFlutterDevice.runHot(
      hotRunner: anyNamed('hotRunner'),
      route: anyNamed('route'),
    )).thenAnswer((Invocation invocation) async {
      return 0;
    });

    expect(await residentRunner.run(), 0);
    verify(residentCompiler.recompile(
      any,
      any,
      outputPath: anyNamed('outputPath'),
      packageConfig: anyNamed('packageConfig'),
      suppressErrors: false,
    )).called(1);
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  }));

297
  testUsingContext('ResidentRunner can attach to device successfully with --fast-start', () => testbed.run(() async {
298
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
299 300 301
      listViews,
      listViews,
      listViews,
302 303 304 305 306 307 308 309 310 311 312
      FakeVmServiceRequest(
        method: 'getIsolate',
        args: <String, Object>{
          'isolateId': fakeUnpausedIsolate.id,
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'getVM',
        jsonResponse: vm_service.VM.parse(<String, Object>{}).toJson(),
      ),
313
      listViews,
314
      const FakeVmServiceRequest(
315 316 317 318 319
        method: 'streamListen',
        args: <String, Object>{
          'streamId': 'Isolate',
        }
      ),
320
      FakeVmServiceRequest(
321 322
        method: kRunInViewMethod,
        args: <String, Object>{
323
          'viewId': fakeFlutterView.id,
324 325 326 327 328 329 330 331 332 333 334 335
          'mainScript': 'lib/main.dart.dill',
          'assetDirectory': 'build/flutter_assets',
        }
      ),
      FakeVmServiceStreamResponse(
        streamId: 'Isolate',
        event: vm_service.Event(
          timestamp: 0,
          kind: vm_service.EventKind.kIsolateRunnable,
        )
      ),
    ]);
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    when(mockDevice.supportsHotRestart).thenReturn(true);
    when(mockDevice.sdkNameAndVersion).thenAnswer((Invocation invocation) async {
      return 'Example';
    });
    when(mockDevice.targetPlatform).thenAnswer((Invocation invocation) async {
      return TargetPlatform.android_arm;
    });
    when(mockDevice.isLocalEmulator).thenAnswer((Invocation invocation) async {
      return false;
    });
    residentRunner = HotRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      stayResident: false,
351 352 353 354 355
      debuggingOptions: DebuggingOptions.enabled(
        BuildInfo.debug,
        fastStart: true,
        startPaused: true,
      ),
356 357 358
    );
    final Completer<DebugConnectionInfo> onConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> onAppStart = Completer<void>.sync();
359 360 361 362 363 364 365 366 367 368 369 370 371
    final Future<int> result = residentRunner.attach(
      appStartedCompleter: onAppStart,
      connectionInfoCompleter: onConnectionInfo,
    );
    final Future<DebugConnectionInfo> connectionInfo = onConnectionInfo.future;

    expect(await result, 0);

    verify(mockFlutterDevice.initLogReader()).called(1);

    expect(onConnectionInfo.isCompleted, true);
    expect((await connectionInfo).baseUri, 'foo://bar');
    expect(onAppStart.isCompleted, true);
372
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
373 374
  }));

375
  testUsingContext('ResidentRunner can handle an RPC exception from hot reload', () => testbed.run(() async {
376 377 378 379 380
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
      listViews,
    ]);
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    when(mockDevice.sdkNameAndVersion).thenAnswer((Invocation invocation) async {
      return 'Example';
    });
    when(mockDevice.targetPlatform).thenAnswer((Invocation invocation) async {
      return TargetPlatform.android_arm;
    });
    when(mockDevice.isLocalEmulator).thenAnswer((Invocation invocation) async {
      return false;
    });
    final Completer<DebugConnectionInfo> onConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> onAppStart = Completer<void>.sync();
    unawaited(residentRunner.attach(
      appStartedCompleter: onAppStart,
      connectionInfoCompleter: onConnectionInfo,
    ));
    await onAppStart.future;
    when(mockFlutterDevice.updateDevFS(
398
      mainUri: anyNamed('mainUri'),
399 400 401 402 403 404 405 406 407
      target: anyNamed('target'),
      bundle: anyNamed('bundle'),
      firstBuildTime: anyNamed('firstBuildTime'),
      bundleFirstUpload: anyNamed('bundleFirstUpload'),
      bundleDirty: anyNamed('bundleDirty'),
      fullRestart: anyNamed('fullRestart'),
      projectRootPath: anyNamed('projectRootPath'),
      pathToReload: anyNamed('pathToReload'),
      invalidatedFiles: anyNamed('invalidatedFiles'),
408
      dillOutputPath: anyNamed('dillOutputPath'),
409
      packageConfig: anyNamed('packageConfig'),
410
    )).thenThrow(vm_service.RPCError('something bad happened', 666, ''));
411 412 413 414

    final OperationResult result = await residentRunner.restart(fullRestart: false);
    expect(result.fatal, true);
    expect(result.code, 1);
415
    verify(globals.flutterUsage.sendEvent('hot', 'exception', parameters: <String, String>{
416 417 418 419 420
      cdKey(CustomDimensions.hotEventTargetPlatform):
        getNameForTargetPlatform(TargetPlatform.android_arm),
      cdKey(CustomDimensions.hotEventSdkName): 'Example',
      cdKey(CustomDimensions.hotEventEmulator): 'false',
      cdKey(CustomDimensions.hotEventFullRestart): 'false',
421
    })).called(1);
422
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
423 424 425 426
  }, overrides: <Type, Generator>{
    Usage: () => MockUsage(),
  }));

427
  testUsingContext('ResidentRunner can send target platform to analytics from hot reload', () => testbed.run(() async {
428
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
429 430 431 432
      listViews,
      listViews,
      listViews,
      listViews,
433 434 435 436 437 438 439 440
      FakeVmServiceRequest(
        method: 'getIsolate',
        args: <String, Object>{
          'isolateId': '1',
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
441 442
        method: 'ext.flutter.reassemble',
        args: <String, Object>{
443
          'isolateId': fakeUnpausedIsolate.id,
444 445 446
        },
      ),
    ]);
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    when(mockDevice.sdkNameAndVersion).thenAnswer((Invocation invocation) async {
      return 'Example';
    });
    when(mockDevice.targetPlatform).thenAnswer((Invocation invocation) async {
      return TargetPlatform.android_arm;
    });
    when(mockDevice.isLocalEmulator).thenAnswer((Invocation invocation) async {
      return false;
    });
    final Completer<DebugConnectionInfo> onConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> onAppStart = Completer<void>.sync();
    unawaited(residentRunner.attach(
      appStartedCompleter: onAppStart,
      connectionInfoCompleter: onConnectionInfo,
    ));

    final OperationResult result = await residentRunner.restart(fullRestart: false);
    expect(result.fatal, false);
    expect(result.code, 0);
466
    expect(verify(globals.flutterUsage.sendEvent('hot', 'reload',
467 468
                  parameters: captureAnyNamed('parameters'))).captured[0],
      containsPair(cdKey(CustomDimensions.hotEventTargetPlatform),
469
                   getNameForTargetPlatform(TargetPlatform.android_arm)),
470 471 472 473 474
    );
  }, overrides: <Type, Generator>{
    Usage: () => MockUsage(),
  }));

475
  testUsingContext('ResidentRunner can send target platform to analytics from full restart', () => testbed.run(() async {
476
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
477 478 479
      listViews,
      listViews,
      listViews,
480 481 482 483 484 485 486 487 488 489 490
      FakeVmServiceRequest(
        method: 'getIsolate',
        args: <String, Object>{
          'isolateId': fakeUnpausedIsolate.id,
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'getVM',
        jsonResponse: vm_service.VM.parse(<String, Object>{}).toJson(),
      ),
491
      listViews,
492
      const FakeVmServiceRequest(
493 494 495 496 497
        method: 'streamListen',
        args: <String, Object>{
          'streamId': 'Isolate',
        },
      ),
498
      FakeVmServiceRequest(
499 500
        method: kRunInViewMethod,
        args: <String, Object>{
501
          'viewId': fakeFlutterView.id,
502 503 504 505 506 507 508 509 510 511 512 513
          'mainScript': 'lib/main.dart.dill',
          'assetDirectory': 'build/flutter_assets',
        },
      ),
      FakeVmServiceStreamResponse(
        streamId: 'Isolate',
        event: vm_service.Event(
          timestamp: 0,
          kind: vm_service.EventKind.kIsolateRunnable,
        )
      )
    ]);
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
    when(mockDevice.sdkNameAndVersion).thenAnswer((Invocation invocation) async {
      return 'Example';
    });
    when(mockDevice.targetPlatform).thenAnswer((Invocation invocation) async {
      return TargetPlatform.android_arm;
    });
    when(mockDevice.isLocalEmulator).thenAnswer((Invocation invocation) async {
      return false;
    });
    when(mockDevice.supportsHotRestart).thenReturn(true);
    final Completer<DebugConnectionInfo> onConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> onAppStart = Completer<void>.sync();
    unawaited(residentRunner.attach(
      appStartedCompleter: onAppStart,
      connectionInfoCompleter: onConnectionInfo,
    ));

    final OperationResult result = await residentRunner.restart(fullRestart: true);
    expect(result.fatal, false);
    expect(result.code, 0);
534
    expect(verify(globals.flutterUsage.sendEvent('hot', 'restart',
535 536
                  parameters: captureAnyNamed('parameters'))).captured[0],
      containsPair(cdKey(CustomDimensions.hotEventTargetPlatform),
537
                   getNameForTargetPlatform(TargetPlatform.android_arm)),
538
    );
539
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
540 541 542 543
  }, overrides: <Type, Generator>{
    Usage: () => MockUsage(),
  }));

544
  testUsingContext('ResidentRunner Can handle an RPC exception from hot restart', () => testbed.run(() async {
545 546 547 548
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    when(mockDevice.sdkNameAndVersion).thenAnswer((Invocation invocation) async {
      return 'Example';
    });
    when(mockDevice.targetPlatform).thenAnswer((Invocation invocation) async {
      return TargetPlatform.android_arm;
    });
    when(mockDevice.isLocalEmulator).thenAnswer((Invocation invocation) async {
      return false;
    });
    when(mockDevice.supportsHotRestart).thenReturn(true);
    final Completer<DebugConnectionInfo> onConnectionInfo = Completer<DebugConnectionInfo>.sync();
    final Completer<void> onAppStart = Completer<void>.sync();
    unawaited(residentRunner.attach(
      appStartedCompleter: onAppStart,
      connectionInfoCompleter: onConnectionInfo,
    ));
    await onAppStart.future;
    when(mockFlutterDevice.updateDevFS(
567
      mainUri: anyNamed('mainUri'),
568 569 570 571 572 573 574 575 576
      target: anyNamed('target'),
      bundle: anyNamed('bundle'),
      firstBuildTime: anyNamed('firstBuildTime'),
      bundleFirstUpload: anyNamed('bundleFirstUpload'),
      bundleDirty: anyNamed('bundleDirty'),
      fullRestart: anyNamed('fullRestart'),
      projectRootPath: anyNamed('projectRootPath'),
      pathToReload: anyNamed('pathToReload'),
      invalidatedFiles: anyNamed('invalidatedFiles'),
577
      dillOutputPath: anyNamed('dillOutputPath'),
578
      packageConfig: anyNamed('packageConfig'),
579
    )).thenThrow(vm_service.RPCError('something bad happened', 666, ''));
580 581 582 583

    final OperationResult result = await residentRunner.restart(fullRestart: true);
    expect(result.fatal, true);
    expect(result.code, 1);
584
    verify(globals.flutterUsage.sendEvent('hot', 'exception', parameters: <String, String>{
585 586 587 588 589
      cdKey(CustomDimensions.hotEventTargetPlatform):
        getNameForTargetPlatform(TargetPlatform.android_arm),
      cdKey(CustomDimensions.hotEventSdkName): 'Example',
      cdKey(CustomDimensions.hotEventEmulator): 'false',
      cdKey(CustomDimensions.hotEventFullRestart): 'true',
590
    })).called(1);
591
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
592 593 594 595
  }, overrides: <Type, Generator>{
    Usage: () => MockUsage(),
  }));

596
  testUsingContext('ResidentRunner uses temp directory when there is no output dill path', () => testbed.run(() {
597
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
598
    expect(residentRunner.artifactDirectory.path, contains('flutter_tool.'));
599 600 601 602 603 604 605

    final ResidentRunner otherRunner = HotRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
606
      dillOutputPath: globals.fs.path.join('foobar', 'app.dill'),
607 608 609 610
    );
    expect(otherRunner.artifactDirectory.path, contains('foobar'));
  }));

611
  testUsingContext('ResidentRunner deletes artifact directory on preExit', () => testbed.run(() async {
612
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
613
    residentRunner.artifactDirectory.childFile('app.dill').createSync();
614 615
    await residentRunner.preExit();

616
    expect(residentRunner.artifactDirectory, isNot(exists));
617 618
  }));

619
  testUsingContext('ResidentRunner can run source generation', () => testbed.run(() async {
620 621 622 623 624 625
    final FakeProcessManager processManager = globals.processManager as FakeProcessManager;
    final Directory dependencies = globals.fs.directory(
      globals.fs.path.join('build', '6ec2559087977927717927ede0a147f1'));
    processManager.addCommand(FakeCommand(
      command: <String>[
        globals.artifacts.getArtifactPath(Artifact.engineDartBinary),
626
        '--disable-dart-dev',
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
        globals.fs.path.join(Cache.flutterRoot, 'dev', 'tools', 'localization', 'bin', 'gen_l10n.dart'),
        '--gen-inputs-and-outputs-list=${dependencies.absolute.path}',
      ],
      onRun: () {
        dependencies
          .childFile('gen_l10n_inputs_and_outputs.json')
          ..createSync()
          ..writeAsStringSync('{"inputs":[],"outputs":[]}');
      }
    ));
    globals.fs.file(globals.fs.path.join('lib', 'l10n', 'foo.arb'))
      .createSync(recursive: true);
    globals.fs.file('l10n.yaml').createSync();

    await residentRunner.runSourceGenerators();

    expect(testLogger.errorText, isEmpty);
  }, overrides: <Type, Generator>{
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[]),
  }));

648
  testUsingContext('ResidentRunner can run source generation - generation fails', () => testbed.run(() async {
649 650 651 652 653 654
    final FakeProcessManager processManager = globals.processManager as FakeProcessManager;
    final Directory dependencies = globals.fs.directory(
      globals.fs.path.join('build', '6ec2559087977927717927ede0a147f1'));
    processManager.addCommand(FakeCommand(
      command: <String>[
        globals.artifacts.getArtifactPath(Artifact.engineDartBinary),
655
        '--disable-dart-dev',
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
        globals.fs.path.join(Cache.flutterRoot, 'dev', 'tools', 'localization', 'bin', 'gen_l10n.dart'),
        '--gen-inputs-and-outputs-list=${dependencies.absolute.path}',
      ],
      exitCode: 1,
      stderr: 'stderr'
    ));
    globals.fs.file(globals.fs.path.join('lib', 'l10n', 'foo.arb'))
      .createSync(recursive: true);
    globals.fs.file('l10n.yaml').createSync();

    await residentRunner.runSourceGenerators();

    expect(testLogger.errorText, allOf(
      contains('stderr'), // Message from gen_l10n.dart
      contains('Exception') // Message from build_system
    ));
  }, overrides: <Type, Generator>{
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[]),
  }));

676
  testUsingContext('ResidentRunner printHelpDetails', () => testbed.run(() {
677
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
678 679 680 681 682
    when(mockDevice.supportsHotRestart).thenReturn(true);
    when(mockDevice.supportsScreenshot).thenReturn(true);

    residentRunner.printHelp(details: true);

683 684
    final CommandHelp commandHelp = residentRunner.commandHelp;

685 686 687 688
    // supports service protocol
    expect(residentRunner.supportsServiceProtocol, true);
    // isRunningDebug
    expect(residentRunner.isRunningDebug, true);
689 690
    // does not support CanvasKit
    expect(residentRunner.supportsCanvasKit, false);
691 692
    // does support SkSL
    expect(residentRunner.supportsWriteSkSL, true);
693 694 695 696
    // commands
    expect(testLogger.statusText, equals(
        <dynamic>[
          'Flutter run key commands.',
697 698 699
          commandHelp.r,
          commandHelp.R,
          commandHelp.h,
700
          commandHelp.c,
701 702 703 704 705 706 707 708 709 710 711
          commandHelp.q,
          commandHelp.s,
          commandHelp.w,
          commandHelp.t,
          commandHelp.L,
          commandHelp.S,
          commandHelp.U,
          commandHelp.i,
          commandHelp.p,
          commandHelp.o,
          commandHelp.z,
712
          commandHelp.g,
713
          commandHelp.M,
714
          commandHelp.v,
715 716
          commandHelp.P,
          commandHelp.a,
717 718 719 720
          'An Observatory debugger and profiler on null is available at: null',
          ''
        ].join('\n')
    ));
721 722
  }));

723
  testUsingContext('ResidentRunner does support CanvasKit', () => testbed.run(() async {
724
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
725

726 727 728 729
    expect(() => residentRunner.toggleCanvaskit(),
      throwsA(isA<Exception>()));
  }));

730
  testUsingContext('ResidentRunner handles writeSkSL returning no data', () => testbed.run(() async {
731
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
732 733
      listViews,
      FakeVmServiceRequest(
734 735
        method: kGetSkSLsMethod,
        args: <String, Object>{
736
          'viewId': fakeFlutterView.id,
737 738 739 740
        },
        jsonResponse: <String, Object>{
          'SkSLs': <String, Object>{}
        }
741
      ),
742
    ]);
743 744 745
    await residentRunner.writeSkSL();

    expect(testLogger.statusText, contains('No data was receieved'));
746
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
747 748
  }));

749
  testUsingContext('ResidentRunner can write SkSL data to a unique file with engine revision, platform, and device name', () => testbed.run(() async {
750
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
751
      listViews,
752
      FakeVmServiceRequest(
753 754
        method: kGetSkSLsMethod,
        args: <String, Object>{
755
          'viewId': fakeFlutterView.id,
756 757 758 759 760 761 762 763
        },
        jsonResponse: <String, Object>{
          'SkSLs': <String, Object>{
            'A': 'B',
          }
        }
      )
    ]);
764 765 766 767 768 769
    when(mockDevice.targetPlatform).thenAnswer((Invocation invocation) async {
      return TargetPlatform.android_arm;
    });
    when(mockDevice.name).thenReturn('test device');
    await residentRunner.writeSkSL();

770 771 772
    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>{
773
      'platform': 'android',
774 775 776 777
      'name': 'test device',
      'engineRevision': '42.2', // From FakeFlutterVersion
      'data': <String, Object>{'A': 'B'}
    });
778
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
779 780
  }));

781
  testUsingContext('ResidentRunner can take screenshot on debug device', () => testbed.run(() async {
782
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
783
      listViews,
784
      FakeVmServiceRequest(
785 786
        method: 'ext.flutter.debugAllowBanner',
        args: <String, Object>{
787
          'isolateId': fakeUnpausedIsolate.id,
788 789 790
          'enabled': 'false',
        },
      ),
791
      FakeVmServiceRequest(
792 793
        method: 'ext.flutter.debugAllowBanner',
        args: <String, Object>{
794
          'isolateId': fakeUnpausedIsolate.id,
795 796 797 798
          'enabled': 'true',
        },
      )
    ]);
799 800
    when(mockDevice.supportsScreenshot).thenReturn(true);
    when(mockDevice.takeScreenshot(any))
801
      .thenAnswer((Invocation invocation) async {
802
        final File file = invocation.positionalArguments.first as File;
803 804
        file.writeAsBytesSync(List<int>.generate(1024, (int i) => i));
      });
805

806
    await residentRunner.screenshot(mockFlutterDevice);
807

808
    expect(testLogger.statusText, contains('1kB'));
809
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
810
  }));
811

812
  testUsingContext('ResidentRunner clears the screen when it should', () => testbed.run(() async {
813
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
814 815 816 817 818 819 820 821
    const String message = 'This should be cleared';
    expect(testLogger.statusText, equals(''));
    testLogger.printStatus(message);
    expect(testLogger.statusText, equals(message + '\n'));  // printStatus makes a newline
    residentRunner.clearScreen();
    expect(testLogger.statusText, equals(''));
  }));

822
  testUsingContext('ResidentRunner bails taking screenshot on debug device if debugAllowBanner throws RpcError', () => testbed.run(() async {
823
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
824
      listViews,
825
      FakeVmServiceRequest(
826 827
        method: 'ext.flutter.debugAllowBanner',
        args: <String, Object>{
828
          'isolateId': fakeUnpausedIsolate.id,
829 830 831 832 833 834
          'enabled': 'false',
        },
        // Failed response,
        errorCode: RPCErrorCodes.kInternalError,
      )
    ]);
835
    when(mockDevice.supportsScreenshot).thenReturn(true);
836
    await residentRunner.screenshot(mockFlutterDevice);
837

838 839 840 841
    expect(testLogger.errorText, contains('Error'));
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  }));

842
  testUsingContext('ResidentRunner bails taking screenshot on debug device if debugAllowBanner during second request', () => testbed.run(() async {
843
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
844
      listViews,
845
      FakeVmServiceRequest(
846 847
        method: 'ext.flutter.debugAllowBanner',
        args: <String, Object>{
848
          'isolateId': fakeUnpausedIsolate.id,
849 850 851
          'enabled': 'false',
        },
      ),
852
      FakeVmServiceRequest(
853 854
        method: 'ext.flutter.debugAllowBanner',
        args: <String, Object>{
855
          'isolateId': fakeUnpausedIsolate.id,
856 857 858 859 860 861 862
          'enabled': 'true',
        },
        // Failed response,
        errorCode: RPCErrorCodes.kInternalError,
      )
    ]);
    when(mockDevice.supportsScreenshot).thenReturn(true);
863 864
    await residentRunner.screenshot(mockFlutterDevice);

865
    expect(testLogger.errorText, contains('Error'));
866
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
867 868
  }));

869
  testUsingContext('ResidentRunner bails taking screenshot on debug device if takeScreenshot throws', () => testbed.run(() async {
870
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
871
      listViews,
872
      FakeVmServiceRequest(
873 874
        method: 'ext.flutter.debugAllowBanner',
        args: <String, Object>{
875
          'isolateId': fakeUnpausedIsolate.id,
876 877 878
          'enabled': 'false',
        },
      ),
879
      FakeVmServiceRequest(
880 881
        method: 'ext.flutter.debugAllowBanner',
        args: <String, Object>{
882
          'isolateId': fakeUnpausedIsolate.id,
883 884 885 886
          'enabled': 'true',
        },
      ),
    ]);
887 888 889 890 891
    when(mockDevice.supportsScreenshot).thenReturn(true);
    when(mockDevice.takeScreenshot(any)).thenThrow(Exception());

    await residentRunner.screenshot(mockFlutterDevice);

892
    expect(testLogger.errorText, contains('Error'));
893 894
  }));

895
  testUsingContext("ResidentRunner can't take screenshot on device without support", () => testbed.run(() {
896
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
897 898 899
    when(mockDevice.supportsScreenshot).thenReturn(false);

    expect(() => residentRunner.screenshot(mockFlutterDevice),
Dan Field's avatar
Dan Field committed
900
        throwsAssertionError);
901
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
902 903
  }));

904
  testUsingContext('ResidentRunner does not toggle banner in non-debug mode', () => testbed.run(() async {
905 906 907
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
    ]);
908 909 910 911 912 913 914 915 916
    residentRunner = HotRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.disabled(BuildInfo.release),
    );
    when(mockDevice.supportsScreenshot).thenReturn(true);
    when(mockDevice.takeScreenshot(any))
917
      .thenAnswer((Invocation invocation) async {
918
        final File file = invocation.positionalArguments.first as File;
919 920
        file.writeAsBytesSync(List<int>.generate(1024, (int i) => i));
      });
921 922 923

    await residentRunner.screenshot(mockFlutterDevice);

924
    expect(testLogger.statusText, contains('1kB'));
925
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
926 927
  }));

928
  testUsingContext('FlutterDevice will not exit a paused isolate', () => testbed.run(() async {
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      FakeVmServiceRequest(
        method: '_flutter.listViews',
        jsonResponse: <String, Object>{
          'views': <Object>[
            fakeFlutterView.toJson(),
          ],
        },
      ),
      FakeVmServiceRequest(
        method: 'getIsolate',
        args: <String, Object>{
          'isolateId': fakeUnpausedIsolate.id,
        },
        jsonResponse: fakePausedIsolate.toJson(),
      ),
    ]);
946 947 948
    final TestFlutterDevice flutterDevice = TestFlutterDevice(
      mockDevice,
    );
949
    flutterDevice.vmService = fakeVmServiceHost.vmService;
950 951 952 953
    when(mockDevice.supportsFlutterExit).thenReturn(true);

    await flutterDevice.exitApps();

954
    verify(mockDevice.stopApp(any, userIdentifier: anyNamed('userIdentifier'))).called(1);
955
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
956 957
  }));

958
  testUsingContext('FlutterDevice can exit from a release mode isolate with no VmService', () => testbed.run(() async {
959 960 961 962 963 964 965
    final TestFlutterDevice flutterDevice = TestFlutterDevice(
      mockDevice,
    );
    when(mockDevice.supportsFlutterExit).thenReturn(true);

    await flutterDevice.exitApps();

966
    verify(mockDevice.stopApp(any, userIdentifier: anyNamed('userIdentifier'))).called(1);
967 968
  }));

969
  testUsingContext('FlutterDevice will call stopApp if the exit request times out', () => testbed.run(() async {
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      FakeVmServiceRequest(
        method: '_flutter.listViews',
        jsonResponse: <String, Object>{
          'views': <Object>[
            fakeFlutterView.toJson(),
          ],
        },
      ),
      FakeVmServiceRequest(
        method: 'getIsolate',
        args: <String, Object>{
          'isolateId': fakeUnpausedIsolate.id,
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
        method: 'ext.flutter.exit',
        args: <String, Object>{
          'isolateId': fakeUnpausedIsolate.id,
        },
        // Intentionally do not close isolate.
        close: false,
      )
    ]);
    final TestFlutterDevice flutterDevice = TestFlutterDevice(
      mockDevice,
    );
    flutterDevice.vmService = fakeVmServiceHost.vmService;
    when(mockDevice.supportsFlutterExit).thenReturn(true);

    await flutterDevice.exitApps(
      timeoutDelay: Duration.zero,
    );

1005
    verify(mockDevice.stopApp(any, userIdentifier: anyNamed('userIdentifier'))).called(1);
1006 1007 1008
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  }));

1009
  testUsingContext('FlutterDevice will exit an un-paused isolate', () => testbed.run(() async {
1010
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
      FakeVmServiceRequest(
        method: kListViewsMethod,
        jsonResponse: <String, Object>{
          'views': <Object>[
            fakeFlutterView.toJson(),
          ],
        },
      ),
      FakeVmServiceRequest(
        method: 'getIsolate',
        args: <String, Object>{
          'isolateId': fakeUnpausedIsolate.id
        },
        jsonResponse: fakeUnpausedIsolate.toJson(),
      ),
      FakeVmServiceRequest(
1027 1028
        method: 'ext.flutter.exit',
        args: <String, Object>{
1029
          'isolateId': fakeUnpausedIsolate.id,
1030
        },
1031
        close: true,
1032 1033
      )
    ]);
1034 1035 1036
    final TestFlutterDevice flutterDevice = TestFlutterDevice(
      mockDevice,
    );
1037
    flutterDevice.vmService = fakeVmServiceHost.vmService;
1038 1039 1040

    when(mockDevice.supportsFlutterExit).thenReturn(true);

1041 1042 1043
    final Future<void> exitFuture = flutterDevice.exitApps();

    await expectLater(exitFuture, completes);
1044
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1045
  }));
1046

1047
  testUsingContext('ResidentRunner debugDumpApp calls flutter device', () => testbed.run(() async {
1048
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1049 1050 1051 1052 1053
    await residentRunner.debugDumpApp();

    verify(mockFlutterDevice.debugDumpApp()).called(1);
  }));

1054
  testUsingContext('ResidentRunner debugDumpRenderTree calls flutter device', () => testbed.run(() async {
1055
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1056 1057 1058 1059 1060
    await residentRunner.debugDumpRenderTree();

    verify(mockFlutterDevice.debugDumpRenderTree()).called(1);
  }));

1061
  testUsingContext('ResidentRunner debugDumpLayerTree calls flutter device', () => testbed.run(() async {
1062
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1063 1064 1065 1066 1067
    await residentRunner.debugDumpLayerTree();

    verify(mockFlutterDevice.debugDumpLayerTree()).called(1);
  }));

1068
  testUsingContext('ResidentRunner debugDumpSemanticsTreeInTraversalOrder calls flutter device', () => testbed.run(() async {
1069
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1070 1071 1072 1073 1074
    await residentRunner.debugDumpSemanticsTreeInTraversalOrder();

    verify(mockFlutterDevice.debugDumpSemanticsTreeInTraversalOrder()).called(1);
  }));

1075
  testUsingContext('ResidentRunner debugDumpSemanticsTreeInInverseHitTestOrder calls flutter device', () => testbed.run(() async {
1076
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1077 1078 1079 1080 1081
    await residentRunner.debugDumpSemanticsTreeInInverseHitTestOrder();

    verify(mockFlutterDevice.debugDumpSemanticsTreeInInverseHitTestOrder()).called(1);
  }));

1082
  testUsingContext('ResidentRunner debugToggleDebugPaintSizeEnabled calls flutter device', () => testbed.run(() async {
1083
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1084 1085 1086 1087 1088
    await residentRunner.debugToggleDebugPaintSizeEnabled();

    verify(mockFlutterDevice.toggleDebugPaintSizeEnabled()).called(1);
  }));

1089
  testUsingContext('ResidentRunner debugToggleDebugCheckElevationsEnabled calls flutter device', () => testbed.run(() async {
1090
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1091 1092 1093 1094 1095
    await residentRunner.debugToggleDebugCheckElevationsEnabled();

    verify(mockFlutterDevice.toggleDebugCheckElevationsEnabled()).called(1);
  }));

1096
  testUsingContext('ResidentRunner debugTogglePerformanceOverlayOverride calls flutter device', () => testbed.run(() async {
1097
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1098 1099 1100 1101 1102
    await residentRunner.debugTogglePerformanceOverlayOverride();

    verify(mockFlutterDevice.debugTogglePerformanceOverlayOverride()).called(1);
  }));

1103
  testUsingContext('ResidentRunner debugToggleWidgetInspector calls flutter device', () => testbed.run(() async {
1104
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1105 1106 1107 1108 1109
    await residentRunner.debugToggleWidgetInspector();

    verify(mockFlutterDevice.toggleWidgetInspector()).called(1);
  }));

1110
  testUsingContext('ResidentRunner debugToggleProfileWidgetBuilds calls flutter device', () => testbed.run(() async {
1111
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1112 1113 1114 1115
    await residentRunner.debugToggleProfileWidgetBuilds();

    verify(mockFlutterDevice.toggleProfileWidgetBuilds()).called(1);
  }));
1116

1117
  testUsingContext('HotRunner writes vm service file when providing debugging option', () => testbed.run(() async {
1118 1119 1120 1121
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
1122
    setWsAddress(testUri, fakeVmServiceHost.vmService);
1123
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
    residentRunner = HotRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug, vmserviceOutFile: 'foo'),
    );
    when(mockFlutterDevice.runHot(
      hotRunner: anyNamed('hotRunner'),
      route: anyNamed('route'),
    )).thenAnswer((Invocation invocation) async {
      return 0;
    });
    await residentRunner.run();

1139
    expect(await globals.fs.file('foo').readAsString(), testUri.toString());
1140 1141
  }));

1142
  testUsingContext('HotRunner copies compiled app.dill to cache during startup', () => testbed.run(() async {
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
    setWsAddress(testUri, fakeVmServiceHost.vmService);
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
    residentRunner = HotRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
    );
    residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC');
    when(mockFlutterDevice.runHot(
      hotRunner: anyNamed('hotRunner'),
      route: anyNamed('route'),
    )).thenAnswer((Invocation invocation) async {
      return 0;
    });
    await residentRunner.run();

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

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
  testUsingContext('HotRunner copies compiled app.dill to cache during startup with dart defines', () => testbed.run(() async {
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
    setWsAddress(testUri, fakeVmServiceHost.vmService);
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
    residentRunner = HotRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(
        const BuildInfo(
          BuildMode.debug,
          '',
          treeShakeIcons: false,
          dartDefines: <String>['a', 'b'],
        )
      ),
    );
    residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC');
    when(mockFlutterDevice.runHot(
      hotRunner: anyNamed('hotRunner'),
      route: anyNamed('route'),
    )).thenAnswer((Invocation invocation) async {
      return 0;
    });
    await residentRunner.run();

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

1202
  testUsingContext('HotRunner does not copy app.dill if a dillOutputPath is given', () => testbed.run(() async {
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
    setWsAddress(testUri, fakeVmServiceHost.vmService);
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
    residentRunner = HotRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      stayResident: false,
      dillOutputPath: 'test',
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
    );
    residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC');
    when(mockFlutterDevice.runHot(
      hotRunner: anyNamed('hotRunner'),
      route: anyNamed('route'),
    )).thenAnswer((Invocation invocation) async {
      return 0;
    });
    await residentRunner.run();

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

1229
  testUsingContext('HotRunner copies compiled app.dill to cache during startup with --track-widget-creation', () => testbed.run(() async {
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
    setWsAddress(testUri, fakeVmServiceHost.vmService);
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
    residentRunner = HotRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(const BuildInfo(
        BuildMode.debug,
        '',
        treeShakeIcons: false,
        trackWidgetCreation: true,
      )),
    );
    residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC');
    when(mockFlutterDevice.runHot(
      hotRunner: anyNamed('hotRunner'),
      route: anyNamed('route'),
    )).thenAnswer((Invocation invocation) async {
      return 0;
    });
    await residentRunner.run();

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


1261
  testUsingContext('HotRunner unforwards device ports', () => testbed.run(() async {
1262 1263 1264 1265
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
1266 1267
    final MockDevicePortForwarder mockPortForwarder = MockDevicePortForwarder();
    when(mockDevice.portForwarder).thenReturn(mockPortForwarder);
1268
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
    residentRunner = HotRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
    );
    when(mockFlutterDevice.runHot(
      hotRunner: anyNamed('hotRunner'),
      route: anyNamed('route'),
    )).thenAnswer((Invocation invocation) async {
      return 0;
    });

    when(mockDevice.dispose()).thenAnswer((Invocation invocation) async {
      await mockDevice.portForwarder.dispose();
    });

    await residentRunner.run();

    verify(mockPortForwarder.dispose()).called(1);
  }));

1292
  testUsingContext('HotRunner handles failure to write vmservice file', () => testbed.run(() async {
1293 1294 1295 1296
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
      listViews,
    ]);
1297
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
    residentRunner = HotRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug, vmserviceOutFile: 'foo'),
    );
    when(mockFlutterDevice.runHot(
      hotRunner: anyNamed('hotRunner'),
      route: anyNamed('route'),
    )).thenAnswer((Invocation invocation) async {
      return 0;
    });
    await residentRunner.run();

1313
    expect(testLogger.errorText, contains('Failed to write vmservice-out-file at foo'));
1314
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1315 1316 1317 1318 1319
  }, overrides: <Type, Generator>{
    FileSystem: () => ThrowingForwardingFileSystem(MemoryFileSystem()),
  }));


1320
  testUsingContext('ColdRunner writes vm service file when providing debugging option', () => testbed.run(() async {
1321 1322 1323
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      listViews,
    ]);
1324
    globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
1325
    setWsAddress(testUri, fakeVmServiceHost.vmService);
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    residentRunner = ColdRunner(
      <FlutterDevice>[
        mockFlutterDevice,
      ],
      stayResident: false,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.profile, vmserviceOutFile: 'foo'),
    );
    when(mockFlutterDevice.runCold(
      coldRunner: anyNamed('coldRunner'),
      route: anyNamed('route'),
    )).thenAnswer((Invocation invocation) async {
      return 0;
    });
    await residentRunner.run();

1341
    expect(await globals.fs.file('foo').readAsString(), testUri.toString());
1342
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1343
  }));
1344

1345
  testUsingContext('FlutterDevice uses dartdevc configuration when targeting web', () => testbed.run(() async {
1346
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1347 1348 1349 1350 1351 1352 1353
    final MockDevice mockDevice = MockDevice();
    when(mockDevice.targetPlatform).thenAnswer((Invocation invocation) async {
      return TargetPlatform.web_javascript;
    });

    final DefaultResidentCompiler residentCompiler = (await FlutterDevice.create(
      mockDevice,
1354
      buildInfo: BuildInfo.debug,
1355 1356
      flutterProject: FlutterProject.current(),
      target: null,
1357
    )).generator as DefaultResidentCompiler;
1358

1359 1360
    expect(residentCompiler.initializeFromDill,
      globals.fs.path.join(getBuildDirectory(), 'cache.dill'));
1361 1362 1363
    expect(residentCompiler.librariesSpec,
      globals.fs.file(globals.artifacts.getArtifactPath(Artifact.flutterWebLibrariesJson))
        .uri.toString());
1364 1365
    expect(residentCompiler.targetModel, TargetModel.dartdevc);
    expect(residentCompiler.sdkRoot,
1366
      globals.artifacts.getArtifactPath(Artifact.flutterWebSdk, mode: BuildMode.debug) + '/');
1367 1368
    expect(
      residentCompiler.platformDill,
1369
      globals.fs.file(globals.artifacts.getArtifactPath(Artifact.webPlatformKernelDill, mode: BuildMode.debug))
1370 1371
        .absolute.uri.toString(),
    );
1372
  }));
1373

1374
  testUsingContext('connect sets up log reader', () => testbed.run(() async {
1375
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1376 1377 1378 1379 1380 1381
    final MockDevice mockDevice = MockDevice();
    final MockDeviceLogReader mockLogReader = MockDeviceLogReader();
    when(mockDevice.getLogReader(app: anyNamed('app'))).thenReturn(mockLogReader);

    final TestFlutterDevice flutterDevice = TestFlutterDevice(
      mockDevice,
1382
      observatoryUris: Stream<Uri>.value(testUri),
1383 1384 1385
    );

    await flutterDevice.connect();
1386
    verify(mockLogReader.connectedVMService = mockVMService);
1387
  }, overrides: <Type, Generator>{
1388 1389 1390 1391
    VMServiceConnector: () => (Uri httpUri, {
      ReloadSources reloadSources,
      Restart restart,
      CompileExpression compileExpression,
1392
      ReloadMethod reloadMethod,
1393
      GetSkSLMethod getSkSLMethod,
1394
      PrintStructuredErrorLogMethod printStructuredErrorLogMethod,
1395 1396 1397
      io.CompressionOptions compression,
      Device device,
    }) async => mockVMService,
1398
  }));
1399

1400
  testUsingContext('nextPlatform moves through expected platforms', () {
1401 1402 1403 1404
    expect(nextPlatform('android', TestFeatureFlags()), 'iOS');
    expect(nextPlatform('iOS', TestFeatureFlags()), 'fuchsia');
    expect(nextPlatform('fuchsia', TestFeatureFlags()), 'android');
    expect(nextPlatform('fuchsia', TestFeatureFlags(isMacOSEnabled: true)), 'macOS');
Dan Field's avatar
Dan Field committed
1405
    expect(() => nextPlatform('unknown', TestFeatureFlags()), throwsAssertionError);
1406
  });
1407 1408
}

1409
class MockFlutterDevice extends Mock implements FlutterDevice {}
1410
class MockVMService extends Mock implements vm_service.VmService {}
1411
class MockDevFS extends Mock implements DevFS {}
1412
class MockDevice extends Mock implements Device {}
1413
class MockDeviceLogReader extends Mock implements DeviceLogReader {}
1414
class MockDevicePortForwarder extends Mock implements DevicePortForwarder {}
1415
class MockUsage extends Mock implements Usage {}
1416
class MockProcessManager extends Mock implements ProcessManager {}
1417
class MockResidentCompiler extends Mock implements ResidentCompiler {}
1418

1419
class TestFlutterDevice extends FlutterDevice {
1420
  TestFlutterDevice(Device device, { Stream<Uri> observatoryUris })
1421
    : super(device, buildInfo: BuildInfo.debug) {
1422 1423
    _observatoryUris = observatoryUris;
  }
1424

1425
  @override
1426 1427
  Stream<Uri> get observatoryUris => _observatoryUris;
  Stream<Uri> _observatoryUris;
1428 1429
}

1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
class ThrowingForwardingFileSystem extends ForwardingFileSystem {
  ThrowingForwardingFileSystem(FileSystem delegate) : super(delegate);

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