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

5 6
// @dart = 2.8

7
import 'dart:async';
8
import 'dart:io';
9

10
import 'package:file/memory.dart';
11
import 'package:flutter_tools/src/android/android_device.dart';
12
import 'package:flutter_tools/src/android/application_package.dart';
13
import 'package:flutter_tools/src/artifacts.dart';
14
import 'package:flutter_tools/src/base/common.dart';
15
import 'package:flutter_tools/src/base/dds.dart';
16
import 'package:flutter_tools/src/base/file_system.dart';
17 18
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/terminal.dart';
19
import 'package:flutter_tools/src/build_info.dart';
20 21 22
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/attach.dart';
import 'package:flutter_tools/src/device.dart';
23
import 'package:flutter_tools/src/device_port_forwarder.dart';
24
import 'package:flutter_tools/src/globals.dart' as globals;
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/project.dart';
29
import 'package:flutter_tools/src/resident_runner.dart';
30
import 'package:flutter_tools/src/run_hot.dart';
31
import 'package:flutter_tools/src/vmservice.dart';
32
import 'package:meta/meta.dart';
33
import 'package:test/fake.dart';
34
import 'package:vm_service/vm_service.dart' as vm_service;
35

36 37
import '../../src/common.dart';
import '../../src/context.dart';
38
import '../../src/fake_devices.dart';
39 40
import '../../src/fake_vm_services.dart';
import '../../src/test_flutter_command_runner.dart';
41

42 43 44 45 46 47 48 49
final vm_service.Isolate fakeUnpausedIsolate = vm_service.Isolate(
  id: '1',
  pauseEvent: vm_service.Event(
    kind: vm_service.EventKind.kResume,
    timestamp: 0
  ),
  breakpoints: <vm_service.Breakpoint>[],
  exceptionPauseMode: null,
50
  isolateFlags: <vm_service.IsolateFlag>[],
51 52 53 54 55 56 57
  libraries: <vm_service.LibraryRef>[],
  livePorts: 0,
  name: 'test',
  number: '1',
  pauseOnExit: false,
  runnable: true,
  startTime: 0,
58
  isSystemIsolate: false,
59
);
60

