attach_test.dart 20.2 KB
Newer Older
1 2 3 4 5 6
// Copyright 2018 The Chromium Authors. All rights reserved.
// 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/base/common.dart';
9
import 'package:flutter_tools/src/base/file_system.dart';
10
import 'package:flutter_tools/src/base/logger.dart';
11
import 'package:flutter_tools/src/base/platform.dart';
12
import 'package:flutter_tools/src/base/terminal.dart';
13 14 15
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/attach.dart';
import 'package:flutter_tools/src/device.dart';
16 17
import 'package:flutter_tools/src/ios/devices.dart';
import 'package:flutter_tools/src/mdns_discovery.dart';
18
import 'package:flutter_tools/src/resident_runner.dart';
19
import 'package:flutter_tools/src/run_hot.dart';
20
import 'package:meta/meta.dart';
21 22
import 'package:mockito/mockito.dart';

23 24 25
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/mocks.dart';
26 27 28

void main() {
  group('attach', () {
29 30
    StreamLogger logger;
    FileSystem testFileSystem;
31

32
    setUp(() {
33
      Cache.disableLocking();
34 35 36 37 38 39
      logger = StreamLogger();
      testFileSystem = MemoryFileSystem(
      style: platform.isWindows
          ? FileSystemStyle.windows
          : FileSystemStyle.posix,
      );
40
      testFileSystem.directory('lib').createSync();
41
      testFileSystem.file(testFileSystem.path.join('lib', 'main.dart')).createSync();
42 43
    });

44
    group('with one device and no specified target file', () {
45 46
      const int devicePort = 499;
      const int hostPort = 42;
47 48 49 50 51 52

      MockDeviceLogReader mockLogReader;
      MockPortForwarder portForwarder;
      MockAndroidDevice device;

      setUp(() {
53 54 55
        mockLogReader = MockDeviceLogReader();
        portForwarder = MockPortForwarder();
        device = MockAndroidDevice();
56 57
        when(device.portForwarder)
          .thenReturn(portForwarder);
58
        when(portForwarder.forward(devicePort, hostPort: anyNamed('hostPort')))
59 60 61 62 63
          .thenAnswer((_) async => hostPort);
        when(portForwarder.forwardedPorts)
          .thenReturn(<ForwardedPort>[ForwardedPort(hostPort, devicePort)]);
        when(portForwarder.unforward(any))
          .thenAnswer((_) async => null);
64

65 66 67 68 69
        // We cannot add the device to a device manager because that is
        // only enabled by the context of each testUsingContext call.
        //
        // Instead each test will add the device to the device manager
        // on its own.
70 71
      });

72 73 74
      tearDown(() {
        mockLogReader.dispose();
      });
75

76
      testUsingContext('finds observatory port and forwards', () async {
77 78 79 80 81 82 83 84
        when(device.getLogReader()).thenAnswer((_) {
          // Now that the reader is used, start writing messages to it.
          Timer.run(() {
            mockLogReader.addLine('Foo');
            mockLogReader.addLine('Observatory listening on http://127.0.0.1:$devicePort');
          });
          return mockLogReader;
        });
85
        testDeviceManager.addDevice(device);
86 87 88 89 90 91 92 93 94
        final Completer<void> completer = Completer<void>();
        final StreamSubscription<String> loggerSubscription = logger.stream.listen((String message) {
          if (message == '[stdout] Done.') {
            // The "Done." message is output by the AttachCommand when it's done.
            completer.complete();
          }
        });
        final Future<void> task = createTestCommandRunner(AttachCommand()).run(<String>['attach']);
        await completer.future;
95 96 97
        verify(
          portForwarder.forward(devicePort, hostPort: anyNamed('hostPort')),
        ).called(1);
98 99
        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
100 101
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
102
        Logger: () => logger,
103 104
      });

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
      testUsingContext('Fails with tool exit on bad Observatory uri', () async {
        when(device.getLogReader()).thenAnswer((_) {
          // Now that the reader is used, start writing messages to it.
          Timer.run(() {
            mockLogReader.addLine('Foo');
            mockLogReader.addLine('Observatory listening on http:/:/127.0.0.1:$devicePort');
          });
          return mockLogReader;
        });
        testDeviceManager.addDevice(device);
        expect(createTestCommandRunner(AttachCommand()).run(<String>['attach']),
               throwsA(isA<ToolExit>()));
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
        Logger: () => logger,
      });

122
      testUsingContext('accepts filesystem parameters', () async {
123 124 125 126 127 128 129 130
        when(device.getLogReader()).thenAnswer((_) {
          // Now that the reader is used, start writing messages to it.
          Timer.run(() {
            mockLogReader.addLine('Foo');
            mockLogReader.addLine('Observatory listening on http://127.0.0.1:$devicePort');
          });
          return mockLogReader;
        });
131 132 133 134 135 136 137
        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';

138
        final MockHotRunner mockHotRunner = MockHotRunner();
139 140
        when(mockHotRunner.attach(appStartedCompleter: anyNamed('appStartedCompleter')))
            .thenAnswer((_) async => 0);
141

142
        final MockHotRunnerFactory mockHotRunnerFactory = MockHotRunnerFactory();
143 144 145 146 147 148 149 150
        when(
          mockHotRunnerFactory.build(
            any,
            target: anyNamed('target'),
            projectRootPath: anyNamed('projectRootPath'),
            dillOutputPath: anyNamed('dillOutputPath'),
            debuggingOptions: anyNamed('debuggingOptions'),
            packagesFilePath: anyNamed('packagesFilePath'),
151
            flutterProject: anyNamed('flutterProject'),
152
            ipv6: false,
153
          ),
154
        ).thenReturn(mockHotRunner);
155

156
        final AttachCommand command = AttachCommand(
157 158 159 160 161 162 163 164 165 166 167 168
          hotRunnerFactory: mockHotRunnerFactory,
        );
        await createTestCommandRunner(command).run(<String>[
          'attach',
          '--filesystem-scheme',
          filesystemScheme,
          '--filesystem-root',
          filesystemRoot,
          '--project-root',
          projectRoot,
          '--output-dill',
          outputDill,
169
          '-v', // enables verbose logging
170 171 172 173 174 175 176 177 178 179 180 181
        ]);

        // Validate the attach call built a mock runner with the right
        // project root and output dill.
        final VerificationResult verificationResult = verify(
          mockHotRunnerFactory.build(
            captureAny,
            target: anyNamed('target'),
            projectRootPath: projectRoot,
            dillOutputPath: outputDill,
            debuggingOptions: anyNamed('debuggingOptions'),
            packagesFilePath: anyNamed('packagesFilePath'),
182
            flutterProject: anyNamed('flutterProject'),
183
            ipv6: false,
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
          ),
        )..called(1);

        final List<FlutterDevice> flutterDevices = verificationResult.captured.first;
        expect(flutterDevices, hasLength(1));

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

        expect(flutterDevice.fileSystemScheme, filesystemScheme);
        expect(flutterDevice.fileSystemRoots, const <String>[filesystemRoot]);
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
      });
199 200

      testUsingContext('exits when ipv6 is specified and debug-port is not', () async {
201 202 203 204 205 206 207 208
        when(device.getLogReader()).thenAnswer((_) {
          // Now that the reader is used, start writing messages to it.
          Timer.run(() {
            mockLogReader.addLine('Foo');
            mockLogReader.addLine('Observatory listening on http://127.0.0.1:$devicePort');
          });
          return mockLogReader;
        });
209 210 211 212 213 214
        testDeviceManager.addDevice(device);

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

      testUsingContext('exits when observatory-port is specified and debug-port is not', () async {
224 225 226 227 228 229 230 231
        when(device.getLogReader()).thenAnswer((_) {
          // Now that the reader is used, start writing messages to it.
          Timer.run(() {
            mockLogReader.addLine('Foo');
            mockLogReader.addLine('Observatory listening on http://127.0.0.1:$devicePort');
          });
          return mockLogReader;
        });
232 233 234 235 236 237
        testDeviceManager.addDevice(device);

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

247 248 249 250

    testUsingContext('selects specified target', () async {
      const int devicePort = 499;
      const int hostPort = 42;
251 252 253
      final MockDeviceLogReader mockLogReader = MockDeviceLogReader();
      final MockPortForwarder portForwarder = MockPortForwarder();
      final MockAndroidDevice device = MockAndroidDevice();
254
      final MockHotRunner mockHotRunner = MockHotRunner();
255
      final MockHotRunnerFactory mockHotRunnerFactory = MockHotRunnerFactory();
256 257
      when(device.portForwarder)
        .thenReturn(portForwarder);
258
      when(portForwarder.forward(devicePort, hostPort: anyNamed('hostPort')))
259 260 261 262 263
        .thenAnswer((_) async => hostPort);
      when(portForwarder.forwardedPorts)
        .thenReturn(<ForwardedPort>[ForwardedPort(hostPort, devicePort)]);
      when(portForwarder.unforward(any))
        .thenAnswer((_) async => null);
264
      when(mockHotRunner.attach(appStartedCompleter: anyNamed('appStartedCompleter')))
265
        .thenAnswer((_) async => 0);
266 267 268 269 270
      when(mockHotRunnerFactory.build(
        any,
        target: anyNamed('target'),
        debuggingOptions: anyNamed('debuggingOptions'),
        packagesFilePath: anyNamed('packagesFilePath'),
271
        flutterProject: anyNamed('flutterProject'),
272 273
        ipv6: false,
      )).thenReturn(mockHotRunner);
274 275

      testDeviceManager.addDevice(device);
276 277 278 279 280 281 282 283
      when(device.getLogReader())
        .thenAnswer((_) {
          // Now that the reader is used, start writing messages to it.
          Timer.run(() {
            mockLogReader.addLine('Foo');
            mockLogReader.addLine(
                'Observatory listening on http://127.0.0.1:$devicePort');
          });
284 285
          return mockLogReader;
        });
286 287 288
      final File foo = fs.file('lib/foo.dart')
        ..createSync();

289
      // Delete the main.dart file to be sure that attach works without it.
290
      fs.file(fs.path.join('lib', 'main.dart')).deleteSync();
291

292 293 294 295 296 297 298 299
      final AttachCommand command = AttachCommand(hotRunnerFactory: mockHotRunnerFactory);
      await createTestCommandRunner(command).run(<String>['attach', '-t', foo.path, '-v']);

      verify(mockHotRunnerFactory.build(
        any,
        target: foo.path,
        debuggingOptions: anyNamed('debuggingOptions'),
        packagesFilePath: anyNamed('packagesFilePath'),
300
        flutterProject: anyNamed('flutterProject'),
301 302
        ipv6: false,
      )).called(1);
303 304
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
305
    });
306

307
    group('forwarding to given port', () {
308 309
      const int devicePort = 499;
      const int hostPort = 42;
310 311
      MockPortForwarder portForwarder;
      MockAndroidDevice device;
312

313 314 315
      setUp(() {
        portForwarder = MockPortForwarder();
        device = MockAndroidDevice();
316

317 318 319 320 321 322 323 324
        when(device.portForwarder)
          .thenReturn(portForwarder);
        when(portForwarder.forward(devicePort))
          .thenAnswer((_) async => hostPort);
        when(portForwarder.forwardedPorts)
          .thenReturn(<ForwardedPort>[ForwardedPort(hostPort, devicePort)]);
        when(portForwarder.unforward(any))
          .thenAnswer((_) async => null);
325
      });
326

327 328
      testUsingContext('succeeds in ipv4 mode', () async {
        testDeviceManager.addDevice(device);
329

330 331 332 333 334 335 336 337 338 339 340
        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;
341
        verify(portForwarder.forward(devicePort)).called(1);
342 343 344

        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
345 346
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
347
        Logger: () => logger,
348 349 350 351
      });

      testUsingContext('succeeds in ipv6 mode', () async {
        testDeviceManager.addDevice(device);
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', '--ipv6']);
        await completer.future;
364
        verify(portForwarder.forward(devicePort)).called(1);
365 366 367

        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
368 369
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
370
        Logger: () => logger,
371 372 373 374 375
      });

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

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
        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',
          ],
392
        );
393
        await completer.future;
394
        verifyNever(portForwarder.forward(devicePort));
395 396 397

        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
398 399
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
400
        Logger: () => logger,
401 402 403 404 405
      });

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

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
        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',
          ],
423
        );
424
        await completer.future;
425
        verifyNever(portForwarder.forward(devicePort));
426 427 428

        await expectLoggerInterruptEndsTask(task, logger);
        await loggerSubscription.cancel();
429 430
      }, overrides: <Type, Generator>{
        FileSystem: () => testFileSystem,
431
        Logger: () => logger,
432 433
      });
    });
434 435

    testUsingContext('exits when no device connected', () async {
436
      final AttachCommand command = AttachCommand();
437 438
      await expectLater(
        createTestCommandRunner(command).run(<String>['attach']),
439
        throwsA(isInstanceOf<ToolExit>()),
440
      );
441
      expect(testLogger.statusText, contains('No supported devices connected'));
442 443
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
444
    });
445 446 447

    testUsingContext('exits when multiple devices connected', () async {
      Device aDeviceWithId(String id) {
448
        final MockAndroidDevice device = MockAndroidDevice();
449 450 451 452 453 454 455
        when(device.name).thenReturn('d$id');
        when(device.id).thenReturn(id);
        when(device.isLocalEmulator).thenAnswer((_) async => false);
        when(device.sdkNameAndVersion).thenAnswer((_) async => 'Android 46');
        return device;
      }

456
      final AttachCommand command = AttachCommand();
457 458 459 460
      testDeviceManager.addDevice(aDeviceWithId('xx1'));
      testDeviceManager.addDevice(aDeviceWithId('yy2'));
      await expectLater(
        createTestCommandRunner(command).run(<String>['attach']),
461
        throwsA(isInstanceOf<ToolExit>()),
462 463 464 465
      );
      expect(testLogger.statusText, contains('More than one device'));
      expect(testLogger.statusText, contains('xx1'));
      expect(testLogger.statusText, contains('yy2'));
466 467
    }, overrides: <Type, Generator>{
      FileSystem: () => testFileSystem,
468
    });
469 470 471
  });
}

472 473
class MockHotRunner extends Mock implements HotRunner {}
class MockHotRunnerFactory extends Mock implements HotRunnerFactory {}
474 475 476
class MockIOSDevice extends Mock implements IOSDevice {}
class MockMDnsObservatoryDiscovery extends Mock implements MDnsObservatoryDiscovery {}
class MockPortForwarder extends Mock implements DevicePortForwarder {}
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 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

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,
  }) {
    _log('[stderr] $message');
  }

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

  @override
  void printTrace(String message) {
    _log('[verbose] $message');
  }

  @override
  Status startProgress(
    String message, {
    @required Duration timeout,
    String progressId,
    bool multilineOutput = false,
    int progressIndicatorPadding = kDefaultStatusPadding,
  }) {
    _log('[progress] $message');
    return SilentStatus(timeout: timeout)..start();
  }

  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;
542 543 544

  @override
  void sendNotification(String message, {String progressId}) { }
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
}

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...
  try {
    await task;
    expect(false, isTrue); // (shouldn't reach here)
  } on ToolExit catch (error) {
    expect(error.exitCode, 2); // ...with exit code 2.
  }
}