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

import 'dart:async';

7
import 'package:file/memory.dart';
8
import 'package:flutter_tools/src/android/android_device.dart';
9
import 'package:flutter_tools/src/application_package.dart';
10
import 'package:flutter_tools/src/artifacts.dart';
11
import 'package:flutter_tools/src/base/common.dart';
12
import 'package:flutter_tools/src/base/dds.dart';
13
import 'package:flutter_tools/src/base/file_system.dart';
14
import 'package:flutter_tools/src/base/io.dart';
15
import 'package:flutter_tools/src/base/logger.dart';
16 17
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/signals.dart';
18
import 'package:flutter_tools/src/base/terminal.dart';
19
import 'package:flutter_tools/src/build_info.dart';
20 21
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/attach.dart';
22
import 'package:flutter_tools/src/compile.dart';
23
import 'package:flutter_tools/src/device.dart';
24
import 'package:flutter_tools/src/device_port_forwarder.dart';
25
import 'package:flutter_tools/src/ios/application_package.dart';
26
import 'package:flutter_tools/src/ios/devices.dart';
27
import 'package:flutter_tools/src/macos/macos_ipad_device.dart';
28
import 'package:flutter_tools/src/mdns_discovery.dart';
29
import 'package:flutter_tools/src/project.dart';
30
import 'package:flutter_tools/src/reporting/reporting.dart';
31
import 'package:flutter_tools/src/resident_runner.dart';
32
import 'package:flutter_tools/src/run_hot.dart';
33
import 'package:flutter_tools/src/vmservice.dart';
34
import 'package:multicast_dns/multicast_dns.dart';
35
import 'package:test/fake.dart';
36
import 'package:unified_analytics/unified_analytics.dart';
37
import 'package:vm_service/vm_service.dart' as vm_service;
38

39 40
import '../../src/common.dart';
import '../../src/context.dart';
41
import '../../src/fake_devices.dart';
42
import '../../src/test_flutter_command_runner.dart';
43

44 45 46 47 48 49 50 51 52 53
class FakeStdio extends Fake implements Stdio {
  @override
  bool stdinHasTerminal = false;
}

class FakeProcessInfo extends Fake implements ProcessInfo {
  @override
  int maxRss = 0;
}

54
void main() {
55 56 57 58
  tearDown(() {
    MacOSDesignedForIPadDevices.allowDiscovery = false;
  });

59
  group('attach', () {
60 61
    late StreamLogger logger;
    late FileSystem testFileSystem;
62
    late TestDeviceManager testDeviceManager;
63 64 65 66 67 68
    late Artifacts artifacts;
    late Stdio stdio;
    late Terminal terminal;
    late Signals signals;
    late Platform platform;
    late ProcessInfo processInfo;
69

70
    setUp(() {
71
      Cache.disableLocking();
72
      logger = StreamLogger();
73 74
      platform = FakePlatform();
      testFileSystem = MemoryFileSystem.test();
75
      testFileSystem.directory('lib').createSync();
76
      testFileSystem.file(testFileSystem.path.join('lib', 'main.dart')).createSync();
77
      artifacts = Artifacts.test(fileSystem: testFileSystem);
78 79 80 81
      stdio = FakeStdio();
      terminal = FakeTerminal();
      signals = Signals.test();
      processInfo = FakeProcessInfo();
82
      testDeviceManager = TestDeviceManager(logger: logger);
83 84
    });

85
    group('with one device and no specified target file', () {
86 87
      const int devicePort = 499;
      const int hostPort = 42;
88
      final int future = DateTime.now().add(const Duration(days: 1)).millisecondsSinceEpoch;
89

90 91 92 93
      late FakeDeviceLogReader fakeLogReader;
      late RecordingPortForwarder portForwarder;
      late FakeDartDevelopmentService fakeDds;
      late FakeAndroidDevice device;
94 95

      setUp(() {
96
        fakeLogReader = FakeDeviceLogReader();
97
        portForwarder = RecordingPortForwarder(hostPort);
98
        fakeDds = FakeDartDevelopmentService();
99 100 101
        device = FakeAndroidDevice(id: '1')
          ..portForwarder = portForwarder
          ..dds = fakeDds;
102 103
      });

104
      tearDown(() {
105
        fakeLogReader.dispose();
106
      });
107

108
      testUsingContext('succeeds with iOS device with protocol discovery', () async {
109 110
        final FakeIOSDevice device = FakeIOSDevice(
          portForwarder: portForwarder,
111
          majorSdkVersion: 12,
112 113 114 115 116 117
          onGetLogReader: () {
            fakeLogReader.addLine('Foo');
            fakeLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:$devicePort');
            return fakeLogReader;
          },
        );
118
        testDeviceManager.devices = <Device>[device];
119 120
        final Completer<void> completer = Completer<void>();
        final StreamSubscription<String> loggerSubscription = logger.stream.listen((String message) {
121 122
          if (message == '[verbose] VM Service URL on device: http://127.0.0.1:$devicePort') {
            // The "VM Service URL on device" message is output by the ProtocolDiscovery when it found the VM Service.
123 124 125
            completer.complete();
          }
        });
126 127 128 129 130 131 132 133
        final FakeHotRunner hotRunner = FakeHotRunner();
        hotRunner.onAttach = (
          Completer<DebugConnectionInfo>? connectionInfoCompleter,
          Completer<void>? appStartedCompleter,
          bool allowExistingDdsInstance,
          bool enableDevTools,
        ) async => 0;
        hotRunner.exited = false;
134
        hotRunner.isWaitingForVmService = false;
135 136 137 138 139
        final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
          ..hotRunner = hotRunner;

        await createTestCommandRunner(AttachCommand(
          hotRunnerFactory: hotRunnerFactory,
140 141 142 143 144 145 146 147
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        )).run(<String>['attach']);
148 149 150 151 152 153 154 155 156 157 158
        await completer.future;

        expect(portForwarder.devicePort, devicePort);
        expect(portForwarder.hostPort, hostPort);

        await fakeLogReader.dispose();
        await loggerSubscription.cancel();
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
        ProcessManager: () => FakeProcessManager.any(),
        Logger: () => logger,
159
        DeviceManager: () => testDeviceManager,
160 161 162 163 164
        MDnsVmServiceDiscovery: () => MDnsVmServiceDiscovery(
          mdnsClient: FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}),
          preliminaryMDnsClient: FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}),
          logger: logger,
          flutterUsage: TestUsage(),
165
          analytics: NoOpAnalytics(),
166 167 168
        ),
      });

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
      testUsingContext('restores terminal to singleCharMode == false on command exit', () async {
        final FakeIOSDevice device = FakeIOSDevice(
          portForwarder: portForwarder,
          majorSdkVersion: 12,
          onGetLogReader: () {
            fakeLogReader.addLine('Foo');
            fakeLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:$devicePort');
            return fakeLogReader;
          },
        );
        testDeviceManager.devices = <Device>[device];
        final Completer<void> completer = Completer<void>();
        final StreamSubscription<String> loggerSubscription = logger.stream.listen((String message) {
          if (message == '[verbose] VM Service URL on device: http://127.0.0.1:$devicePort') {
            // The "VM Service URL on device" message is output by the ProtocolDiscovery when it found the VM Service.
            completer.complete();
          }
        });
        final FakeHotRunner hotRunner = FakeHotRunner();
        hotRunner.onAttach = (
          Completer<DebugConnectionInfo>? connectionInfoCompleter,
          Completer<void>? appStartedCompleter,
          bool allowExistingDdsInstance,
          bool enableDevTools,
        ) async {
          appStartedCompleter?.complete();
          return 0;
        };
        hotRunner.exited = false;
        hotRunner.isWaitingForVmService = false;
        final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
          ..hotRunner = hotRunner;

        await createTestCommandRunner(AttachCommand(
          hotRunnerFactory: hotRunnerFactory,
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        )).run(<String>['attach']);
        await Future.wait<void>(<Future<void>>[
          completer.future,
          fakeLogReader.dispose(),
          loggerSubscription.cancel(),
        ]);

        expect(terminal.singleCharMode, isFalse);
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
        ProcessManager: () => FakeProcessManager.any(),
        Logger: () => logger,
        DeviceManager: () => testDeviceManager,
        MDnsVmServiceDiscovery: () => MDnsVmServiceDiscovery(
          mdnsClient: FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}),
          preliminaryMDnsClient: FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}),
          logger: logger,
          flutterUsage: TestUsage(),
