resident_web_runner_test.dart 66.5 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
import 'dart:convert';
7
import 'dart:io';
8 9

import 'package:dwds/dwds.dart';
10
import 'package:file/memory.dart';
11
import 'package:flutter_tools/src/base/common.dart';
12
import 'package:flutter_tools/src/base/file_system.dart';
13
import 'package:flutter_tools/src/base/io.dart';
14
import 'package:flutter_tools/src/base/logger.dart';
15
import 'package:flutter_tools/src/base/platform.dart';
16
import 'package:flutter_tools/src/base/terminal.dart';
17
import 'package:flutter_tools/src/build_info.dart';
18 19
import 'package:flutter_tools/src/isolated/devfs_web.dart';
import 'package:flutter_tools/src/isolated/resident_web_runner.dart';
20
import 'package:flutter_tools/src/compile.dart';
21
import 'package:flutter_tools/src/dart/pub.dart';
22
import 'package:flutter_tools/src/devfs.dart';
23
import 'package:flutter_tools/src/device.dart';
24
import 'package:flutter_tools/src/globals.dart' as globals;
25
import 'package:flutter_tools/src/project.dart';
26
import 'package:flutter_tools/src/reporting/reporting.dart';
27
import 'package:flutter_tools/src/resident_runner.dart';
28
import 'package:flutter_tools/src/vmservice.dart';
29
import 'package:flutter_tools/src/web/chrome.dart';
30
import 'package:flutter_tools/src/web/web_device.dart';
31
import 'package:mockito/mockito.dart';
32
import 'package:vm_service/vm_service.dart' as vm_service;
33
import 'package:vm_service/vm_service.dart';
34
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart';
35 36

import '../src/common.dart';
37
import '../src/context.dart';
38 39
import '../src/testbed.dart';

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
const List<VmServiceExpectation> kAttachLogExpectations = <VmServiceExpectation>[
  FakeVmServiceRequest(
    method: 'streamListen',
    args: <String, Object>{
      'streamId': 'Stdout',
    },
  ),
  FakeVmServiceRequest(
    method: 'streamListen',
    args: <String, Object>{
      'streamId': 'Stderr',
    },
  )
];

const List<VmServiceExpectation> kAttachIsolateExpectations = <VmServiceExpectation>[
  FakeVmServiceRequest(
    method: 'streamListen',
    args: <String, Object>{
      'streamId': 'Isolate'
    }
  ),
62 63 64 65 66 67
  FakeVmServiceRequest(
    method: 'streamListen',
    args: <String, Object>{
      'streamId': 'Extension',
    },
  ),
68 69 70 71 72 73 74 75 76 77 78 79 80 81
  FakeVmServiceRequest(
    method: 'registerService',
    args: <String, Object>{
      'service': 'reloadSources',
      'alias': 'FlutterTools',
    }
  )
];

const List<VmServiceExpectation> kAttachExpectations = <VmServiceExpectation>[
  ...kAttachLogExpectations,
  ...kAttachIsolateExpectations,
];