61
void main() {
62 63 64 65
  tearDown(() {
    MacOSDesignedForIPadDevices.allowDiscovery = false;
  });

66
  group('attach', () {
67 68
    StreamLogger logger;
    FileSystem testFileSystem;
69

70
    setUp(() {
71
      Cache.disableLocking();
72 73
      logger = StreamLogger();
      testFileSystem = MemoryFileSystem(
74
      style: globals.platform.isWindows
75 76 77
          ? FileSystemStyle.windows
          : FileSystemStyle.posix,
      );
78
      testFileSystem.directory('lib').createSync();
79
      testFileSystem.file(testFileSystem.path.join('lib', 'main.dart')).createSync();
80 81
    });

82
    group('with one device and no specified target file', () {
83 84
      const int devicePort = 499;
      const int hostPort = 42;
85

86
      FakeDeviceLogReader fakeLogReader;
87
      RecordingPortForwarder portForwarder;
88
      FakeDartDevelopmentService fakeDds;
89
      FakeAndroidDevice device;
90 91

      setUp(() {
92
        fakeLogReader = FakeDeviceLogReader();
93
        portForwarder = RecordingPortForwarder(hostPort);
94
        fakeDds = FakeDartDevelopmentService();
95 96 97
        device = FakeAndroidDevice(id: '1')
          ..portForwarder = portForwarder
          ..dds = fakeDds;
98 99
      });

100
      tearDown(() {
101
        fakeLogReader.dispose();
102
      });
103

104
      testUsingContext('finds observatory port and forwards', () async {
105 106
        device.onGetLogReader = () {
          fakeLogReader.addLine('Foo');
107
          fakeLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:$devicePort');
108 109
          return fakeLogReader;
        };
110
        testDeviceManager.addDevice(device);
111 112
        final Completer<void> completer = Completer<void>();
        final StreamSubscription<String> loggerSubscription = logger.stream.listen((String message) {
113 114
          if (message == '[verbose] Observatory URL on device: http://127.0.0.1:$devicePort') {
            // The "Observatory URL on device" message is output by the ProtocolDiscovery when it found the observatory.
115 116 117 118 119
            completer.complete();
          }
        });
        final Future<void> task = createTestCommandRunner(AttachCommand()).run(<String>['attach']);
        await completer.future;
120 121 122 123

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

124
        await fakeLogReader.dispose();
125 126
        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
127 128
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
129
        ProcessManager: () => FakeProcessManager.any(),
130
        Logger: () => logger,
131 132
      });

133
      testUsingContext('Fails with tool exit on bad Observatory uri', () async {
134 135
        device.onGetLogReader = () {
          fakeLogReader.addLine('Foo');
136
          fakeLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:$devicePort');
137 138 139
          fakeLogReader.dispose();
          return fakeLogReader;
        };
140
        testDeviceManager.addDevice(device);
141
        expect(() => createTestCommandRunner(AttachCommand()).run(<String>['attach']), throwsToolExit());
142 143
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
144
        ProcessManager: () => FakeProcessManager.any(),
145 146 147
        Logger: () => logger,
      });

148
      testUsingContext('accepts filesystem parameters', () async {
149 150
        device.onGetLogReader = () {
          fakeLogReader.addLine('Foo');
151
          fakeLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:$devicePort');
152 153
          return fakeLogReader;
        };
154 155 156 157 158 159 160
        testDeviceManager.addDevice(device);

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

161 162 163 164 165 166 167 168 169 170 171 172
        final FakeHotRunner hotRunner = FakeHotRunner();
        hotRunner.onAttach = (
          Completer<DebugConnectionInfo> connectionInfoCompleter,
          Completer<void> appStartedCompleter,
          bool allowExistingDdsInstance,
          bool enableDevTools,
        ) async => 0;
        hotRunner.exited = false;
        hotRunner.isWaitingForObservatory = false;

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

174
        final AttachCommand command = AttachCommand(
175
          hotRunnerFactory: hotRunnerFactory,
176 177 178 179 180 181 182 183 184 185 186
        );
        await createTestCommandRunner(command).run(<String>[
          'attach',
          '--filesystem-scheme',
          filesystemScheme,
          '--filesystem-root',
          filesystemRoot,
          '--project-root',
          projectRoot,
          '--output-dill',
          outputDill,
187
          '-v', // enables verbose logging
188 189
        ]);

190
        // Validate the attach call built a fake runner with the right
191
        // project root and output dill.
192 193 194
        expect(hotRunnerFactory.projectRootPath, projectRoot);
        expect(hotRunnerFactory.dillOutputPath, outputDill);
        expect(hotRunnerFactory.devices, hasLength(1));
195 196 197

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

200 201
        expect(flutterDevice.buildInfo.fileSystemScheme, filesystemScheme);
        expect(flutterDevice.buildInfo.fileSystemRoots, const <String>[filesystemRoot]);
202 203
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
204
        ProcessManager: () => FakeProcessManager.any(),
205
      });
206 207 208 209 210 211 212 213

      testUsingContext('exits when ipv6 is specified and debug-port is not', () async {
        testDeviceManager.addDevice(device);

        final AttachCommand command = AttachCommand();
        await expectLater(
          createTestCommandRunner(command).run(<String>['attach', '--ipv6']),
          throwsToolExit(
214
            message: 'When the --debug-port or --debug-url is unknown, this command determines '
215 216 217 218 219
                     'the value of --ipv6 on its own.',
          ),
        );
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
220
        ProcessManager: () => FakeProcessManager.any(),
221 222 223
      },);

      testUsingContext('exits when observatory-port is specified and debug-port is not', () async {
224 225
        device.onGetLogReader = () {
          fakeLogReader.addLine('Foo');
226
          fakeLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:$devicePort');
227 228
          return fakeLogReader;
        };
229 230 231 232 233 234
        testDeviceManager.addDevice(device);

        final AttachCommand command = AttachCommand();
        await expectLater(
          createTestCommandRunner(command).run(<String>['attach', '--observatory-port', '100']),
          throwsToolExit(
235
            message: 'When the --debug-port or --debug-url is unknown, this command does not use '
236 237 238 239 240
                     'the value of --observatory-port.',
          ),
        );
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
241
        ProcessManager: () => FakeProcessManager.any(),
242
      },);
243
    });
244

245
    group('forwarding to given port', () {
246 247
      const int devicePort = 499;
      const int hostPort = 42;
248 249
      RecordingPortForwarder portForwarder;
      FakeAndroidDevice device;
250

251
      setUp(() {
252
        final FakeDartDevelopmentService fakeDds = FakeDartDevelopmentService();
253 254 255 256
        portForwarder = RecordingPortForwarder(hostPort);
        device = FakeAndroidDevice(id: '1')
          ..portForwarder = portForwarder
          ..dds = fakeDds;
257
      });
258

259 260
      testUsingContext('succeeds in ipv4 mode', () async {
        testDeviceManager.addDevice(device);
261

262 263 264 265 266 267 268 269 270 271 272
        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();
          }
        });
        final Future<void> task = createTestCommandRunner(AttachCommand())
          .run(<String>['attach', '--debug-port', '$devicePort']);
        await completer.future;
273 274
        expect(portForwarder.devicePort, devicePort);
        expect(portForwarder.hostPort, hostPort);
275 276 277

        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
278 279
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
280
        ProcessManager: () => FakeProcessManager.any(),
281
        Logger: () => logger,
282 283 284 285
      });

      testUsingContext('succeeds in ipv6 mode', () async {
        testDeviceManager.addDevice(device);
286

287 288 289 290 291 292 293 294 295 296 297
        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();
          }
        });
        final Future<void> task = createTestCommandRunner(AttachCommand())
          .run(<String>['attach', '--debug-port', '$devicePort', '--ipv6']);
        await completer.future;
298 299 300

        expect(portForwarder.devicePort, devicePort);
        expect(portForwarder.hostPort, hostPort);
301 302 303

        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
304 305
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
306
        ProcessManager: () => FakeProcessManager.any(),
307
        Logger: () => logger,
308 309 310 311 312
      });

      testUsingContext('skips in ipv4 mode with a provided observatory port', () async {
        testDeviceManager.addDevice(device);

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
        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();
          }
        });
        final Future<void> task = createTestCommandRunner(AttachCommand()).run(
          <String>[
            'attach',
            '--debug-port',
            '$devicePort',
            '--observatory-port',
            '$hostPort',
328 329 330
            // Ensure DDS doesn't use hostPort by binding to a random port.
            '--dds-port',
            '0',
331
          ],
332
        );