229
          analytics: NoOpAnalytics(),
230 231 232 233
        ),
        Signals: () => FakeSignals(),
      });

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 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
      testUsingContext('local engine artifacts are passed to runner', () async {
        const String localEngineSrc = '/path/to/local/engine/src';
        const String localEngineDir = 'host_debug_unopt';
        testFileSystem.directory('$localEngineSrc/out/$localEngineDir').createSync(recursive: true);
        final FakeIOSDevice device = FakeIOSDevice(
          portForwarder: portForwarder,
          majorSdkVersion: 12,
          onGetLogReader: () {
            fakeLogReader.addLine('Foo');
            fakeLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:$devicePort');
            return fakeLogReader;
          },
        );
        testDeviceManager.devices = <Device>[device];
        final Completer<void> completer = Completer<void>();
        final StreamSubscription<String> loggerSubscription = logger.stream.listen((String message) {
          if (message == '[verbose] VM Service URL on device: http://127.0.0.1:$devicePort') {
            // The "VM Service URL on device" message is output by the ProtocolDiscovery when it found the VM Service.
            completer.complete();
          }
        });
        final FakeHotRunner hotRunner = FakeHotRunner();
        hotRunner.onAttach = (
          Completer<DebugConnectionInfo>? connectionInfoCompleter,
          Completer<void>? appStartedCompleter,
          bool allowExistingDdsInstance,
          bool enableDevTools,
        ) async => 0;
        hotRunner.exited = false;
        hotRunner.isWaitingForVmService = false;
        bool passedArtifactTest = false;
        final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
          ..hotRunner = hotRunner
          .._artifactTester = (Artifacts artifacts) {
            expect(artifacts, isA<CachedLocalEngineArtifacts>());
            // expecting this to be true ensures this test ran
            passedArtifactTest = true;
          };

        await createTestCommandRunner(AttachCommand(
          hotRunnerFactory: hotRunnerFactory,
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
282
        )).run(<String>['attach', '--local-engine-src-path=$localEngineSrc', '--local-engine=$localEngineDir', '--local-engine-host=$localEngineDir']);
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        await Future.wait<void>(<Future<void>>[
          completer.future,
          fakeLogReader.dispose(),
          loggerSubscription.cancel(),
        ]);
        expect(passedArtifactTest, isTrue);
      }, overrides: <Type, Generator>{
        Artifacts: () => artifacts,
        DeviceManager: () => testDeviceManager,
        FileSystem: () => testFileSystem,
        Logger: () => logger,
        MDnsVmServiceDiscovery: () => MDnsVmServiceDiscovery(
          mdnsClient: FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}),
          preliminaryMDnsClient: FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}),
          logger: logger,
          flutterUsage: TestUsage(),
299
          analytics: NoOpAnalytics(),
300 301 302 303
        ),
        ProcessManager: () => FakeProcessManager.empty(),
      });

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
      testUsingContext('succeeds with iOS device with mDNS', () async {
        final FakeIOSDevice device = FakeIOSDevice(
          portForwarder: portForwarder,
          majorSdkVersion: 16,
          onGetLogReader: () {
            fakeLogReader.addLine('Foo');
            fakeLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:$devicePort');
            return fakeLogReader;
          },
        );
        testDeviceManager.devices = <Device>[device];
        final FakeHotRunner hotRunner = FakeHotRunner();
        hotRunner.onAttach = (
          Completer<DebugConnectionInfo>? connectionInfoCompleter,
          Completer<void>? appStartedCompleter,
          bool allowExistingDdsInstance,
          bool enableDevTools,
        ) async => 0;
        hotRunner.exited = false;
323
        hotRunner.isWaitingForVmService = false;
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
        final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
          ..hotRunner = hotRunner;

        await createTestCommandRunner(AttachCommand(
          hotRunnerFactory: hotRunnerFactory,
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        )).run(<String>['attach']);
        await fakeLogReader.dispose();

        expect(portForwarder.devicePort, devicePort);
        expect(portForwarder.hostPort, hostPort);
        expect(hotRunnerFactory.devices, hasLength(1));
        final FlutterDevice flutterDevice = hotRunnerFactory.devices.first;
343 344
        final Uri? vmServiceUri = await flutterDevice.vmServiceUris?.first;
        expect(vmServiceUri.toString(), 'http://127.0.0.1:$hostPort/xyz/');
345 346 347 348 349 350
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
        ProcessManager: () => FakeProcessManager.any(),
        Logger: () => logger,
        DeviceManager: () => testDeviceManager,
        MDnsVmServiceDiscovery: () => MDnsVmServiceDiscovery(
351
          mdnsClient: FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}),
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
          preliminaryMDnsClient: FakeMDnsClient(
            <PtrResourceRecord>[
              PtrResourceRecord('foo', future, domainName: 'bar'),
            ],
            <String, List<SrvResourceRecord>>{
              'bar': <SrvResourceRecord>[
                SrvResourceRecord('bar', future, port: devicePort, weight: 1, priority: 1, target: 'appId'),
              ],
            },
            txtResponse: <String, List<TxtResourceRecord>>{
              'bar': <TxtResourceRecord>[
                TxtResourceRecord('bar', future, text: 'authCode=xyz\n'),
              ],
            },
          ),
          logger: logger,
          flutterUsage: TestUsage(),
369
          analytics: NoOpAnalytics(),
370 371 372
        ),
      });