82 83
void main() {
  MockDebugConnection mockDebugConnection;
84
  MockChromeDevice mockChromeDevice;
85
  MockAppConnection mockAppConnection;
86 87 88 89 90 91 92 93
  MockFlutterDevice mockFlutterDevice;
  MockWebDevFS mockWebDevFS;
  MockResidentCompiler mockResidentCompiler;
  MockChrome mockChrome;
  MockChromeConnection mockChromeConnection;
  MockChromeTab mockChromeTab;
  MockWipConnection mockWipConnection;
  MockWipDebugger mockWipDebugger;
94
  MockWebServerDevice mockWebServerDevice;
95
  MockDevice mockDevice;
96
  FakeVmServiceHost fakeVmServiceHost;
97 98
  FileSystem fileSystem;
  ProcessManager processManager;
99 100

  setUp(() {
101 102
    fileSystem = MemoryFileSystem.test();
    processManager = FakeProcessManager.any();
103
    mockDebugConnection = MockDebugConnection();
104
    mockDevice = MockDevice();
105
    mockAppConnection = MockAppConnection();
106 107 108 109 110 111 112 113
    mockFlutterDevice = MockFlutterDevice();
    mockWebDevFS = MockWebDevFS();
    mockResidentCompiler = MockResidentCompiler();
    mockChrome = MockChrome();
    mockChromeConnection = MockChromeConnection();
    mockChromeTab = MockChromeTab();
    mockWipConnection = MockWipConnection();
    mockWipDebugger = MockWipDebugger();
114
    mockWebServerDevice = MockWebServerDevice();
115 116 117 118 119
    when(mockFlutterDevice.devFS).thenReturn(mockWebDevFS);
    when(mockFlutterDevice.device).thenReturn(mockDevice);
    when(mockWebDevFS.connect(any)).thenAnswer((Invocation invocation) async {
      return ConnectionResult(mockAppConnection, mockDebugConnection);
    });
120
    fileSystem.file('.packages').writeAsStringSync('\n');
121 122
  });

123
  void _setupMocks() {
124 125 126
    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('lib/main.dart').createSync(recursive: true);
    fileSystem.file('web/index.html').createSync(recursive: true);
127
    when(mockWebDevFS.update(
128
      mainUri: anyNamed('mainUri'),
129 130 131 132 133 134 135 136 137 138
      target: anyNamed('target'),
      bundle: anyNamed('bundle'),
      firstBuildTime: anyNamed('firstBuildTime'),
      bundleFirstUpload: anyNamed('bundleFirstUpload'),
      generator: anyNamed('generator'),
      fullRestart: anyNamed('fullRestart'),
      dillOutputPath: anyNamed('dillOutputPath'),
      projectRootPath: anyNamed('projectRootPath'),
      pathToReload: anyNamed('pathToReload'),
      invalidatedFiles: anyNamed('invalidatedFiles'),
139
      trackWidgetCreation: anyNamed('trackWidgetCreation'),
140
      packageConfig: anyNamed('packageConfig'),
141
    )).thenAnswer((Invocation _) async {
142
      return UpdateFSReport(success: true,  syncedBytes: 0);
143
    });
144 145 146
    when(mockDebugConnection.vmService).thenAnswer((Invocation invocation) {
      return fakeVmServiceHost.vmService;
    });
147 148 149
    when(mockDebugConnection.onDone).thenAnswer((Invocation invocation) {
      return Completer<void>().future;
    });
150
    when(mockDebugConnection.uri).thenReturn('ws://127.0.0.1/abcd/');
151 152
    when(mockFlutterDevice.devFS).thenReturn(mockWebDevFS);
    when(mockWebDevFS.sources).thenReturn(<Uri>[]);
153
    when(mockWebDevFS.baseUri).thenReturn(Uri.parse('http://localhost:12345'));
154 155 156 157 158 159 160 161 162
    when(mockFlutterDevice.generator).thenReturn(mockResidentCompiler);
    when(mockChrome.chromeConnection).thenReturn(mockChromeConnection);
    when(mockChromeConnection.getTab(any)).thenAnswer((Invocation invocation) async {
      return mockChromeTab;
    });
    when(mockChromeTab.connect()).thenAnswer((Invocation invocation) async {
      return mockWipConnection;
    });
    when(mockWipConnection.debugger).thenReturn(mockWipDebugger);
163 164
  }

165 166
  testUsingContext('runner with web server device does not support debugging without --start-paused', () {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
167 168 169
    when(mockFlutterDevice.device).thenReturn(WebServerDevice(
      logger: BufferLogger.test(),
    ));
170
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
171
    final ResidentRunner profileResidentWebRunner = DwdsWebRunnerFactory().createWebRunner(
172
      mockFlutterDevice,
173 174 175
      flutterProject: FlutterProject.current(),
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      ipv6: true,
176
      stayResident: true,
177
      urlTunneller: null,
178
    ) as ResidentWebRunner;
179 180

    expect(profileResidentWebRunner.debuggingEnabled, false);
181 182

    when(mockFlutterDevice.device).thenReturn(MockChromeDevice());
183

184
    expect(residentWebRunner.debuggingEnabled, true);
185
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
186 187 188 189 190 191
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
192

193 194 195 196
  testUsingContext('runner with web server device supports debugging with --start-paused', () {
    fileSystem.file('.packages')
      ..createSync(recursive: true)
      ..writeAsStringSync('\n');
197
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
198
    _setupMocks();
199 200 201
    when(mockFlutterDevice.device).thenReturn(WebServerDevice(
      logger: BufferLogger.test(),
    ));
202 203 204 205 206 207
    final ResidentRunner profileResidentWebRunner = DwdsWebRunnerFactory().createWebRunner(
      mockFlutterDevice,
      flutterProject: FlutterProject.current(),
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug, startPaused: true),
      ipv6: true,
      stayResident: true,
208
      urlTunneller: null,
209 210
    );

211
    expect(profileResidentWebRunner.uri, mockWebDevFS.baseUri);
212
    expect(profileResidentWebRunner.debuggingEnabled, true);
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
  testUsingContext('profile does not supportsServiceProtocol', () {
    fileSystem.file('.packages')
      ..createSync(recursive: true)
      ..writeAsStringSync('\n');
    final ResidentRunner residentWebRunner = DwdsWebRunnerFactory().createWebRunner(
      mockFlutterDevice,
      flutterProject: FlutterProject.current(),
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      ipv6: true,
      stayResident: true,
      urlTunneller: null,
    ) as ResidentWebRunner;
231
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
232
    when(mockFlutterDevice.device).thenReturn(mockChromeDevice);
233 234
    final ResidentRunner profileResidentWebRunner = DwdsWebRunnerFactory().createWebRunner(
      mockFlutterDevice,
235 236 237
      flutterProject: FlutterProject.current(),
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.profile),
      ipv6: true,
238
      stayResident: true,
239
      urlTunneller: null,
240 241 242 243
    );

    expect(profileResidentWebRunner.supportsServiceProtocol, false);
    expect(residentWebRunner.supportsServiceProtocol, true);
244 245 246 247 248 249
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
250

251 252 253 254 255 256 257 258 259 260 261 262
  testUsingContext('Exits on run if target file does not exist', () async {
    fileSystem.file('.packages')
      ..createSync(recursive: true)
      ..writeAsStringSync('\n');
    final ResidentRunner residentWebRunner = DwdsWebRunnerFactory().createWebRunner(
      mockFlutterDevice,
      flutterProject: FlutterProject.current(),
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      ipv6: true,
      stayResident: true,
      urlTunneller: null,
    ) as ResidentWebRunner;
263
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
264 265
    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file(fileSystem.path.join('web', 'index.html'))
266
      .createSync(recursive: true);
267 268

    expect(await residentWebRunner.run(), 1);
269
    final String absoluteMain = fileSystem.path.absolute(fileSystem.path.join('lib', 'main.dart'));
270
    expect(testLogger.errorText, contains('Tried to run $absoluteMain, but that file does not exist.'));
271 272 273 274 275 276
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
277

278 279 280 281 282
  testUsingContext('Can successfully run and connect to vmservice', () async {
    fileSystem.file('.packages')
      ..createSync(recursive: true)
      ..writeAsStringSync('\n');
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
283
    fakeVmServiceHost = FakeVmServiceHost(requests: kAttachExpectations.toList());
284
    _setupMocks();
285 286
    final FakeStatusLogger fakeStatusLogger = globals.logger as FakeStatusLogger;
    final BufferLogger bufferLogger = asLogger<BufferLogger>(fakeStatusLogger);
287
    final MockStatus status = MockStatus();
288
    fakeStatusLogger.status = status;
289 290 291 292 293 294
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    final DebugConnectionInfo debugConnectionInfo = await connectionInfoCompleter.future;

295
    verify(mockAppConnection.runMain()).called(1);
296
    verify(status.stop()).called(1);
297
    expect(bufferLogger.statusText, contains('Debug service listening on ws://127.0.0.1/abcd/'));
298
    expect(debugConnectionInfo.wsUri.toString(), 'ws://127.0.0.1/abcd/');
299
  }, overrides: <Type, Generator>{
300
    Logger: () => FakeStatusLogger(BufferLogger.test()),
301 302 303 304 305
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
306

307 308
  testUsingContext('WebRunner copies compiled app.dill to cache during startup', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
309 310 311 312 313 314 315 316 317 318
    fakeVmServiceHost = FakeVmServiceHost(requests: kAttachExpectations.toList());
    _setupMocks();

    residentWebRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC');
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

319 320 321 322 323 324 325
    expect(await fileSystem.file(fileSystem.path.join('build', 'cache.dill')).readAsString(), 'ABC');
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
326

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
  // Regression test for https://github.com/flutter/flutter/issues/60613
  testUsingContext('ResidentWebRunner calls appFailedToStart if initial compilation fails', () async {
    _setupMocks();
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
    fileSystem.file(globals.fs.path.join('lib', 'main.dart'))
      .createSync(recursive: true);
    fakeVmServiceHost = FakeVmServiceHost(requests: kAttachExpectations.toList());
    when(mockWebDevFS.update(
      mainUri: anyNamed('mainUri'),
      target: anyNamed('target'),
      bundle: anyNamed('bundle'),
      firstBuildTime: anyNamed('firstBuildTime'),
      bundleFirstUpload: anyNamed('bundleFirstUpload'),
      generator: anyNamed('generator'),
      fullRestart: anyNamed('fullRestart'),
      dillOutputPath: anyNamed('dillOutputPath'),
      projectRootPath: anyNamed('projectRootPath'),
      pathToReload: anyNamed('pathToReload'),
      invalidatedFiles: anyNamed('invalidatedFiles'),
      trackWidgetCreation: anyNamed('trackWidgetCreation'),
      packageConfig: anyNamed('packageConfig'),
    )).thenAnswer((Invocation _) async {
349
      return UpdateFSReport(success: false, syncedBytes: 0);
350 351 352 353 354 355 356 357 358 359 360 361
    });

    expect(await residentWebRunner.run(), 1);
    // Completing this future ensures that the daemon can exit correctly.
    expect(await residentWebRunner.waitForAppToFinish(), 1);
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });

362
  testUsingContext('Can successfully run without an index.html including status warning', () async {
363 364
    fakeVmServiceHost = FakeVmServiceHost(requests: kAttachExpectations.toList());
    _setupMocks();
365
    fileSystem.file(fileSystem.path.join('web', 'index.html'))
366
      .deleteSync();
367
    final ResidentWebRunner residentWebRunner = DwdsWebRunnerFactory().createWebRunner(
368 369 370 371 372 373 374
      mockFlutterDevice,
      flutterProject: FlutterProject.current(),
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      ipv6: true,
      stayResident: false,
      urlTunneller: null,
    ) as ResidentWebRunner;
375 376 377 378

    expect(await residentWebRunner.run(), 0);
    expect(testLogger.statusText,
      contains('This application is not configured to build on the web'));
379 380 381 382 383 384
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
385

386
  testUsingContext('Can successfully run and disconnect with --no-resident', () async {
387
    fakeVmServiceHost = FakeVmServiceHost(requests: kAttachExpectations.toList());
388
    _setupMocks();
389
    final ResidentRunner residentWebRunner = DwdsWebRunnerFactory().createWebRunner(
390
      mockFlutterDevice,
391 392 393 394
      flutterProject: FlutterProject.current(),
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      ipv6: true,
      stayResident: false,
395
      urlTunneller: null,
396
    ) as ResidentWebRunner;
397 398

    expect(await residentWebRunner.run(), 0);
399 400 401 402 403 404
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
405

406 407
  testUsingContext('Listens to stdout and stderr streams before running main', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachLogExpectations,
      FakeVmServiceStreamResponse(
        streamId: 'Stdout',
        event: vm_service.Event(
          timestamp: 0,
          kind: vm_service.EventStreams.kStdout,
          bytes: base64.encode(utf8.encode('THIS MESSAGE IS IMPORTANT'))
        ),
      ),
      FakeVmServiceStreamResponse(
        streamId: 'Stderr',
        event: vm_service.Event(
          timestamp: 0,
          kind: vm_service.EventStreams.kStderr,
          bytes: base64.encode(utf8.encode('SO IS THIS'))
        ),
      ),
      ...kAttachIsolateExpectations,
    ]);
428 429 430 431 432 433 434
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

435
    expect(testLogger.statusText, contains('THIS MESSAGE IS IMPORTANT'));
436
    expect(testLogger.statusText, contains('SO IS THIS'));
437 438 439 440 441 442
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
443

444 445
  testUsingContext('Listens to extension events with structured errors', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    final Map<String, String> extensionData = <String, String>{
      'test': 'data',
      'renderedErrorText': 'error text',
    };
    final Map<String, String> emptyExtensionData = <String, String>{
      'test': 'data',
      'renderedErrorText': '',
    };
    final Map<String, String> nonStructuredErrorData = <String, String>{
      'other': 'other stuff',
    };
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      FakeVmServiceStreamResponse(
        streamId: 'Extension',
        event: vm_service.Event(
          timestamp: 0,
          extensionKind: 'Flutter.Error',
          extensionData: vm_service.ExtensionData.parse(extensionData),
          kind: vm_service.EventStreams.kExtension,
        ),
      ),
      // Empty error text should not break anything.
      FakeVmServiceStreamResponse(
        streamId: 'Extension',
        event: vm_service.Event(
          timestamp: 0,
          extensionKind: 'Flutter.Error',
          extensionData: vm_service.ExtensionData.parse(emptyExtensionData),
          kind: vm_service.EventStreams.kExtension,
        ),
      ),
      // This is not Flutter.Error kind data, so it should not be logged.
      FakeVmServiceStreamResponse(
        streamId: 'Extension',
        event: vm_service.Event(
          timestamp: 0,
          extensionKind: 'Other',
          extensionData: vm_service.ExtensionData.parse(nonStructuredErrorData),
          kind: vm_service.EventStreams.kExtension,
        ),
      ),
    ]);

    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    // Need these to run events, otherwise expect statements below run before
    // structured errors are processed.
    await null;
    await null;
    await null;

    expect(testLogger.statusText, contains('\nerror text'));
    expect(testLogger.statusText, isNot(contains('other stuff')));
505 506 507 508 509 510
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
511

512 513
  testUsingContext('Does not run main with --start-paused', () async {
    final ResidentRunner residentWebRunner = DwdsWebRunnerFactory().createWebRunner(
514
      mockFlutterDevice,
515 516 517
      flutterProject: FlutterProject.current(),
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug, startPaused: true),
      ipv6: true,
518
      stayResident: true,
519
      urlTunneller: null,
520
    ) as ResidentWebRunner;
521
    fakeVmServiceHost = FakeVmServiceHost(requests: kAttachExpectations.toList());
522 523
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
524

525 526 527 528 529 530
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    verifyNever(mockAppConnection.runMain());
531 532 533 534 535 536
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
537

538 539
  testUsingContext('Can hot reload after attaching', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
540 541 542 543 544 545 546 547 548
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'hotRestart',
        jsonResponse: <String, Object>{
          'type': 'Success',
        }
      ),
    ]);
549
    _setupMocks();
550 551 552 553 554 555 556 557 558
    final ChromiumLauncher chromiumLauncher = MockChromeLauncher();
    when(chromiumLauncher.launch(any, cacheDir: anyNamed('cacheDir')))
      .thenAnswer((Invocation invocation) async {
        return mockChrome;
      });
    when(chromiumLauncher.connectedInstance).thenAnswer((Invocation invocation) async {
      return mockChrome;
    });
    when(mockFlutterDevice.device).thenReturn(GoogleChromeDevice(
559
      fileSystem: fileSystem,
560 561 562 563 564 565 566
      chromiumLauncher: chromiumLauncher,
      logger: globals.logger,
      platform: FakePlatform(operatingSystem: 'linux'),
      processManager: FakeProcessManager.any(),
    ));
    when(chromiumLauncher.canFindExecutable()).thenReturn(true);
    chromiumLauncher.testLaunchChromium(mockChrome);
567
    when(mockWebDevFS.update(
568
      mainUri: anyNamed('mainUri'),
569 570 571 572 573 574 575 576 577 578 579
      target: anyNamed('target'),
      bundle: anyNamed('bundle'),
      firstBuildTime: anyNamed('firstBuildTime'),
      bundleFirstUpload: anyNamed('bundleFirstUpload'),
      generator: anyNamed('generator'),
      fullRestart: anyNamed('fullRestart'),
      dillOutputPath: anyNamed('dillOutputPath'),
      trackWidgetCreation: anyNamed('trackWidgetCreation'),
      projectRootPath: anyNamed('projectRootPath'),
      pathToReload: anyNamed('pathToReload'),
      invalidatedFiles: anyNamed('invalidatedFiles'),
580
      packageConfig: anyNamed('packageConfig'),
581
    )).thenAnswer((Invocation invocation) async {
Dan Field's avatar
Dan Field committed
582
      // Generated entrypoint file in temp dir.
583
      expect(invocation.namedArguments[#mainUri].toString(), contains('entrypoint.dart'));
584
      return UpdateFSReport(success: true);
585 586 587 588 589
    });
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
590 591 592 593
    final DebugConnectionInfo debugConnectionInfo = await connectionInfoCompleter.future;

    expect(debugConnectionInfo, isNotNull);

594 595
    final OperationResult result = await residentWebRunner.restart(fullRestart: false);

596
    expect(testLogger.statusText, contains('Restarted application in'));
597 598 599
    expect(result.code, 0);
    verify(mockResidentCompiler.accept()).called(2);
	  // ensure that analytics are sent.
600
    final Map<String, String> config = verify(globals.flutterUsage.sendEvent('hot', 'restart',
601 602 603 604
      parameters: captureAnyNamed('parameters'))).captured.first as Map<String, String>;

    expect(config, allOf(<Matcher>[
      containsPair('cd27', 'web-javascript'),
605
      containsPair('cd28', ''),
606 607 608
      containsPair('cd29', 'false'),
      containsPair('cd30', 'true'),
    ]));
609
    verify(globals.flutterUsage.sendTiming('hot', 'web-incremental-restart', any)).called(1);
610 611
  }, overrides: <Type, Generator>{
    Usage: () => MockFlutterUsage(),
612 613 614 615 616
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
617

618 619
  testUsingContext('Can hot restart after attaching', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
620 621 622 623 624 625 626 627 628
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'hotRestart',
        jsonResponse: <String, Object>{
          'type': 'Success',
        }
      ),
    ]);
629
    _setupMocks();
630 631 632 633 634 635 636 637 638 639
    final ChromiumLauncher chromiumLauncher = MockChromeLauncher();
    when(chromiumLauncher.launch(any, cacheDir: anyNamed('cacheDir')))
      .thenAnswer((Invocation invocation) async {
        return mockChrome;
      });
    when(chromiumLauncher.connectedInstance).thenAnswer((Invocation invocation) async {
      return mockChrome;
    });
    when(chromiumLauncher.canFindExecutable()).thenReturn(true);
    when(mockFlutterDevice.device).thenReturn(GoogleChromeDevice(
640
      fileSystem: fileSystem,
641 642 643 644 645 646
      chromiumLauncher: chromiumLauncher,
      logger: globals.logger,
      platform: FakePlatform(operatingSystem: 'linux'),
      processManager: FakeProcessManager.any(),
    ));
    chromiumLauncher.testLaunchChromium(mockChrome);
647
    Uri entrypointFileUri;
648
    when(mockWebDevFS.update(
649
      mainUri: anyNamed('mainUri'),
650 651 652 653 654 655 656 657 658 659 660
      target: anyNamed('target'),
      bundle: anyNamed('bundle'),
      firstBuildTime: anyNamed('firstBuildTime'),
      bundleFirstUpload: anyNamed('bundleFirstUpload'),
      generator: anyNamed('generator'),
      fullRestart: anyNamed('fullRestart'),
      dillOutputPath: anyNamed('dillOutputPath'),
      trackWidgetCreation: anyNamed('trackWidgetCreation'),
      projectRootPath: anyNamed('projectRootPath'),
      pathToReload: anyNamed('pathToReload'),
      invalidatedFiles: anyNamed('invalidatedFiles'),
661
      packageConfig: anyNamed('packageConfig'),
662
    )).thenAnswer((Invocation invocation) async {
663
      entrypointFileUri = invocation.namedArguments[#mainUri] as Uri;
664
      return UpdateFSReport(success: true);
665 666 667 668 669 670 671 672
    });
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;
    final OperationResult result = await residentWebRunner.restart(fullRestart: true);

673
    // Ensure that generated entrypoint is generated correctly.
674
    expect(entrypointFileUri, isNotNull);
675
    final String entrypointContents = fileSystem.file(entrypointFileUri).readAsStringSync();
676 677 678
    expect(entrypointContents, contains('// Flutter web bootstrap script'));
    expect(entrypointContents, contains("import 'dart:ui' as ui;"));
    expect(entrypointContents, contains('await ui.webOnlyInitializePlatform();'));
679

680
    expect(testLogger.statusText, contains('Restarted application in'));
681 682 683
    expect(result.code, 0);
    verify(mockResidentCompiler.accept()).called(2);
	  // ensure that analytics are sent.
684
    final Map<String, String> config = verify(globals.flutterUsage.sendEvent('hot', 'restart',
685 686 687 688
      parameters: captureAnyNamed('parameters'))).captured.first as Map<String, String>;

    expect(config, allOf(<Matcher>[
      containsPair('cd27', 'web-javascript'),
689
      containsPair('cd28', ''),
690 691 692
      containsPair('cd29', 'false'),
      containsPair('cd30', 'true'),
    ]));
693
    verify(globals.flutterUsage.sendTiming('hot', 'web-incremental-restart', any)).called(1);
694 695
  }, overrides: <Type, Generator>{
    Usage: () => MockFlutterUsage(),
696 697 698 699 700
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
701

702 703
  testUsingContext('Can hot restart after attaching with web-server device', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
704
    fakeVmServiceHost = FakeVmServiceHost(requests :kAttachExpectations);
705 706 707
    _setupMocks();
    when(mockFlutterDevice.device).thenReturn(mockWebServerDevice);
    when(mockWebDevFS.update(
708
      mainUri: anyNamed('mainUri'),
709 710 711 712 713 714 715 716 717 718 719
      target: anyNamed('target'),
      bundle: anyNamed('bundle'),
      firstBuildTime: anyNamed('firstBuildTime'),
      bundleFirstUpload: anyNamed('bundleFirstUpload'),
      generator: anyNamed('generator'),
      fullRestart: anyNamed('fullRestart'),
      dillOutputPath: anyNamed('dillOutputPath'),
      trackWidgetCreation: anyNamed('trackWidgetCreation'),
      projectRootPath: anyNamed('projectRootPath'),
      pathToReload: anyNamed('pathToReload'),
      invalidatedFiles: anyNamed('invalidatedFiles'),
720
      packageConfig: anyNamed('packageConfig'),
721
    )).thenAnswer((Invocation invocation) async {
722
      return UpdateFSReport(success: true);
723 724 725 726 727 728 729 730 731 732 733 734
    });
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;
    final OperationResult result = await residentWebRunner.restart(fullRestart: true);

    expect(testLogger.statusText, contains('Restarted application in'));
    expect(result.code, 0);
    verify(mockResidentCompiler.accept()).called(2);
    // ensure that analytics are sent.
735
    verifyNever(globals.flutterUsage.sendTiming('hot', 'web-incremental-restart', any));
736 737
  }, overrides: <Type, Generator>{
    Usage: () => MockFlutterUsage(),
738 739 740 741 742
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
743

744 745
  testUsingContext('web resident runner is debuggable', () {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
746 747
    fakeVmServiceHost = FakeVmServiceHost(requests: kAttachExpectations.toList());

748
    expect(residentWebRunner.debuggingEnabled, true);
749 750 751 752 753 754
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
755

756 757
  testUsingContext('Exits when initial compile fails', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
758
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
759
    _setupMocks();
760
    when(mockWebDevFS.update(
761
      mainUri: anyNamed('mainUri'),
762 763 764 765 766 767 768 769 770 771
      target: anyNamed('target'),
      bundle: anyNamed('bundle'),
      firstBuildTime: anyNamed('firstBuildTime'),
      bundleFirstUpload: anyNamed('bundleFirstUpload'),
      generator: anyNamed('generator'),
      fullRestart: anyNamed('fullRestart'),
      dillOutputPath: anyNamed('dillOutputPath'),
      projectRootPath: anyNamed('projectRootPath'),
      pathToReload: anyNamed('pathToReload'),
      invalidatedFiles: anyNamed('invalidatedFiles'),
772
      packageConfig: anyNamed('packageConfig'),
773
      trackWidgetCreation: anyNamed('trackWidgetCreation'),
774
    )).thenAnswer((Invocation _) async {
775
      return UpdateFSReport(success: false,  syncedBytes: 0);
776
    });
777
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
778
    unawaited(residentWebRunner.run(
779 780 781
      connectionInfoCompleter: connectionInfoCompleter,
    ));

782
    expect(await residentWebRunner.run(), 1);
783
    verifyNever(globals.flutterUsage.sendTiming('hot', 'web-restart', any));
784 785
  }, overrides: <Type, Generator>{
    Usage: () => MockFlutterUsage(),
786 787 788 789 790
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
791

792 793
  testUsingContext('Faithfully displays stdout messages with leading/trailing spaces', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
794 795 796 797 798 799 800 801 802 803 804 805 806 807
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachLogExpectations,
      FakeVmServiceStreamResponse(
        streamId: 'Stdout',
        event: vm_service.Event(
          timestamp: 0,
          kind: vm_service.EventStreams.kStdout,
          bytes: base64.encode(
            utf8.encode('    This is a message with 4 leading and trailing spaces    '),
          ),
        ),
      ),
      ...kAttachIsolateExpectations,
    ]);
808 809 810 811 812 813 814 815 816
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    expect(testLogger.statusText,
      contains('    This is a message with 4 leading and trailing spaces    '));
817
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
818 819 820 821 822 823
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
824

825 826
  testUsingContext('Fails on compilation errors in hot restart', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
827
    fakeVmServiceHost = FakeVmServiceHost(requests: kAttachExpectations.toList());
828 829
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
830
    unawaited(residentWebRunner.run(
831 832 833
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;
834
    when(mockWebDevFS.update(
835
      mainUri: anyNamed('mainUri'),
836 837 838 839 840 841 842 843 844 845
      target: anyNamed('target'),
      bundle: anyNamed('bundle'),
      firstBuildTime: anyNamed('firstBuildTime'),
      bundleFirstUpload: anyNamed('bundleFirstUpload'),
      generator: anyNamed('generator'),
      fullRestart: anyNamed('fullRestart'),
      dillOutputPath: anyNamed('dillOutputPath'),
      projectRootPath: anyNamed('projectRootPath'),
      pathToReload: anyNamed('pathToReload'),
      invalidatedFiles: anyNamed('invalidatedFiles'),
846
      packageConfig: anyNamed('packageConfig'),
847
      trackWidgetCreation: anyNamed('trackWidgetCreation'),
848
    )).thenAnswer((Invocation _) async {
849
      return UpdateFSReport(success: false,  syncedBytes: 0);
850 851 852 853 854
    });

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

    expect(result.code, 1);
855
    expect(result.message, contains('Failed to recompile application.'));
856
    verifyNever(globals.flutterUsage.sendTiming('hot', 'web-restart', any));
857 858
  }, overrides: <Type, Generator>{
    Usage: () => MockFlutterUsage(),
859 860 861 862 863
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
864

865 866
  testUsingContext('Fails non-fatally on vmservice response error for hot restart', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
867 868 869 870 871 872 873 874 875
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'hotRestart',
        jsonResponse: <String, Object>{
          'type': 'Failed',
        }
      )
    ]);
876 877 878 879 880 881 882 883 884
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    final OperationResult result = await residentWebRunner.restart(fullRestart: false);

885
    expect(result.code, 0);
886 887 888 889 890 891
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
892

893 894
  testUsingContext('Fails fatally on Vm Service error response', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
895 896 897 898 899 900 901 902
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'hotRestart',
        // Failed response,
        errorCode: RPCErrorCodes.kInternalError,
      ),
    ]);
903 904 905 906 907 908 909 910 911
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;
    final OperationResult result = await residentWebRunner.restart(fullRestart: false);

    expect(result.code, 1);
912 913
    expect(result.message,
      contains(RPCErrorCodes.kInternalError.toString()));
914 915 916 917 918 919
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
920

921 922
  testUsingContext('printHelp without details has web warning', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
923
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
924 925
    residentWebRunner.printHelp(details: false);

926 927 928
    expect(testLogger.statusText, contains('Warning'));
    expect(testLogger.statusText, contains('https://flutter.dev/web'));
    expect(testLogger.statusText, isNot(contains('https://flutter.dev/web.')));
929 930 931 932 933 934
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
935

936 937
  testUsingContext('debugDumpApp', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
938 939 940 941 942 943 944 945 946
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'ext.flutter.debugDumpApp',
        args: <String, Object>{
          'isolateId': null,
        },
      ),
    ]);
947 948
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
949
    unawaited(residentWebRunner.run(
950 951 952 953 954
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;
    await residentWebRunner.debugDumpApp();

955
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
956 957 958 959 960 961
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
962

963 964
  testUsingContext('debugDumpLayerTree', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
965 966 967 968 969 970 971 972 973
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'ext.flutter.debugDumpLayerTree',
        args: <String, Object>{
          'isolateId': null,
        },
      ),
    ]);
974 975
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
976
    unawaited(residentWebRunner.run(
977 978 979 980 981
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;
    await residentWebRunner.debugDumpLayerTree();

982
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
983 984 985 986 987 988
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
989

990 991
  testUsingContext('debugDumpRenderTree', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
992 993 994 995 996 997 998 999 1000
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'ext.flutter.debugDumpRenderTree',
        args: <String, Object>{
          'isolateId': null,
        },
      ),
    ]);
1001 1002
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
1003
    unawaited(residentWebRunner.run(
1004 1005 1006 1007 1008
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;
    await residentWebRunner.debugDumpRenderTree();

1009
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1010 1011 1012 1013 1014 1015
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1016

1017 1018
  testUsingContext('debugDumpSemanticsTreeInTraversalOrder', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1019 1020 1021 1022 1023 1024 1025 1026 1027
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'ext.flutter.debugDumpSemanticsTreeInTraversalOrder',
        args: <String, Object>{
          'isolateId': null,
        },
      ),
    ]);
1028 1029
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
1030
    unawaited(residentWebRunner.run(
1031 1032 1033 1034 1035
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;
    await residentWebRunner.debugDumpSemanticsTreeInTraversalOrder();

1036
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1037 1038 1039 1040 1041 1042
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1043

1044 1045
  testUsingContext('debugDumpSemanticsTreeInInverseHitTestOrder', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1046 1047 1048 1049 1050 1051 1052 1053 1054
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'ext.flutter.debugDumpSemanticsTreeInInverseHitTestOrder',
        args: <String, Object>{
          'isolateId': null,
        },
      ),
    ]);
1055 1056
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
1057
    unawaited(residentWebRunner.run(
1058 1059
      connectionInfoCompleter: connectionInfoCompleter,
    ));
1060

1061 1062 1063
    await connectionInfoCompleter.future;
    await residentWebRunner.debugDumpSemanticsTreeInInverseHitTestOrder();

1064
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1065 1066 1067 1068 1069 1070
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1071

1072 1073
  testUsingContext('debugToggleDebugPaintSizeEnabled', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'ext.flutter.debugPaint',
        args: <String, Object>{
          'isolateId': null,
        },
        jsonResponse: <String, Object>{
          'enabled': 'false'
        },
      ),
      const FakeVmServiceRequest(
        method: 'ext.flutter.debugPaint',
        args: <String, Object>{
          'isolateId': null,
          'enabled': 'true',
        },
        jsonResponse: <String, Object>{
          'value': 'true'
        },
      )
    ]);
1096 1097
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
1098
    unawaited(residentWebRunner.run(
1099 1100 1101
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;
1102

1103 1104
    await residentWebRunner.debugToggleDebugPaintSizeEnabled();

1105
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1106 1107 1108 1109 1110 1111
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1112

1113 1114
  testUsingContext('debugTogglePerformanceOverlayOverride', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'ext.flutter.showPerformanceOverlay',
        args: <String, Object>{
          'isolateId': null,
        },
        jsonResponse: <String, Object>{
          'enabled': 'false'
        },
      ),
      const FakeVmServiceRequest(
        method: 'ext.flutter.showPerformanceOverlay',
        args: <String, Object>{
          'isolateId': null,
          'enabled': 'true',
        },
        jsonResponse: <String, Object>{
          'enabled': 'true'
        },
      )
    ]);
1137 1138
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
1139
    unawaited(residentWebRunner.run(
1140 1141 1142 1143 1144 1145
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    await residentWebRunner.debugTogglePerformanceOverlayOverride();

1146
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1147 1148 1149 1150 1151 1152
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1153

1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 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
  testUsingContext('debugToggleInvertOversizedImagesOverride', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'ext.flutter.invertOversizedImages',
        args: <String, Object>{
          'isolateId': null,
        },
        jsonResponse: <String, Object>{
          'enabled': 'false'
        },
      ),
      const FakeVmServiceRequest(
        method: 'ext.flutter.invertOversizedImages',
        args: <String, Object>{
          'isolateId': null,
          'enabled': 'true',
        },
        jsonResponse: <String, Object>{
          'enabled': 'true'
        },
      )
    ]);
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    await residentWebRunner.debugToggleInvertOversizedImages();

    expect(fakeVmServiceHost.hasRemainingExpectations, false);
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });

1195 1196
  testUsingContext('debugToggleWidgetInspector', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'ext.flutter.inspector.show',
        args: <String, Object>{
          'isolateId': null,
        },
        jsonResponse: <String, Object>{
          'enabled': 'false'
        },
      ),
      const FakeVmServiceRequest(
        method: 'ext.flutter.inspector.show',
        args: <String, Object>{
          'isolateId': null,
          'enabled': 'true',
        },
        jsonResponse: <String, Object>{
          'enabled': 'true'
        },
      )
    ]);
1219 1220
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
1221
    unawaited(residentWebRunner.run(
1222 1223 1224 1225 1226 1227
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    await residentWebRunner.debugToggleWidgetInspector();

1228
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1229 1230 1231 1232 1233 1234
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1235

1236 1237
  testUsingContext('debugToggleProfileWidgetBuilds', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'ext.flutter.profileWidgetBuilds',
        args: <String, Object>{
          'isolateId': null,
        },
        jsonResponse: <String, Object>{
          'enabled': 'false'
        },
      ),
      const FakeVmServiceRequest(
        method: 'ext.flutter.profileWidgetBuilds',
        args: <String, Object>{
          'isolateId': null,
          'enabled': 'true',
        },
        jsonResponse: <String, Object>{
          'enabled': 'true'
        },
      )
    ]);
1260 1261
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
1262
    unawaited(residentWebRunner.run(
1263 1264 1265 1266 1267 1268
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    await residentWebRunner.debugToggleProfileWidgetBuilds();

1269
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1270 1271 1272 1273 1274 1275
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1276

1277 1278
  testUsingContext('debugTogglePlatform', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'ext.flutter.platformOverride',
        args: <String, Object>{
          'isolateId': null,
        },
        jsonResponse: <String, Object>{
          'value': 'iOS'
        },
      ),
      const FakeVmServiceRequest(
        method: 'ext.flutter.platformOverride',
        args: <String, Object>{
          'isolateId': null,
          'value': 'fuchsia',
        },
        jsonResponse: <String, Object>{
          'value': 'fuchsia'
        },
      ),
    ]);
1301 1302 1303 1304 1305 1306 1307 1308 1309
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    await residentWebRunner.debugTogglePlatform();

1310 1311 1312
    expect(testLogger.statusText,
      contains('Switched operating system to fuchsia'));
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1313 1314 1315 1316 1317 1318
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1319

1320 1321
  testUsingContext('debugToggleBrightness', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
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
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
      const FakeVmServiceRequest(
        method: 'ext.flutter.brightnessOverride',
        args: <String, Object>{
          'isolateId': null,
        },
        jsonResponse: <String, Object>{
          'value': 'Brightness.light'
        },
      ),
      const FakeVmServiceRequest(
        method: 'ext.flutter.brightnessOverride',
        args: <String, Object>{
          'isolateId': null,
          'value': 'Brightness.dark',
        },
        jsonResponse: <String, Object>{
          'value': 'Brightness.dark'
        },
      ),
    ]);
    _setupMocks();
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    await residentWebRunner.debugToggleBrightness();

    expect(testLogger.statusText,
      contains('Changed brightness to Brightness.dark.'));
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1356 1357 1358 1359 1360 1361
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1362

1363 1364
  testUsingContext('cleanup of resources is safe to call multiple times', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1365 1366 1367
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
    ]);
1368 1369
    _setupMocks();
    bool debugClosed = false;
1370
    when(mockDevice.stopApp(any, userIdentifier: anyNamed('userIdentifier'))).thenAnswer((Invocation invocation) async {
1371 1372 1373 1374
      if (debugClosed) {
        throw StateError('debug connection closed twice');
      }
      debugClosed = true;
1375
      return true;
1376 1377
    });
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
1378
    unawaited(residentWebRunner.run(
1379 1380 1381 1382 1383 1384
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    await residentWebRunner.exit();
    await residentWebRunner.exit();
1385 1386

    verifyNever(mockDebugConnection.close());
1387
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1388 1389 1390 1391 1392 1393
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1394

1395 1396
  testUsingContext('cleans up Chrome if tab is closed', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1397 1398 1399
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
    ]);
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
    _setupMocks();
    final Completer<void> onDone = Completer<void>();
    when(mockDebugConnection.onDone).thenAnswer((Invocation invocation) {
      return onDone.future;
    });
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    final Future<int> result = residentWebRunner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    );
    await connectionInfoCompleter.future;
    onDone.complete();

    await result;
1413
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1414 1415 1416 1417 1418 1419
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1420

1421 1422
  testUsingContext('Prints target and device name on run', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1423 1424 1425
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachExpectations,
    ]);
1426
    _setupMocks();
1427
    when(mockDevice.name).thenReturn('Chromez');
1428
    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
1429
    unawaited(residentWebRunner.run(
1430 1431 1432 1433
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

1434
    expect(testLogger.statusText, contains(
1435
      'Launching ${fileSystem.path.join('lib', 'main.dart')} on '
1436 1437 1438
      'Chromez in debug mode',
    ));
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1439 1440 1441 1442 1443 1444
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1445

1446
  testUsingContext('Sends launched app.webLaunchUrl event for Chrome device', () async {
1447 1448
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
      ...kAttachLogExpectations,
1449
      ...kAttachIsolateExpectations,
1450
    ]);
1451
    _setupMocks();
1452 1453 1454 1455 1456 1457 1458 1459 1460
    final ChromiumLauncher chromiumLauncher = MockChromeLauncher();
    when(chromiumLauncher.launch(any, cacheDir: anyNamed('cacheDir')))
      .thenAnswer((Invocation invocation) async {
        return mockChrome;
      });
    when(chromiumLauncher.connectedInstance).thenAnswer((Invocation invocation) async {
      return mockChrome;
    });
    when(mockFlutterDevice.device).thenReturn(GoogleChromeDevice(
1461
      fileSystem: fileSystem,
1462 1463 1464 1465 1466 1467
      chromiumLauncher: chromiumLauncher,
      logger: globals.logger,
      platform: FakePlatform(operatingSystem: 'linux'),
      processManager: FakeProcessManager.any(),
    ));
    when(chromiumLauncher.canFindExecutable()).thenReturn(true);
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
    when(mockWebDevFS.create()).thenAnswer((Invocation invocation) async {
      return Uri.parse('http://localhost:8765/app/');
    });
    final MockChrome chrome = MockChrome();
    final MockChromeConnection mockChromeConnection = MockChromeConnection();
    final MockChromeTab mockChromeTab = MockChromeTab();
    final MockWipConnection mockWipConnection = MockWipConnection();
    when(mockChromeConnection.getTab(any)).thenAnswer((Invocation invocation) async {
      return mockChromeTab;
    });
    when(mockChromeTab.connect()).thenAnswer((Invocation invocation) async {
      return mockWipConnection;
    });
    when(chrome.chromeConnection).thenReturn(mockChromeConnection);
1482
    chromiumLauncher.testLaunchChromium(chrome);
1483

1484
    final FakeStatusLogger fakeStatusLogger = globals.logger as FakeStatusLogger;
1485
    final MockStatus mockStatus = MockStatus();
1486
    fakeStatusLogger.status = mockStatus;
1487 1488 1489 1490 1491 1492
    final ResidentWebRunner runner = DwdsWebRunnerFactory().createWebRunner(
      mockFlutterDevice,
      flutterProject: FlutterProject.current(),
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      ipv6: true,
      stayResident: true,
1493
      urlTunneller: null,
1494
    ) as ResidentWebRunner;
1495 1496 1497 1498 1499 1500 1501 1502

    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(runner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    // Ensure we got the URL and that it was already launched.
1503
    expect(asLogger<BufferLogger>(fakeStatusLogger).eventText,
1504 1505 1506 1507 1508 1509 1510 1511
      contains(json.encode(<String, Object>{
        'name': 'app.webLaunchUrl',
        'args': <String, Object>{
          'url': 'http://localhost:8765/app/',
          'launched': true,
        },
      },
    )));
1512
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1513
  }, overrides: <Type, Generator>{
1514
    Logger: () => FakeStatusLogger(BufferLogger.test()),
1515 1516 1517 1518 1519
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1520

1521
  testUsingContext('Sends unlaunched app.webLaunchUrl event for Web Server device', () async {
1522
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1523
    _setupMocks();
1524 1525 1526
    when(mockFlutterDevice.device).thenReturn(WebServerDevice(
      logger: globals.logger,
    ));
1527 1528 1529
    when(mockWebDevFS.create()).thenAnswer((Invocation invocation) async {
      return Uri.parse('http://localhost:8765/app/');
    });
1530

1531
    final FakeStatusLogger fakeStatusLogger = globals.logger as FakeStatusLogger;
1532
    final MockStatus mockStatus = MockStatus();
1533
    fakeStatusLogger.status = mockStatus;
1534 1535 1536 1537 1538 1539
    final ResidentWebRunner runner = DwdsWebRunnerFactory().createWebRunner(
      mockFlutterDevice,
      flutterProject: FlutterProject.current(),
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
      ipv6: true,
      stayResident: true,
1540
      urlTunneller: null,
1541
    ) as ResidentWebRunner;
1542 1543 1544 1545 1546 1547 1548 1549

    final Completer<DebugConnectionInfo> connectionInfoCompleter = Completer<DebugConnectionInfo>();
    unawaited(runner.run(
      connectionInfoCompleter: connectionInfoCompleter,
    ));
    await connectionInfoCompleter.future;

    // Ensure we got the URL and that it was not already launched.
1550
    expect(asLogger<BufferLogger>(fakeStatusLogger).eventText,
1551 1552 1553 1554 1555 1556 1557 1558
      contains(json.encode(<String, Object>{
        'name': 'app.webLaunchUrl',
        'args': <String, Object>{
          'url': 'http://localhost:8765/app/',
          'launched': false,
        },
      },
    )));
1559
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1560
  }, overrides: <Type, Generator>{
1561
    Logger: () => FakeStatusLogger(BufferLogger.test()),
1562 1563 1564 1565 1566
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1567

1568 1569
  testUsingContext('Successfully turns WebSocketException into ToolExit', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1570
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1571 1572
    _setupMocks();

1573 1574
    when(mockWebDevFS.connect(any))
      .thenThrow(const WebSocketException());
1575

1576
    await expectLater(residentWebRunner.run, throwsToolExit());
1577
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1578 1579 1580 1581 1582 1583
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1584

1585 1586
  testUsingContext('Successfully turns AppConnectionException into ToolExit', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1587
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1588 1589
    _setupMocks();

1590 1591
    when(mockWebDevFS.connect(any))
      .thenThrow(AppConnectionException(''));
1592

1593
    await expectLater(residentWebRunner.run, throwsToolExit());
1594
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1595 1596 1597 1598 1599 1600
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1601

1602 1603
  testUsingContext('Successfully turns ChromeDebugError into ToolExit', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1604 1605
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
    _setupMocks();
1606

1607 1608
    when(mockWebDevFS.connect(any))
      .thenThrow(ChromeDebugException(<String, dynamic>{}));
1609

1610
    await expectLater(residentWebRunner.run, throwsToolExit());
1611
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1612 1613 1614 1615 1616 1617
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1618

1619 1620
  testUsingContext('Rethrows unknown Exception type from dwds', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1621
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1622
    _setupMocks();
1623
    when(mockWebDevFS.connect(any)).thenThrow(Exception());
1624

1625
    await expectLater(residentWebRunner.run, throwsException);
1626
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1627 1628 1629 1630 1631 1632
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
1633

1634 1635
  testUsingContext('Rethrows unknown Error type from dwds tooling', () async {
    final ResidentRunner residentWebRunner = setUpResidentRunner(mockFlutterDevice);
1636
    fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1637
    _setupMocks();
1638
    final FakeStatusLogger fakeStatusLogger = globals.logger as FakeStatusLogger;
1639
    final MockStatus mockStatus = MockStatus();
1640
    fakeStatusLogger.status = mockStatus;
1641

1642
    when(mockWebDevFS.connect(any)).thenThrow(StateError(''));
1643

1644
    await expectLater(residentWebRunner.run, throwsStateError);
1645
    verify(mockStatus.stop()).called(1);
1646
    expect(fakeVmServiceHost.hasRemainingExpectations, false);
1647
  }, overrides: <Type, Generator>{
1648
    Logger: () => FakeStatusLogger(BufferLogger(
1649 1650 1651 1652 1653
      terminal: AnsiTerminal(
        stdio: null,
        platform: const LocalPlatform(),
      ),
      outputPreferences: OutputPreferences.test(),
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
    )),
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Pub: () => MockPub(),
    Platform: () => FakePlatform(operatingSystem: 'linux', environment: <String, String>{}),
  });
}

ResidentRunner setUpResidentRunner(FlutterDevice flutterDevice) {
  return DwdsWebRunnerFactory().createWebRunner(
    flutterDevice,
    flutterProject: FlutterProject.current(),
    debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
    ipv6: true,
    stayResident: true,
    urlTunneller: null,
  ) as ResidentWebRunner;
1671 1672
}

1673
class MockChromeLauncher extends Mock implements ChromiumLauncher {}
1674
class MockFlutterUsage extends Mock implements Usage {}
1675
class MockChromeDevice extends Mock implements ChromiumDevice {}
1676
class MockDebugConnection extends Mock implements DebugConnection {}
1677
class MockAppConnection extends Mock implements AppConnection {}
1678
class MockVmService extends Mock implements VmService {}
1679
class MockStatus extends Mock implements Status {}
1680
class MockFlutterDevice extends Mock implements FlutterDevice {}
1681
class MockWebDevFS extends Mock implements WebDevFS {}
1682
class MockResidentCompiler extends Mock implements ResidentCompiler {}
1683
class MockChrome extends Mock implements Chromium {}
1684 1685 1686 1687
class MockChromeConnection extends Mock implements ChromeConnection {}
class MockChromeTab extends Mock implements ChromeTab {}
class MockWipConnection extends Mock implements WipConnection {}
class MockWipDebugger extends Mock implements WipDebugger {}
1688
class MockWebServerDevice extends Mock implements WebServerDevice {}
1689
class MockDevice extends Mock implements Device {}
1690
class MockPub extends Mock implements Pub {}