333
        await completer.future;
334 335
        expect(portForwarder.devicePort, null);
        expect(portForwarder.hostPort, 42);
336 337 338

        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
339 340
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
341
        ProcessManager: () => FakeProcessManager.any(),
342
        Logger: () => logger,
343 344 345 346 347
      });

      testUsingContext('skips in ipv6 mode with a provided observatory port', () async {
        testDeviceManager.addDevice(device);

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
        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();
          }
        });
        final Future<void> task = createTestCommandRunner(AttachCommand()).run(
          <String>[
            'attach',
            '--debug-port',
            '$devicePort',
            '--observatory-port',
            '$hostPort',
            '--ipv6',
364 365 366
            // Ensure DDS doesn't use hostPort by binding to a random port.
            '--dds-port',
            '0',
367
          ],
368
        );
369
        await completer.future;
370 371
        expect(portForwarder.devicePort, null);
        expect(portForwarder.hostPort, 42);
372 373 374

        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
375 376
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
377
        ProcessManager: () => FakeProcessManager.any(),
378
        Logger: () => logger,
379 380
      });
    });
381 382

    testUsingContext('exits when no device connected', () async {
383
      final AttachCommand command = AttachCommand();
384 385
      await expectLater(
        createTestCommandRunner(command).run(<String>['attach']),
Dan Field's avatar
Dan Field committed
386
        throwsToolExit(),
387
      );
388
      expect(testLogger.statusText, containsIgnoringWhitespace('No supported devices connected'));
389 390
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
391
      ProcessManager: () => FakeProcessManager.any(),
392
    });
393

394
    testUsingContext('fails when targeted device is not Android with --device-user', () async {
395
      final FakeIOSDevice device = FakeIOSDevice();
396 397 398 399 400 401 402 403 404 405 406
      testDeviceManager.addDevice(device);
      expect(createTestCommandRunner(AttachCommand()).run(<String>[
        'attach',
        '--device-user',
        '10',
      ]), throwsToolExit(message: '--device-user is only supported for Android'));
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
      ProcessManager: () => FakeProcessManager.any(),
    });