373
      testUsingContext('succeeds with iOS device with mDNS wireless device', () async {
374 375 376
        final FakeIOSDevice device = FakeIOSDevice(
          portForwarder: portForwarder,
          majorSdkVersion: 16,
377
          connectionInterface: DeviceConnectionInterface.wireless,
378 379 380 381 382 383 384 385 386 387
        );
        testDeviceManager.devices = <Device>[device];
        final FakeHotRunner hotRunner = FakeHotRunner();
        hotRunner.onAttach = (
          Completer<DebugConnectionInfo>? connectionInfoCompleter,
          Completer<void>? appStartedCompleter,
          bool allowExistingDdsInstance,
          bool enableDevTools,
        ) async => 0;
        hotRunner.exited = false;
388
        hotRunner.isWaitingForVmService = false;
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
        final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
          ..hotRunner = hotRunner;

        await createTestCommandRunner(AttachCommand(
          hotRunnerFactory: hotRunnerFactory,
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        )).run(<String>['attach']);
        await fakeLogReader.dispose();

        expect(portForwarder.devicePort, null);
        expect(portForwarder.hostPort, hostPort);
        expect(hotRunnerFactory.devices, hasLength(1));

        final FlutterDevice flutterDevice = hotRunnerFactory.devices.first;
409 410
        final Uri? vmServiceUri = await flutterDevice.vmServiceUris?.first;
        expect(vmServiceUri.toString(), 'http://111.111.111.111:123/xyz/');
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
        ProcessManager: () => FakeProcessManager.any(),
        Logger: () => logger,
        DeviceManager: () => testDeviceManager,
        MDnsVmServiceDiscovery: () => MDnsVmServiceDiscovery(
          mdnsClient: FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}),
          preliminaryMDnsClient: FakeMDnsClient(
            <PtrResourceRecord>[
              PtrResourceRecord('foo', future, domainName: 'srv-foo'),
            ],
            <String, List<SrvResourceRecord>>{
              'srv-foo': <SrvResourceRecord>[
                SrvResourceRecord('srv-foo', future, port: 123, weight: 1, priority: 1, target: 'target-foo'),
              ],
            },
            ipResponse: <String, List<IPAddressResourceRecord>>{
              'target-foo': <IPAddressResourceRecord>[
                IPAddressResourceRecord('target-foo', 0, address: InternetAddress.tryParse('111.111.111.111')!),
              ],
            },
            txtResponse: <String, List<TxtResourceRecord>>{
              'srv-foo': <TxtResourceRecord>[
                TxtResourceRecord('srv-foo', future, text: 'authCode=xyz\n'),
              ],
            },
          ),
          logger: logger,
          flutterUsage: TestUsage(),
440
          analytics: NoOpAnalytics(),
441 442 443
        ),
      });

444
      testUsingContext('succeeds with iOS device with mDNS wireless device with debug-port', () async {
445 446 447
        final FakeIOSDevice device = FakeIOSDevice(
          portForwarder: portForwarder,
          majorSdkVersion: 16,
448
          connectionInterface: DeviceConnectionInterface.wireless,
449 450 451 452 453 454 455 456 457 458
        );
        testDeviceManager.devices = <Device>[device];
        final FakeHotRunner hotRunner = FakeHotRunner();
        hotRunner.onAttach = (
          Completer<DebugConnectionInfo>? connectionInfoCompleter,
          Completer<void>? appStartedCompleter,
          bool allowExistingDdsInstance,
          bool enableDevTools,
        ) async => 0;
        hotRunner.exited = false;
459
        hotRunner.isWaitingForVmService = false;
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
        final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
          ..hotRunner = hotRunner;

        await createTestCommandRunner(AttachCommand(
          hotRunnerFactory: hotRunnerFactory,
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        )).run(<String>['attach', '--debug-port', '123']);
        await fakeLogReader.dispose();

        expect(portForwarder.devicePort, null);
        expect(portForwarder.hostPort, hostPort);
        expect(hotRunnerFactory.devices, hasLength(1));

        final FlutterDevice flutterDevice = hotRunnerFactory.devices.first;
480 481
        final Uri? vmServiceUri = await flutterDevice.vmServiceUris?.first;
        expect(vmServiceUri.toString(), 'http://111.111.111.111:123/xyz/');
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
        ProcessManager: () => FakeProcessManager.any(),
        Logger: () => logger,
        DeviceManager: () => testDeviceManager,
        MDnsVmServiceDiscovery: () => MDnsVmServiceDiscovery(
          mdnsClient: FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}),
          preliminaryMDnsClient: FakeMDnsClient(
            <PtrResourceRecord>[
              PtrResourceRecord('bar', future, domainName: 'srv-bar'),
              PtrResourceRecord('foo', future, domainName: 'srv-foo'),
            ],
            <String, List<SrvResourceRecord>>{
              'srv-bar': <SrvResourceRecord>[
                SrvResourceRecord('srv-bar', future, port: 321, weight: 1, priority: 1, target: 'target-bar'),
              ],
              'srv-foo': <SrvResourceRecord>[
                SrvResourceRecord('srv-foo', future, port: 123, weight: 1, priority: 1, target: 'target-foo'),
              ],
            },
            ipResponse: <String, List<IPAddressResourceRecord>>{
              'target-foo': <IPAddressResourceRecord>[
                IPAddressResourceRecord('target-foo', 0, address: InternetAddress.tryParse('111.111.111.111')!),
              ],
            },
            txtResponse: <String, List<TxtResourceRecord>>{
              'srv-foo': <TxtResourceRecord>[
                TxtResourceRecord('srv-foo', future, text: 'authCode=xyz\n'),
              ],
            },
          ),
          logger: logger,
          flutterUsage: TestUsage(),
515
          analytics: NoOpAnalytics(),
516 517 518
        ),
      });

519
      testUsingContext('succeeds with iOS device with mDNS wireless device with debug-url', () async {
520 521 522
        final FakeIOSDevice device = FakeIOSDevice(
          portForwarder: portForwarder,
          majorSdkVersion: 16,
523
          connectionInterface: DeviceConnectionInterface.wireless,
524 525 526 527 528 529 530 531 532 533
        );
        testDeviceManager.devices = <Device>[device];
        final FakeHotRunner hotRunner = FakeHotRunner();
        hotRunner.onAttach = (
          Completer<DebugConnectionInfo>? connectionInfoCompleter,
          Completer<void>? appStartedCompleter,
          bool allowExistingDdsInstance,
          bool enableDevTools,
        ) async => 0;
        hotRunner.exited = false;
534
        hotRunner.isWaitingForVmService = false;
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
        final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
          ..hotRunner = hotRunner;

        await createTestCommandRunner(AttachCommand(
          hotRunnerFactory: hotRunnerFactory,
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        )).run(<String>['attach', '--debug-url', 'https://0.0.0.0:123']);
        await fakeLogReader.dispose();

        expect(portForwarder.devicePort, null);
        expect(portForwarder.hostPort, hostPort);
        expect(hotRunnerFactory.devices, hasLength(1));

        final FlutterDevice flutterDevice = hotRunnerFactory.devices.first;
555 556
        final Uri? vmServiceUri = await flutterDevice.vmServiceUris?.first;
        expect(vmServiceUri.toString(), 'http://111.111.111.111:123/xyz/');
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
        ProcessManager: () => FakeProcessManager.any(),
        Logger: () => logger,
        DeviceManager: () => testDeviceManager,
        MDnsVmServiceDiscovery: () => MDnsVmServiceDiscovery(
          mdnsClient: FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}),
          preliminaryMDnsClient: FakeMDnsClient(
            <PtrResourceRecord>[
              PtrResourceRecord('bar', future, domainName: 'srv-bar'),
              PtrResourceRecord('foo', future, domainName: 'srv-foo'),
            ],
            <String, List<SrvResourceRecord>>{
              'srv-bar': <SrvResourceRecord>[
                SrvResourceRecord('srv-bar', future, port: 321, weight: 1, priority: 1, target: 'target-bar'),
              ],
              'srv-foo': <SrvResourceRecord>[
                SrvResourceRecord('srv-foo', future, port: 123, weight: 1, priority: 1, target: 'target-foo'),
              ],
            },
            ipResponse: <String, List<IPAddressResourceRecord>>{
              'target-foo': <IPAddressResourceRecord>[
                IPAddressResourceRecord('target-foo', 0, address: InternetAddress.tryParse('111.111.111.111')!),
              ],
            },
            txtResponse: <String, List<TxtResourceRecord>>{
              'srv-foo': <TxtResourceRecord>[
                TxtResourceRecord('srv-foo', future, text: 'authCode=xyz\n'),
              ],
            },
          ),
588 589
          logger: logger,
          flutterUsage: TestUsage(),
590
          analytics: NoOpAnalytics(),
591 592 593
        ),
      });

594
      testUsingContext('finds VM Service port and forwards', () async {
595 596
        device.onGetLogReader = () {
          fakeLogReader.addLine('Foo');
597
          fakeLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:$devicePort');
598 599
          return fakeLogReader;
        };
600
        testDeviceManager.devices = <Device>[device];
601 602
        final Completer<void> completer = Completer<void>();
        final StreamSubscription<String> loggerSubscription = logger.stream.listen((String message) {
603 604
          if (message == '[verbose] VM Service URL on device: http://127.0.0.1:$devicePort') {
            // The "VM Service URL on device" message is output by the ProtocolDiscovery when it found the VM Service.
605 606 607
            completer.complete();
          }
        });
608 609 610 611 612 613 614 615 616
        final Future<void> task = createTestCommandRunner(AttachCommand(
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        )).run(<String>['attach']);
617
        await completer.future;
618 619 620 621

        expect(portForwarder.devicePort, devicePort);
        expect(portForwarder.hostPort, hostPort);

622
        await fakeLogReader.dispose();
623 624
        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
625 626
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
627
        ProcessManager: () => FakeProcessManager.any(),
628
        Logger: () => logger,
629
        DeviceManager: () => testDeviceManager,
630 631
      });

632
      testUsingContext('Fails with tool exit on bad VmService uri', () async {
633 634
        device.onGetLogReader = () {
          fakeLogReader.addLine('Foo');
635
          fakeLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:$devicePort');
636 637 638
          fakeLogReader.dispose();
          return fakeLogReader;
        };
639
        testDeviceManager.devices = <Device>[device];
640 641 642 643 644 645 646 647 648
        expect(() => createTestCommandRunner(AttachCommand(
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        )).run(<String>['attach']), throwsToolExit());
649 650
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
651
        ProcessManager: () => FakeProcessManager.any(),
652
        Logger: () => logger,
653
        DeviceManager: () => testDeviceManager,
654 655
      });

656
      testUsingContext('accepts filesystem parameters', () async {
657 658
        device.onGetLogReader = () {
          fakeLogReader.addLine('Foo');
659
          fakeLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:$devicePort');
660 661
          return fakeLogReader;
        };
662
        testDeviceManager.devices = <Device>[device];
663 664 665 666 667 668

        const String filesystemScheme = 'foo';
        const String filesystemRoot = '/build-output/';
        const String projectRoot = '/build-output/project-root';
        const String outputDill = '/tmp/output.dill';

669 670
        final FakeHotRunner hotRunner = FakeHotRunner();
        hotRunner.onAttach = (
671 672
          Completer<DebugConnectionInfo>? connectionInfoCompleter,
          Completer<void>? appStartedCompleter,
673 674 675 676
          bool allowExistingDdsInstance,
          bool enableDevTools,
        ) async => 0;
        hotRunner.exited = false;
677
        hotRunner.isWaitingForVmService = false;
678 679 680

        final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
          ..hotRunner = hotRunner;
681

682
        final AttachCommand command = AttachCommand(
683
          hotRunnerFactory: hotRunnerFactory,
684 685 686 687 688 689 690
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
691 692 693 694 695 696 697 698 699 700 701
        );
        await createTestCommandRunner(command).run(<String>[
          'attach',
          '--filesystem-scheme',
          filesystemScheme,
          '--filesystem-root',
          filesystemRoot,
          '--project-root',
          projectRoot,
          '--output-dill',
          outputDill,
702
          '-v', // enables verbose logging
703 704
        ]);

705
        // Validate the attach call built a fake runner with the right
706
        // project root and output dill.
707 708 709
        expect(hotRunnerFactory.projectRootPath, projectRoot);
        expect(hotRunnerFactory.dillOutputPath, outputDill);
        expect(hotRunnerFactory.devices, hasLength(1));
710 711 712

        // Validate that the attach call built a flutter device with the right
        // output dill, filesystem scheme, and filesystem root.
713
        final FlutterDevice flutterDevice = hotRunnerFactory.devices.first;
714

715 716
        expect(flutterDevice.buildInfo.fileSystemScheme, filesystemScheme);
        expect(flutterDevice.buildInfo.fileSystemRoots, const <String>[filesystemRoot]);
717 718
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
719
        ProcessManager: () => FakeProcessManager.any(),
720
        DeviceManager: () => testDeviceManager,
721
      });
722

723
      testUsingContext('exits when ipv6 is specified and debug-port is not on non-iOS device', () async {
724
        testDeviceManager.devices = <Device>[device];
725

726 727 728 729 730 731 732 733 734
        final AttachCommand command = AttachCommand(
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        );
735 736 737
        await expectLater(
          createTestCommandRunner(command).run(<String>['attach', '--ipv6']),
          throwsToolExit(
738
            message: 'When the --debug-port or --debug-url is unknown, this command determines '
739 740 741 742 743
                     'the value of --ipv6 on its own.',
          ),
        );
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
744
        ProcessManager: () => FakeProcessManager.any(),
745
        DeviceManager: () => testDeviceManager,
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
      });

      testUsingContext('succeeds when ipv6 is specified and debug-port is not on iOS device', () async {
        final FakeIOSDevice device = FakeIOSDevice(
          portForwarder: portForwarder,
          majorSdkVersion: 12,
          onGetLogReader: () {
            fakeLogReader.addLine('Foo');
            fakeLogReader.addLine('The Dart VM service is listening on http://[::1]:$devicePort');
            return fakeLogReader;
          },
        );
        testDeviceManager.devices = <Device>[device];
        final Completer<void> completer = Completer<void>();
        final StreamSubscription<String> loggerSubscription = logger.stream.listen((String message) {
          if (message == '[verbose] VM Service URL on device: http://[::1]:$devicePort') {
            // The "VM Service URL on device" message is output by the ProtocolDiscovery when it found the VM Service.
            completer.complete();
          }
        });
        final FakeHotRunner hotRunner = FakeHotRunner();
        hotRunner.onAttach = (
          Completer<DebugConnectionInfo>? connectionInfoCompleter,
          Completer<void>? appStartedCompleter,
          bool allowExistingDdsInstance,
          bool enableDevTools,
        ) async => 0;
        hotRunner.exited = false;
        hotRunner.isWaitingForVmService = false;
        final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
          ..hotRunner = hotRunner;

        await createTestCommandRunner(AttachCommand(
          hotRunnerFactory: hotRunnerFactory,
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        )).run(<String>['attach', '--ipv6']);
        await completer.future;

        expect(portForwarder.devicePort, devicePort);
        expect(portForwarder.hostPort, hostPort);

        await fakeLogReader.dispose();
        await loggerSubscription.cancel();
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
        ProcessManager: () => FakeProcessManager.any(),
        Logger: () => logger,
        DeviceManager: () => testDeviceManager,
      });