407
    testUsingContext('exits when multiple devices connected', () async {
408
      final AttachCommand command = AttachCommand();
409 410
      testDeviceManager.addDevice(FakeAndroidDevice(id: 'xx1'));
      testDeviceManager.addDevice(FakeAndroidDevice(id: 'yy2'));
411 412
      await expectLater(
        createTestCommandRunner(command).run(<String>['attach']),
Dan Field's avatar
Dan Field committed
413
        throwsToolExit(),
414
      );
415
      expect(testLogger.statusText, containsIgnoringWhitespace('More than one device'));
416 417
      expect(testLogger.statusText, contains('xx1'));
      expect(testLogger.statusText, contains('yy2'));
418
      expect(MacOSDesignedForIPadDevices.allowDiscovery, isTrue);
419 420
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
421
      ProcessManager: () => FakeProcessManager.any(),
422
    });
423 424

    testUsingContext('Catches service disappeared error', () async {
425 426 427 428 429 430 431 432 433 434 435 436
      final FakeAndroidDevice device = FakeAndroidDevice(id: '1')
        ..portForwarder = const NoOpDevicePortForwarder()
        ..onGetLogReader = () => NoOpDeviceLogReader('test');
      final FakeHotRunner hotRunner = FakeHotRunner();
      final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
        ..hotRunner = hotRunner;
      hotRunner.onAttach = (
        Completer<DebugConnectionInfo> connectionInfoCompleter,
        Completer<void> appStartedCompleter,
        bool allowExistingDdsInstance,
        bool enableDevTools,
      ) async {
437 438
        await null;
        throw vm_service.RPCError('flutter._listViews', RPCErrorCodes.kServiceDisappeared, '');
439
      };
440 441 442 443

      testDeviceManager.addDevice(device);
      testFileSystem.file('lib/main.dart').createSync();

444
      final AttachCommand command = AttachCommand(hotRunnerFactory: hotRunnerFactory);
445 446 447 448 449 450 451 452 453
      await expectLater(createTestCommandRunner(command).run(<String>[
        'attach',
      ]), throwsToolExit(message: 'Lost connection to device.'));
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
      ProcessManager: () => FakeProcessManager.any(),
    });

    testUsingContext('Does not catch generic RPC error', () async {
454 455 456 457 458 459 460 461 462 463 464 465 466
      final FakeAndroidDevice device = FakeAndroidDevice(id: '1')
        ..portForwarder = const NoOpDevicePortForwarder()
        ..onGetLogReader = () => NoOpDeviceLogReader('test');
      final FakeHotRunner hotRunner = FakeHotRunner();
      final FakeHotRunnerFactory hotRunnerFactory = FakeHotRunnerFactory()
        ..hotRunner = hotRunner;

      hotRunner.onAttach = (
        Completer<DebugConnectionInfo> connectionInfoCompleter,
        Completer<void> appStartedCompleter,
        bool allowExistingDdsInstance,
        bool enableDevTools,
      ) async {
467 468
        await null;
        throw vm_service.RPCError('flutter._listViews', RPCErrorCodes.kInvalidParams, '');
469 470
      };

471 472 473 474

      testDeviceManager.addDevice(device);
      testFileSystem.file('lib/main.dart').createSync();

475
      final AttachCommand command = AttachCommand(hotRunnerFactory: hotRunnerFactory);
476 477 478 479 480 481 482
      await expectLater(createTestCommandRunner(command).run(<String>[
        'attach',
      ]), throwsA(isA<vm_service.RPCError>()));
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
      ProcessManager: () => FakeProcessManager.any(),
    });
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 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
class FakeHotRunner extends Fake implements HotRunner {
  Future<int> Function(Completer<DebugConnectionInfo>, Completer<void>, bool, bool) onAttach;

  @override
  bool exited = false;

  @override
  bool isWaitingForObservatory = true;

  @override
  Future<int> attach({
    Completer<DebugConnectionInfo> connectionInfoCompleter,
    Completer<void> appStartedCompleter,
    bool allowExistingDdsInstance = false,
    bool enableDevTools = false,
  }) {
    return onAttach(connectionInfoCompleter, appStartedCompleter, allowExistingDdsInstance, enableDevTools);
  }
}

class FakeHotRunnerFactory extends Fake implements HotRunnerFactory {
  HotRunner hotRunner;
  String dillOutputPath;
  String projectRootPath;
  List<FlutterDevice> devices;