801

802
      testUsingContext('exits when vm-service-port is specified and debug-port is not', () async {
803 804
        device.onGetLogReader = () {
          fakeLogReader.addLine('Foo');
805
          fakeLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:$devicePort');
806 807
          return fakeLogReader;
        };
808
        testDeviceManager.devices = <Device>[device];
809

810 811 812 813 814 815 816 817 818
        final AttachCommand command = AttachCommand(
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        );
819
        await expectLater(
820
          createTestCommandRunner(command).run(<String>['attach', '--vm-service-port', '100']),
821
          throwsToolExit(
822
            message: 'When the --debug-port or --debug-url is unknown, this command does not use '
823
                     'the value of --vm-service-port.',
824 825 826 827
          ),
        );
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
828
        ProcessManager: () => FakeProcessManager.any(),
829
        DeviceManager: () => testDeviceManager,
830
      },);
831
    });
832

833
    group('forwarding to given port', () {
834 835
      const int devicePort = 499;
      const int hostPort = 42;
836 837
      late RecordingPortForwarder portForwarder;
      late FakeAndroidDevice device;
838

839
      setUp(() {
840
        final FakeDartDevelopmentService fakeDds = FakeDartDevelopmentService();
841 842 843 844
        portForwarder = RecordingPortForwarder(hostPort);
        device = FakeAndroidDevice(id: '1')
          ..portForwarder = portForwarder
          ..dds = fakeDds;
845
      });
846

847
      testUsingContext('succeeds in ipv4 mode', () async {
848
        testDeviceManager.devices = <Device>[device];
849

850 851 852 853 854 855 856 857
        final Completer<void> completer = Completer<void>();
        final StreamSubscription<String> loggerSubscription = logger.stream.listen((String message) {
          if (message == '[verbose] Connecting to service protocol: http://127.0.0.1:42/') {
            // Wait until resident_runner.dart tries to connect.
            // There's nothing to connect _to_, so that's as far as we care to go.
            completer.complete();
          }
        });
858 859 860 861 862 863 864 865 866
        final Future<void> task = createTestCommandRunner(AttachCommand(
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        ))
867 868
          .run(<String>['attach', '--debug-port', '$devicePort']);
        await completer.future;
869 870
        expect(portForwarder.devicePort, devicePort);
        expect(portForwarder.hostPort, hostPort);
871 872 873

        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
874 875
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
876
        ProcessManager: () => FakeProcessManager.any(),
877
        Logger: () => logger,
878
        DeviceManager: () => testDeviceManager,
879 880 881
      });

      testUsingContext('succeeds in ipv6 mode', () async {
882
        testDeviceManager.devices = <Device>[device];
883

884 885 886 887 888 889 890 891
        final Completer<void> completer = Completer<void>();
        final StreamSubscription<String> loggerSubscription = logger.stream.listen((String message) {
          if (message == '[verbose] Connecting to service protocol: http://[::1]:42/') {
            // Wait until resident_runner.dart tries to connect.
            // There's nothing to connect _to_, so that's as far as we care to go.
            completer.complete();
          }
        });
892 893 894 895 896 897 898 899 900
        final Future<void> task = createTestCommandRunner(AttachCommand(
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        ))
901 902
          .run(<String>['attach', '--debug-port', '$devicePort', '--ipv6']);
        await completer.future;
903 904 905

        expect(portForwarder.devicePort, devicePort);
        expect(portForwarder.hostPort, hostPort);
906 907 908

        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
909 910
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
911
        ProcessManager: () => FakeProcessManager.any(),
912
        Logger: () => logger,
913
        DeviceManager: () => testDeviceManager,
914 915
      });

916
      testUsingContext('skips in ipv4 mode with a provided VM Service port', () async {
917
        testDeviceManager.devices = <Device>[device];
918

919 920 921 922 923 924 925 926
        final Completer<void> completer = Completer<void>();
        final StreamSubscription<String> loggerSubscription = logger.stream.listen((String message) {
          if (message == '[verbose] Connecting to service protocol: http://127.0.0.1:42/') {
            // Wait until resident_runner.dart tries to connect.
            // There's nothing to connect _to_, so that's as far as we care to go.
            completer.complete();
          }
        });
927 928 929 930 931 932 933 934 935
        final Future<void> task = createTestCommandRunner(AttachCommand(
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        )).run(
936 937 938 939
          <String>[
            'attach',
            '--debug-port',
            '$devicePort',
940
            '--vm-service-port',
941
            '$hostPort',
942 943 944
            // Ensure DDS doesn't use hostPort by binding to a random port.
            '--dds-port',
            '0',
945
          ],
946
        );
947
        await completer.future;
948 949
        expect(portForwarder.devicePort, null);
        expect(portForwarder.hostPort, 42);
950 951 952

        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
953 954
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
955
        ProcessManager: () => FakeProcessManager.any(),
956
        Logger: () => logger,
957
        DeviceManager: () => testDeviceManager,
958 959
      });

960
      testUsingContext('skips in ipv6 mode with a provided VM Service port', () async {
961
        testDeviceManager.devices = <Device>[device];
962

963 964 965 966 967 968 969 970
        final Completer<void> completer = Completer<void>();
        final StreamSubscription<String> loggerSubscription = logger.stream.listen((String message) {
          if (message == '[verbose] Connecting to service protocol: http://[::1]:42/') {
            // Wait until resident_runner.dart tries to connect.
            // There's nothing to connect _to_, so that's as far as we care to go.
            completer.complete();
          }
        });
971 972 973 974 975 976 977 978 979
        final Future<void> task = createTestCommandRunner(AttachCommand(
          stdio: stdio,
          logger: logger,
          terminal: terminal,
          signals: signals,
          platform: platform,
          processInfo: processInfo,
          fileSystem: testFileSystem,
        )).run(
980 981 982 983
          <String>[
            'attach',
            '--debug-port',
            '$devicePort',
984
            '--vm-service-port',
985 986
            '$hostPort',
            '--ipv6',
987 988 989
            // Ensure DDS doesn't use hostPort by binding to a random port.
            '--dds-port',
            '0',
990
          ],
991
        );
992
        await completer.future;
993 994
        expect(portForwarder.devicePort, null);
        expect(portForwarder.hostPort, 42);
995 996 997

        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
998 999
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
1000
        ProcessManager: () => FakeProcessManager.any(),
1001
        Logger: () => logger,
1002
        DeviceManager: () => testDeviceManager,
1003 1004
      });
    });
1005 1006

    testUsingContext('exits when no device connected', () async {
1007 1008 1009 1010 1011 1012 1013 1014 1015
      final AttachCommand command = AttachCommand(
        stdio: stdio,
        logger: logger,
        terminal: terminal,
        signals: signals,
        platform: platform,
        processInfo: processInfo,
        fileSystem: testFileSystem,
      );
1016 1017
      await expectLater(
        createTestCommandRunner(command).run(<String>['attach']),
Dan Field's avatar
Dan Field committed
1018
        throwsToolExit(),
1019
      );
1020
      expect(testLogger.statusText, containsIgnoringWhitespace('No supported devices connected'));
1021 1022
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
1023
      ProcessManager: () => FakeProcessManager.any(),
1024
      DeviceManager: () => testDeviceManager,
1025
    });
1026

1027
    testUsingContext('fails when targeted device is not Android with --device-user', () async {
1028
      final FakeIOSDevice device = FakeIOSDevice();
1029
      testDeviceManager.devices = <Device>[device];
1030 1031 1032 1033 1034 1035 1036 1037 1038
      expect(createTestCommandRunner(AttachCommand(
        stdio: stdio,
        logger: logger,
        terminal: terminal,
        signals: signals,
        platform: platform,
        processInfo: processInfo,
        fileSystem: testFileSystem,
      )).run(<String>[
1039 1040 1041 1042 1043 1044 1045
        'attach',
        '--device-user',
        '10',
      ]), throwsToolExit(message: '--device-user is only supported for Android'));
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
      ProcessManager: () => FakeProcessManager.any(),
1046
      DeviceManager: () => testDeviceManager,
1047 1048
    });

1049
    testUsingContext('exits when multiple devices connected', () async {
1050 1051 1052 1053 1054 1055 1056 1057 1058
      final AttachCommand command = AttachCommand(
        stdio: stdio,
        logger: logger,
        terminal: terminal,
        signals: signals,
        platform: platform,
        processInfo: processInfo,
        fileSystem: testFileSystem,
      );
1059 1060 1061 1062
      testDeviceManager.devices = <Device>[
        FakeAndroidDevice(id: 'xx1'),
        FakeAndroidDevice(id: 'yy2'),
      ];
1063 1064
      await expectLater(
        createTestCommandRunner(command).run(<String>['attach']),
Dan Field's avatar
Dan Field committed
1065
        throwsToolExit(),
1066
      );
1067
      expect(testLogger.statusText, containsIgnoringWhitespace('More than one device'));
1068 1069
      expect(testLogger.statusText, contains('xx1'));
      expect(testLogger.statusText, contains('yy2'));
1070
      expect(MacOSDesignedForIPadDevices.allowDiscovery, isTrue);
1071 1072
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
1073
      ProcessManager: () => FakeProcessManager.any(),
1074 1075
      DeviceManager: () => testDeviceManager,
      AnsiTerminal: () => FakeTerminal(stdinHasTerminal: false),
1076
    });
1077 1078

    testUsingContext('Catches service disappeared error', () async {
1079 1080 1081 1082 1083 1084 1085
      final FakeAndroidDevice device = FakeAndroidDevice(id: '1')
        ..portForwarder = const NoOpDevicePortForwarder()
        ..onGetLogReader = () => NoOpDeviceLogReader('test');
      final FakeHotRunner hotRunner = FakeHotRunner();
      final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
        ..hotRunner = hotRunner;
      hotRunner.onAttach = (
1086 1087
        Completer<DebugConnectionInfo>? connectionInfoCompleter,
        Completer<void>? appStartedCompleter,
1088 1089 1090
        bool allowExistingDdsInstance,
        bool enableDevTools,
      ) async {
1091 1092
        await null;
        throw vm_service.RPCError('flutter._listViews', RPCErrorCodes.kServiceDisappeared, '');
1093
      };
1094

1095
      testDeviceManager.devices = <Device>[device];
1096 1097
      testFileSystem.file('lib/main.dart').createSync();

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
      final AttachCommand command = AttachCommand(
        hotRunnerFactory: hotRunnerFactory,
        stdio: stdio,
        logger: logger,
        terminal: terminal,
        signals: signals,
        platform: platform,
        processInfo: processInfo,
        fileSystem: testFileSystem,
      );
1108 1109 1110 1111 1112 1113
      await expectLater(createTestCommandRunner(command).run(<String>[
        'attach',
      ]), throwsToolExit(message: 'Lost connection to device.'));
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
      ProcessManager: () => FakeProcessManager.any(),
1114
      DeviceManager: () => testDeviceManager,
1115 1116 1117
    });

    testUsingContext('Does not catch generic RPC error', () async {
1118 1119 1120 1121 1122 1123 1124 1125
      final FakeAndroidDevice device = FakeAndroidDevice(id: '1')
        ..portForwarder = const NoOpDevicePortForwarder()
        ..onGetLogReader = () => NoOpDeviceLogReader('test');
      final FakeHotRunner hotRunner = FakeHotRunner();
      final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
        ..hotRunner = hotRunner;

      hotRunner.onAttach = (
1126 1127
        Completer<DebugConnectionInfo>? connectionInfoCompleter,
        Completer<void>? appStartedCompleter,
1128 1129 1130
        bool allowExistingDdsInstance,
        bool enableDevTools,
      ) async {
1131 1132
        await null;
        throw vm_service.RPCError('flutter._listViews', RPCErrorCodes.kInvalidParams, '');
1133 1134
      };

1135
      testDeviceManager.devices = <Device>[device];
1136 1137
      testFileSystem.file('lib/main.dart').createSync();

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
      final AttachCommand command = AttachCommand(
        hotRunnerFactory: hotRunnerFactory,
        stdio: stdio,
        logger: logger,
        terminal: terminal,
        signals: signals,
        platform: platform,
        processInfo: processInfo,
        fileSystem: testFileSystem,
      );
1148 1149 1150 1151 1152 1153
      await expectLater(createTestCommandRunner(command).run(<String>[
        'attach',
      ]), throwsA(isA<vm_service.RPCError>()));
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
      ProcessManager: () => FakeProcessManager.any(),
1154
      DeviceManager: () => testDeviceManager,
1155
    });
1156 1157 1158
  });
}

1159
class FakeHotRunner extends Fake implements HotRunner {
1160
  late Future<int> Function(Completer<DebugConnectionInfo>?, Completer<void>?, bool, bool) onAttach;
1161 1162 1163 1164 1165

  @override
  bool exited = false;