  @override
  HotRunner build(
    List<FlutterDevice> devices, {
    String target,
    DebuggingOptions debuggingOptions,
    bool benchmarkMode = false,
    File applicationBinary,
    bool hostIsIde = false,
    String projectRootPath,
    String packagesFilePath,
    String dillOutputPath,
    bool stayResident = true,
    bool ipv6 = false,
    FlutterProject flutterProject,
  }) {
    this.devices = devices;
    this.dillOutputPath = dillOutputPath;
    this.projectRootPath = projectRootPath;
    return hotRunner;
  }
}

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

  int devicePort;
  int hostPort;

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

  @override
  Future<int> forward(int devicePort, {int hostPort}) async {
    this.devicePort = devicePort;
    this.hostPort ??= hostPort;
    return this.hostPort;
  }

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

  @override
  Future<void> unforward(ForwardedPort forwardedPort) async { }
}
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570

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

  @override
  void printError(
    String message, {
    StackTrace stackTrace,
    bool emphasis,
    TerminalColor color,
    int indent,
    int hangingIndent,
    bool wrap,
  }) {
571 572 573 574 575 576 577 578 579 580 581 582 583 584
    hadErrorOutput = true;
    _log('[stderr] $message');
  }

  @override
  void printWarning(
    String message, {
    bool emphasis,
    TerminalColor color,
    int indent,
    int hangingIndent,
    bool wrap,
  }) {
    hadWarningOutput = true;
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
    _log('[stderr] $message');
  }

  @override
  void printStatus(
    String message, {
    bool emphasis,
    TerminalColor color,
    bool newline,
    int indent,
    int hangingIndent,
    bool wrap,
  }) {
    _log('[stdout] $message');
  }

601 602 603 604 605 606 607 608 609 610 611 612
  @override
  void printBox(
    String message, {
    String title,
  }) {
    if (title == null) {
      _log('[stdout] $message');
    } else {
      _log('[stdout] $title: $message');
    }
  }

613 614 615 616 617 618 619 620 621 622 623
  @override
  void printTrace(String message) {
    _log('[verbose] $message');
  }

  @override
  Status startProgress(
    String message, {
    @required Duration timeout,
    String progressId,
    bool multilineOutput = false,
624
    bool includeTiming = true,
625 626 627
    int progressIndicatorPadding = kDefaultStatusPadding,
  }) {
    _log('[progress] $message');
628 629 630
    return SilentStatus(
      stopwatch: Stopwatch(),
    )..start();
631 632
  }

633
  @override
634 635 636 637 638
  Status startSpinner({
    VoidCallback onFinish,
    Duration timeout,
    SlowWarningCallback slowWarningCallback,
  }) {
639 640 641 642 643 644
    return SilentStatus(
      stopwatch: Stopwatch(),
      onFinish: onFinish,
    )..start();
  }

645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
  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;
662 663

  @override
664
  void sendEvent(String name, [Map<String, dynamic> args]) { }
665 666 667 668 669 670

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

  @override
  bool get hasTerminal => false;
671 672 673

  @override
  void clear() => _log('[stdout] ${globals.terminal.clearScreen()}\n');
674 675 676

  @override
  Terminal get terminal => Terminal.test();
677 678 679 680 681 682 683 684
}

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...
685 686 687 688
  await expectLater(
    () => task,
    throwsA(isA<ToolExit>().having((ToolExit error) => error.exitCode, 'exitCode', 2)),
  );
689
}
690 691 692 693 694 695 696 697 698 699 700

VMServiceConnector getFakeVmServiceFactory({
  @required Completer<void> vmServiceDoneCompleter,
}) {
  assert(vmServiceDoneCompleter != null);

  return (
    Uri httpUri, {
    ReloadSources reloadSources,
    Restart restart,
    CompileExpression compileExpression,
701
    GetSkSLMethod getSkSLMethod,
702
    PrintStructuredErrorLogMethod printStructuredErrorLogMethod,
703
    CompressionOptions compression,
704
    Device device,
705
    Logger logger,
706
  }) async {
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
    final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
      requests: <VmServiceExpectation>[
        FakeVmServiceRequest(
          method: kListViewsMethod,
          args: null,
          jsonResponse: <String, Object>{
            'views': <Object>[
              <String, Object>{
                'id': '1',
                'isolate': fakeUnpausedIsolate.toJson()
              },
            ],
          },
        ),
        FakeVmServiceRequest(
          method: 'getVM',
          args: null,
          jsonResponse: vm_service.VM.parse(<String, Object>{})
            .toJson(),
        ),
        FakeVmServiceRequest(
          method: '_createDevFS',
          args: <String, Object>{
            'fsName': globals.fs.currentDirectory.absolute.path,
          },
          jsonResponse: <String, Object>{
            'uri': globals.fs.currentDirectory.absolute.path,
          },
        ),
        FakeVmServiceRequest(
          method: kListViewsMethod,
          args: null,
          jsonResponse: <String, Object>{
            'views': <Object>[
              <String, Object>{
                'id': '1',
                'isolate': fakeUnpausedIsolate.toJson()
              },
            ],
          },
        ),
      ],
    );
    return fakeVmServiceHost.vmService;
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
  };
}