  @override
1166
  bool isWaitingForVmService = true;
1167 1168 1169

  @override
  Future<int> attach({
1170 1171
    Completer<DebugConnectionInfo>? connectionInfoCompleter,
    Completer<void>? appStartedCompleter,
1172 1173
    bool allowExistingDdsInstance = false,
    bool enableDevTools = false,
1174
    bool needsFullRestart = true,
1175 1176 1177
  }) {
    return onAttach(connectionInfoCompleter, appStartedCompleter, allowExistingDdsInstance, enableDevTools);
  }
1178 1179 1180 1181 1182 1183 1184 1185 1186

  @override
  bool supportsServiceProtocol = false;

  @override
  bool stayResident = true;

  @override
  void printHelp({required bool details}) {}
1187 1188 1189
}

class FakeHotRunnerFactory extends Fake implements HotRunnerFactory {
1190 1191 1192 1193
  late HotRunner hotRunner;
  String? dillOutputPath;
  String? projectRootPath;
  late List<FlutterDevice> devices;
1194
  void Function(Artifacts artifacts)? _artifactTester;
1195 1196 1197 1198

  @override
  HotRunner build(
    List<FlutterDevice> devices, {
1199 1200
    required String target,
    required DebuggingOptions debuggingOptions,
1201
    bool benchmarkMode = false,
1202
    File? applicationBinary,
1203
    bool hostIsIde = false,
1204 1205 1206
    String? projectRootPath,
    String? packagesFilePath,
    String? dillOutputPath,
1207 1208
    bool stayResident = true,
    bool ipv6 = false,
1209
    FlutterProject? flutterProject,
1210
    Analytics? analytics,
1211
  }) {
1212 1213 1214 1215 1216
    if (_artifactTester != null) {
      for (final FlutterDevice device in devices) {
        _artifactTester!((device.generator! as DefaultResidentCompiler).artifacts);
      }
    }
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    this.devices = devices;
    this.dillOutputPath = dillOutputPath;
    this.projectRootPath = projectRootPath;
    return hotRunner;
  }
}

class RecordingPortForwarder implements DevicePortForwarder {
  RecordingPortForwarder([this.hostPort]);

1227 1228
  int? devicePort;
  int? hostPort;
1229 1230 1231 1232 1233

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

  @override
1234
  Future<int> forward(int devicePort, {int? hostPort}) async {
1235 1236
    this.devicePort = devicePort;
    this.hostPort ??= hostPort;
1237
    return this.hostPort!;
1238 1239 1240 1241 1242 1243 1244 1245
  }

  @override
  List<ForwardedPort> get forwardedPorts => <ForwardedPort>[];

  @override
  Future<void> unforward(ForwardedPort forwardedPort) async { }
}
1246 1247 1248 1249 1250 1251 1252 1253

class StreamLogger extends Logger {
  @override
  bool get isVerbose => true;

  @override
  void printError(
    String message, {
1254 1255 1256 1257 1258 1259
    StackTrace? stackTrace,
    bool? emphasis,
    TerminalColor? color,
    int? indent,
    int? hangingIndent,
    bool? wrap,
1260
  }) {
1261 1262 1263 1264 1265 1266 1267
    hadErrorOutput = true;
    _log('[stderr] $message');
  }

  @override
  void printWarning(
    String message, {
1268 1269 1270 1271 1272
    bool? emphasis,
    TerminalColor? color,
    int? indent,
    int? hangingIndent,
    bool? wrap,
1273
    bool fatal = true,
1274
  }) {
1275
    hadWarningOutput = hadWarningOutput || fatal;
1276 1277 1278 1279 1280 1281
    _log('[stderr] $message');
  }

  @override
  void printStatus(
    String message, {
1282 1283 1284 1285 1286 1287
    bool? emphasis,
    TerminalColor? color,
    bool? newline,
    int? indent,
    int? hangingIndent,
    bool? wrap,
1288 1289 1290 1291
  }) {
    _log('[stdout] $message');
  }

1292 1293 1294
  @override
  void printBox(
    String message, {
1295
    String? title,
1296 1297 1298 1299 1300 1301 1302 1303
  }) {
    if (title == null) {
      _log('[stdout] $message');
    } else {
      _log('[stdout] $title: $message');
    }
  }

1304 1305 1306 1307 1308 1309 1310 1311
  @override
  void printTrace(String message) {
    _log('[verbose] $message');
  }

  @override
  Status startProgress(
    String message, {
1312 1313
    Duration? timeout,
    String? progressId,
1314
    bool multilineOutput = false,
1315
    bool includeTiming = true,
1316 1317 1318
    int progressIndicatorPadding = kDefaultStatusPadding,
  }) {
    _log('[progress] $message');
1319 1320 1321
    return SilentStatus(
      stopwatch: Stopwatch(),
    )..start();
1322 1323
  }

1324
  @override
1325
  Status startSpinner({
1326 1327 1328
    VoidCallback? onFinish,
    Duration? timeout,
    SlowWarningCallback? slowWarningCallback,
1329
    TerminalColor? warningColor,
1330
  }) {
1331 1332 1333 1334 1335 1336
    return SilentStatus(
      stopwatch: Stopwatch(),
      onFinish: onFinish,
    )..start();
  }

1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
  bool _interrupt = false;

  void interrupt() {
    _interrupt = true;
  }

  final StreamController<String> _controller = StreamController<String>.broadcast();

  void _log(String message) {
    _controller.add(message);
    if (_interrupt) {
      _interrupt = false;
      throw const LoggerInterrupted();
    }
  }

  Stream<String> get stream => _controller.stream;
1354 1355

  @override
1356
  void sendEvent(String name, [Map<String, dynamic>? args]) { }
1357 1358 1359 1360 1361 1362

  @override
  bool get supportsColor => throw UnimplementedError();

  @override
  bool get hasTerminal => false;
1363 1364

  @override
1365
  void clear() => _log('[stdout] ${terminal.clearScreen()}\n');
1366 1367 1368

  @override
  Terminal get terminal => Terminal.test();
1369 1370 1371 1372 1373 1374 1375 1376
}

class LoggerInterrupted implements Exception {
  const LoggerInterrupted();
}

Future<void> expectLoggerInterruptEndsTask(Future<void> task, StreamLogger logger) async {
  logger.interrupt(); // an exception during the task should cause it to fail...
1377 1378 1379 1380
  await expectLater(
    () => task,
    throwsA(isA<ToolExit>().having((ToolExit error) => error.exitCode, 'exitCode', 2)),
  );
1381
}
1382

1383 1384 1385 1386 1387 1388 1389
class FakeDartDevelopmentService extends Fake implements DartDevelopmentService {
  @override
  Future<void> get done => noopCompleter.future;
  final Completer<void> noopCompleter = Completer<void>();

  @override
  Future<void> startDartDevelopmentService(
1390
    Uri vmServiceUri, {
1391 1392 1393 1394
    required Logger logger,
    int? hostPort,
    bool? ipv6,
    bool? disableServiceAuthCodes,
1395
    bool cacheStartupProfile = false,
1396 1397 1398 1399 1400
  }) async {}

  @override
  Uri get uri => Uri.parse('http://localhost:8181');
}
1401

1402
class FakeAndroidDevice extends Fake implements AndroidDevice {
1403
  FakeAndroidDevice({required this.id});
1404 1405

  @override
1406
  late DartDevelopmentService dds;
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422

  @override
  final String id;

  @override
  String get name => 'd$id';

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

  @override
  Future<String> get sdkNameAndVersion async => 'Android 46';

  @override
  Future<String> get targetPlatformDisplayName async => 'android';

1423 1424 1425
  @override
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.android_arm;

1426 1427 1428 1429
  @override
  DeviceConnectionInterface get connectionInterface =>
      DeviceConnectionInterface.attached;

1430 1431 1432
  @override
  bool isSupported() => true;

1433 1434 1435
  @override
  bool get isConnected => true;

1436 1437 1438 1439 1440 1441 1442 1443
  @override
  bool get supportsHotRestart => true;

  @override
  bool get supportsFlutterExit => false;

  @override
  bool isSupportedForProject(FlutterProject flutterProject) => true;
1444 1445

  @override
1446
  DevicePortForwarder? portForwarder;
1447

1448
  DeviceLogReader Function()? onGetLogReader;
1449 1450 1451

  @override
  FutureOr<DeviceLogReader> getLogReader({
1452
    ApplicationPackage? app,
1453 1454
    bool includePastLogs = false,
  }) {
1455 1456 1457 1458 1459 1460
    if (onGetLogReader == null) {
      throw UnimplementedError(
        'Called getLogReader but no onGetLogReader callback was supplied in the constructor to FakeAndroidDevice.',
      );
    }
    return onGetLogReader!();
1461 1462 1463 1464 1465 1466 1467
  }

  @override
  final PlatformType platformType = PlatformType.android;

  @override
  Category get category => Category.mobile;
1468 1469 1470

  @override
  bool get ephemeral => true;
1471
}
1472 1473

class FakeIOSDevice extends Fake implements IOSDevice {
1474 1475 1476
  FakeIOSDevice({
    DevicePortForwarder? portForwarder,
    this.onGetLogReader,
1477
    this.connectionInterface = DeviceConnectionInterface.attached,
1478
    this.majorSdkVersion = 0,
1479
  }) : _portForwarder = portForwarder;
1480 1481

  final DevicePortForwarder? _portForwarder;
1482 1483 1484 1485
  @override
  int majorSdkVersion;

  @override
1486 1487 1488 1489 1490
  final DeviceConnectionInterface connectionInterface;

  @override
  bool get isWirelesslyConnected =>
      connectionInterface == DeviceConnectionInterface.wireless;
1491 1492

  @override
1493
  DevicePortForwarder get portForwarder => _portForwarder!;
1494 1495

  @override
1496
  DartDevelopmentService get dds => throw UnimplementedError('getter dds not implemented');
1497

1498
  final DeviceLogReader Function()? onGetLogReader;
1499 1500 1501

  @override
  DeviceLogReader getLogReader({
1502
    IOSApp? app,
1503
    bool includePastLogs = false,
1504
    bool usingCISystem = false,
1505 1506 1507 1508 1509 1510 1511 1512
  }) {
    if (onGetLogReader == null) {
      throw UnimplementedError(
        'Called getLogReader but no onGetLogReader callback was supplied in the constructor to FakeIOSDevice',
      );
    }
    return onGetLogReader!();
  }
1513 1514 1515 1516 1517 1518 1519 1520 1521

  @override
  final String name = 'name';

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

  @override
  final PlatformType platformType = PlatformType.ios;
1522 1523 1524 1525 1526 1527

  @override
  bool isSupported() => true;

  @override
  bool isSupportedForProject(FlutterProject project) => true;
1528 1529 1530

  @override
  bool get isConnected => true;
1531 1532 1533

  @override
  bool get ephemeral => true;
1534
}
1535 1536 1537 1538

class FakeMDnsClient extends Fake implements MDnsClient {
  FakeMDnsClient(this.ptrRecords, this.srvResponse, {
    this.txtResponse = const <String, List<TxtResourceRecord>>{},
1539
    this.ipResponse = const <String, List<IPAddressResourceRecord>>{},
1540 1541 1542 1543 1544 1545
    this.osErrorOnStart = false,
  });

  final List<PtrResourceRecord> ptrRecords;
  final Map<String, List<SrvResourceRecord>> srvResponse;
  final Map<String, List<TxtResourceRecord>> txtResponse;
1546
  final Map<String, List<IPAddressResourceRecord>> ipResponse;
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
  final bool osErrorOnStart;

  @override
  Future<void> start({
    InternetAddress? listenAddress,
    NetworkInterfacesFactory? interfacesFactory,
    int mDnsPort = 5353,
    InternetAddress? mDnsAddress,
  }) async {
    if (osErrorOnStart) {
      throw const OSError('Operation not supported on socket', 102);
    }
  }

  @override
  Stream<T> lookup<T extends ResourceRecord>(
    ResourceRecordQuery query, {
    Duration timeout = const Duration(seconds: 5),
  }) {
1566
    if (T == PtrResourceRecord && query.fullyQualifiedName == MDnsVmServiceDiscovery.dartVmServiceName) {
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
      return Stream<PtrResourceRecord>.fromIterable(ptrRecords) as Stream<T>;
    }
    if (T == SrvResourceRecord) {
      final String key = query.fullyQualifiedName;
      return Stream<SrvResourceRecord>.fromIterable(srvResponse[key] ?? <SrvResourceRecord>[]) as Stream<T>;
    }
    if (T == TxtResourceRecord) {
      final String key = query.fullyQualifiedName;
      return Stream<TxtResourceRecord>.fromIterable(txtResponse[key] ?? <TxtResourceRecord>[]) as Stream<T>;
    }
1577 1578 1579 1580
    if (T == IPAddressResourceRecord) {
      final String key = query.fullyQualifiedName;
      return Stream<IPAddressResourceRecord>.fromIterable(ipResponse[key] ?? <IPAddressResourceRecord>[]) as Stream<T>;
    }
1581 1582 1583 1584 1585 1586
    throw UnsupportedError('Unsupported query type $T');
  }

  @override
  void stop() {}
}
1587 1588

class TestDeviceManager extends DeviceManager {
1589
  TestDeviceManager({required super.logger});
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
  List<Device> devices = <Device>[];

  @override
  List<DeviceDiscovery> get deviceDiscoverers {
    final FakePollingDeviceDiscovery discoverer = FakePollingDeviceDiscovery();
    devices.forEach(discoverer.addDevice);
    return <DeviceDiscovery>[discoverer];
  }
}

class FakeTerminal extends Fake implements AnsiTerminal {
  FakeTerminal({this.stdinHasTerminal = true});

  @override
  final bool stdinHasTerminal;
1605 1606 1607

  @override
  bool usesTerminalUi = false;
1608 1609 1610 1611 1612 1613

  @override
  bool singleCharMode = false;

  @override
  Stream<String> get keystrokes => StreamController<String>().stream;
1614
}