class TestHotRunnerFactory extends HotRunnerFactory {
  HotRunner _runner;

  @override
  HotRunner build(
    List<FlutterDevice> devices, {
    String target,
    DebuggingOptions debuggingOptions,
    bool benchmarkMode = false,
    File applicationBinary,
    bool hostIsIde = false,
    String projectRootPath,
    String packagesFilePath,
    String dillOutputPath,
    bool stayResident = true,
    bool ipv6 = false,
    FlutterProject flutterProject,
  }) {
    _runner ??= HotRunner(
      devices,
      target: target,
      debuggingOptions: debuggingOptions,
      benchmarkMode: benchmarkMode,
      applicationBinary: applicationBinary,
      hostIsIde: hostIsIde,
      projectRootPath: projectRootPath,
      dillOutputPath: dillOutputPath,
      stayResident: stayResident,
      ipv6: ipv6,
    );
    return _runner;
  }

  Future<void> exitApp() async {
    assert(_runner != null);
    await _runner.exit();
  }
}

793 794 795 796 797 798 799
class FakeDartDevelopmentService extends Fake implements DartDevelopmentService {
  @override
  Future<void> get done => noopCompleter.future;
  final Completer<void> noopCompleter = Completer<void>();

  @override
  Future<void> startDartDevelopmentService(
800 801
    Uri observatoryUri, {
    @required Logger logger,
802 803
    int hostPort,
    bool ipv6,
804
    bool disableServiceAuthCodes,
805
    bool cacheStartupProfile = false,
806 807 808 809 810
  }) async {}

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

812 813 814
// Unfortunately Device, despite not being immutable, has an `operator ==`.
// Until we fix that, we have to also ignore related lints here.
// ignore: avoid_implementing_value_types
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
class FakeAndroidDevice extends Fake implements AndroidDevice {
  FakeAndroidDevice({@required this.id});

  @override
  DartDevelopmentService dds;

  @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';

836 837 838 839 840 841 842 843 844 845 846 847 848 849
  @override
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.android_arm;

  @override
  bool isSupported() => true;

  @override
  bool get supportsHotRestart => true;

  @override
  bool get supportsFlutterExit => false;

  @override
  bool isSupportedForProject(FlutterProject flutterProject) => true;
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871

  @override
  DevicePortForwarder portForwarder;

  DeviceLogReader Function() onGetLogReader;

  @override
  FutureOr<DeviceLogReader> getLogReader({
    AndroidApk app,
    bool includePastLogs = false,
  }) {
    return onGetLogReader();
  }

  @override
  OverrideArtifacts get artifactOverrides => null;

  @override
  final PlatformType platformType = PlatformType.android;

  @override
  Category get category => Category.mobile;
872
}
873

874 875 876
// Unfortunately Device, despite not being immutable, has an `operator ==`.
// Until we fix that, we have to also ignore related lints here.
// ignore: avoid_implementing_value_types
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
class FakeIOSDevice extends Fake implements IOSDevice {
  FakeIOSDevice({this.dds, this.portForwarder, this.logReader});

  @override
  final DevicePortForwarder portForwarder;

  @override
  final DartDevelopmentService dds;

  final DeviceLogReader logReader;

  @override
  DeviceLogReader getLogReader({
    IOSApp app,
    bool includePastLogs = false,
  }) => logReader;

  @override
  OverrideArtifacts get artifactOverrides => null;

  @override
  final String name = 'name';

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

  @override
  final PlatformType platformType = PlatformType.ios;
}