devices_test.dart 19.9 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
import 'dart:async';

7
import 'package:file/file.dart';
8
import 'package:file/memory.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/file_system.dart';
12
import 'package:flutter_tools/src/base/io.dart';
13
import 'package:flutter_tools/src/base/logger.dart';
14
import 'package:flutter_tools/src/base/platform.dart';
15
import 'package:flutter_tools/src/build_info.dart';
16
import 'package:flutter_tools/src/cache.dart';
17
import 'package:flutter_tools/src/device.dart';
18
import 'package:flutter_tools/src/ios/devices.dart';
19
import 'package:flutter_tools/src/ios/ios_deploy.dart';
20
import 'package:flutter_tools/src/ios/ios_workflow.dart';
21
import 'package:flutter_tools/src/ios/mac.dart';
22
import 'package:flutter_tools/src/macos/xcode.dart';
23
import 'package:mockito/mockito.dart';
24
import 'package:vm_service/vm_service.dart';
25

26 27 28
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/mocks.dart';
29

30
void main() {
31 32 33
  final FakePlatform macPlatform = FakePlatform(operatingSystem: 'macos');
  final FakePlatform linuxPlatform = FakePlatform(operatingSystem: 'linux');
  final FakePlatform windowsPlatform = FakePlatform(operatingSystem: 'windows');
34

35 36
  group('IOSDevice', () {
    final List<Platform> unsupportedPlatforms = <Platform>[linuxPlatform, windowsPlatform];
37 38
    Artifacts mockArtifacts;
    MockCache mockCache;
39
    MockVmService mockVmService;
40
    Logger logger;
41
    IOSDeploy iosDeploy;
42
    IMobileDevice iMobileDevice;
43
    FileSystem mockFileSystem;
44

45 46 47
    setUp(() {
      mockArtifacts = MockArtifacts();
      mockCache = MockCache();
48
      mockVmService = MockVmService();
49 50
      const MapEntry<String, String> dyLdLibEntry = MapEntry<String, String>('DYLD_LIBRARY_PATH', '/path/to/libs');
      when(mockCache.dyLdLibEntry).thenReturn(dyLdLibEntry);
51
      logger = BufferLogger.test();
52 53 54
      iosDeploy = IOSDeploy(
        artifacts: mockArtifacts,
        cache: mockCache,
55
        logger: logger,
56 57 58
        platform: macPlatform,
        processManager: FakeProcessManager.any(),
      );
59 60 61 62 63 64
      iMobileDevice = IMobileDevice(
        artifacts: mockArtifacts,
        cache: mockCache,
        logger: logger,
        processManager: FakeProcessManager.any(),
      );
65 66
    });

67 68 69 70 71
    testWithoutContext('successfully instantiates on Mac OS', () {
      IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
72
        logger: logger,
73 74
        platform: macPlatform,
        iosDeploy: iosDeploy,
75
        iMobileDevice: iMobileDevice,
76 77
        name: 'iPhone 1',
        sdkVersion: '13.3',
78 79
        cpuArchitecture: DarwinArch.arm64,
        interfaceType: IOSDeviceInterface.usb,
80
        vmServiceConnectUri: (String string, {Log log}) async => mockVmService,
81 82 83 84 85 86 87 88
      );
    });

    testWithoutContext('parses major version', () {
      expect(IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
89
        logger: logger,
90 91
        platform: macPlatform,
        iosDeploy: iosDeploy,
92
        iMobileDevice: iMobileDevice,
93 94
        name: 'iPhone 1',
        cpuArchitecture: DarwinArch.arm64,
95 96
        sdkVersion: '1.0.0',
        interfaceType: IOSDeviceInterface.usb,
97
        vmServiceConnectUri: (String string, {Log log}) async => mockVmService,
98 99 100 101 102
      ).majorSdkVersion, 1);
      expect(IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
103
        logger: logger,
104 105
        platform: macPlatform,
        iosDeploy: iosDeploy,
106
        iMobileDevice: iMobileDevice,
107 108
        name: 'iPhone 1',
        cpuArchitecture: DarwinArch.arm64,
109 110
        sdkVersion: '13.1.1',
        interfaceType: IOSDeviceInterface.usb,
111
        vmServiceConnectUri: (String string, {Log log}) async => mockVmService,
112 113 114 115 116
      ).majorSdkVersion, 13);
      expect(IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
117
        logger: logger,
118 119
        platform: macPlatform,
        iosDeploy: iosDeploy,
120
        iMobileDevice: iMobileDevice,
121 122
        name: 'iPhone 1',
        cpuArchitecture: DarwinArch.arm64,
123 124
        sdkVersion: '10',
        interfaceType: IOSDeviceInterface.usb,
125
        vmServiceConnectUri: (String string, {Log log}) async => mockVmService,
126 127 128 129 130
      ).majorSdkVersion, 10);
      expect(IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
131
        logger: logger,
132 133
        platform: macPlatform,
        iosDeploy: iosDeploy,
134
        iMobileDevice: iMobileDevice,
135 136
        name: 'iPhone 1',
        cpuArchitecture: DarwinArch.arm64,
137 138
        sdkVersion: '0',
        interfaceType: IOSDeviceInterface.usb,
139
        vmServiceConnectUri: (String string, {Log log}) async => mockVmService,
140 141 142 143 144
      ).majorSdkVersion, 0);
      expect(IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
145
        logger: logger,
146 147
        platform: macPlatform,
        iosDeploy: iosDeploy,
148
        iMobileDevice: iMobileDevice,
149 150
        name: 'iPhone 1',
        cpuArchitecture: DarwinArch.arm64,
151 152
        sdkVersion: 'bogus',
        interfaceType: IOSDeviceInterface.usb,
153
        vmServiceConnectUri: (String string, {Log log}) async => mockVmService,
154
      ).majorSdkVersion, 0);
155 156
    });

157 158 159 160 161 162 163 164 165 166 167 168 169
    testWithoutContext('Supports debug, profile, and release modes', () {
      final IOSDevice device = IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
        logger: logger,
        platform: macPlatform,
        iosDeploy: iosDeploy,
        iMobileDevice: iMobileDevice,
        name: 'iPhone 1',
        sdkVersion: '13.3',
        cpuArchitecture: DarwinArch.arm64,
        interfaceType: IOSDeviceInterface.usb,
170
        vmServiceConnectUri: (String string, {Log log}) async => mockVmService,
171 172 173 174 175 176 177 178
      );

      expect(device.supportsRuntimeMode(BuildMode.debug), true);
      expect(device.supportsRuntimeMode(BuildMode.profile), true);
      expect(device.supportsRuntimeMode(BuildMode.release), true);
      expect(device.supportsRuntimeMode(BuildMode.jitRelease), false);
    });

179
    for (final Platform platform in unsupportedPlatforms) {
180
      testWithoutContext('throws UnsupportedError exception if instantiated on ${platform.operatingSystem}', () {
181
        expect(
182 183 184 185 186
          () {
            IOSDevice(
              'device-123',
              artifacts: mockArtifacts,
              fileSystem: mockFileSystem,
187
              logger: logger,
188 189
              platform: platform,
              iosDeploy: iosDeploy,
190
              iMobileDevice: iMobileDevice,
191 192 193
              name: 'iPhone 1',
              sdkVersion: '13.3',
              cpuArchitecture: DarwinArch.arm64,
194
              interfaceType: IOSDeviceInterface.usb,
195
              vmServiceConnectUri: (String string, {Log log}) async => mockVmService,
196 197
            );
          },
Dan Field's avatar
Dan Field committed
198
          throwsAssertionError,
199
        );
200 201 202
      });
    }

203 204
    group('.dispose()', () {
      IOSDevice device;
205 206
      MockIOSApp appPackage1;
      MockIOSApp appPackage2;
207 208 209 210 211 212 213
      IOSDeviceLogReader logReader1;
      IOSDeviceLogReader logReader2;
      MockProcess mockProcess1;
      MockProcess mockProcess2;
      MockProcess mockProcess3;
      IOSDevicePortForwarder portForwarder;
      ForwardedPort forwardedPort;
214 215
      Artifacts mockArtifacts;
      MockCache mockCache;
216
      Logger logger;
217 218
      IOSDeploy iosDeploy;
      FileSystem mockFileSystem;
219 220 221 222

      IOSDevicePortForwarder createPortForwarder(
          ForwardedPort forwardedPort,
          IOSDevice device) {
223 224 225 226 227 228 229
        final IOSDevicePortForwarder portForwarder = IOSDevicePortForwarder(
          dyLdLibEntry: mockCache.dyLdLibEntry,
          id: device.id,
          iproxyPath: mockArtifacts.getArtifactPath(Artifact.iproxy, platform: TargetPlatform.ios),
          logger: logger,
          processManager: FakeProcessManager.any(),
        );
230 231 232 233 234 235
        portForwarder.addForwardedPorts(<ForwardedPort>[forwardedPort]);
        return portForwarder;
      }

      IOSDeviceLogReader createLogReader(
          IOSDevice device,
236
          IOSApp appPackage,
237
          Process process) {
238 239 240 241 242
        final IOSDeviceLogReader logReader = IOSDeviceLogReader.create(
          device: device,
          app: appPackage,
          iMobileDevice: null, // not used by this test.
        );
243 244 245 246 247
        logReader.idevicesyslogProcess = process;
        return logReader;
      }

      setUp(() {
248 249
        appPackage1 = MockIOSApp();
        appPackage2 = MockIOSApp();
250 251 252 253 254 255
        when(appPackage1.name).thenReturn('flutterApp1');
        when(appPackage2.name).thenReturn('flutterApp2');
        mockProcess1 = MockProcess();
        mockProcess2 = MockProcess();
        mockProcess3 = MockProcess();
        forwardedPort = ForwardedPort.withContext(123, 456, mockProcess3);
256 257 258 259 260
        mockArtifacts = MockArtifacts();
        mockCache = MockCache();
        iosDeploy = IOSDeploy(
          artifacts: mockArtifacts,
          cache: mockCache,
261
          logger: logger,
262 263 264
          platform: macPlatform,
          processManager: FakeProcessManager.any(),
        );
265 266
      });

267 268 269 270 271
      testWithoutContext('kills all log readers & port forwarders', () async {
        device = IOSDevice(
          '123',
          artifacts: mockArtifacts,
          fileSystem: mockFileSystem,
272
          logger: logger,
273 274
          platform: macPlatform,
          iosDeploy: iosDeploy,
275
          iMobileDevice: iMobileDevice,
276 277 278
          name: 'iPhone 1',
          sdkVersion: '13.3',
          cpuArchitecture: DarwinArch.arm64,
279
          interfaceType: IOSDeviceInterface.usb,
280
          vmServiceConnectUri: (String string, {Log log}) async => mockVmService,
281
        );
282 283 284 285 286 287 288
        logReader1 = createLogReader(device, appPackage1, mockProcess1);
        logReader2 = createLogReader(device, appPackage2, mockProcess2);
        portForwarder = createPortForwarder(forwardedPort, device);
        device.setLogReader(appPackage1, logReader1);
        device.setLogReader(appPackage2, logReader2);
        device.portForwarder = portForwarder;

289
        await device.dispose();
290 291 292 293 294 295

        verify(mockProcess1.kill());
        verify(mockProcess2.kill());
        verify(mockProcess3.kill());
      });
    });
296
  });
297

298
  group('polling', () {
299
    MockXcdevice mockXcdevice;
300 301
    MockArtifacts mockArtifacts;
    MockCache mockCache;
302 303
    MockVmService mockVmService1;
    MockVmService mockVmService2;
304
    FakeProcessManager fakeProcessManager;
305
    BufferLogger logger;
306
    IOSDeploy iosDeploy;
307
    IMobileDevice iMobileDevice;
308
    IOSWorkflow mockIosWorkflow;
309 310
    IOSDevice device1;
    IOSDevice device2;
311 312

    setUp(() {
313
      mockXcdevice = MockXcdevice();
314 315
      mockArtifacts = MockArtifacts();
      mockCache = MockCache();
316 317
      mockVmService1 = MockVmService();
      mockVmService2 = MockVmService();
318
      logger = BufferLogger.test();
319 320
      mockIosWorkflow = MockIOSWorkflow();
      fakeProcessManager = FakeProcessManager.any();
321 322 323
      iosDeploy = IOSDeploy(
        artifacts: mockArtifacts,
        cache: mockCache,
324
        logger: logger,
325
        platform: macPlatform,
326
        processManager: fakeProcessManager,
327
      );
328 329 330 331 332 333
      iMobileDevice = IMobileDevice(
        artifacts: mockArtifacts,
        cache: mockCache,
        processManager: fakeProcessManager,
        logger: logger,
      );
334 335 336 337 338 339 340 341 342 343 344 345 346

      device1 = IOSDevice(
        'd83d5bc53967baa0ee18626ba87b6254b2ab5418',
        name: 'Paired iPhone',
        sdkVersion: '13.3',
        cpuArchitecture: DarwinArch.arm64,
        artifacts: mockArtifacts,
        iosDeploy: iosDeploy,
        iMobileDevice: iMobileDevice,
        logger: logger,
        platform: macPlatform,
        fileSystem: MemoryFileSystem.test(),
        interfaceType: IOSDeviceInterface.usb,
347
        vmServiceConnectUri: (String string, {Log log}) async => mockVmService1,
348 349 350 351 352 353 354 355 356 357 358 359 360 361
      );

      device2 = IOSDevice(
        '43ad2fda7991b34fe1acbda82f9e2fd3d6ddc9f7',
        name: 'iPhone 6s',
        sdkVersion: '13.3',
        cpuArchitecture: DarwinArch.arm64,
        artifacts: mockArtifacts,
        iosDeploy: iosDeploy,
        iMobileDevice: iMobileDevice,
        logger: logger,
        platform: macPlatform,
        fileSystem: MemoryFileSystem.test(),
        interfaceType: IOSDeviceInterface.usb,
362
        vmServiceConnectUri: (String string, {Log log}) async => mockVmService2,
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 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 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
      );
    });

    testWithoutContext('start polling', () async {
      final IOSDevices iosDevices = IOSDevices(
        platform: macPlatform,
        xcdevice: mockXcdevice,
        iosWorkflow: mockIosWorkflow,
        logger: logger,
      );
      when(mockXcdevice.isInstalled).thenReturn(true);

      int fetchDevicesCount = 0;
      when(mockXcdevice.getAvailableIOSDevices())
        .thenAnswer((Invocation invocation) {
          if (fetchDevicesCount == 0) {
            // Initial time, no devices.
            fetchDevicesCount++;
            return Future<List<IOSDevice>>.value(<IOSDevice>[]);
          } else if (fetchDevicesCount == 1) {
            // Simulate 2 devices added later.
            fetchDevicesCount++;
            return Future<List<IOSDevice>>.value(<IOSDevice>[device1, device2]);
          }
          fail('Too many calls to getAvailableTetheredIOSDevices');
      });

      int addedCount = 0;
      final Completer<void> added = Completer<void>();
      iosDevices.onAdded.listen((Device device) {
        addedCount++;
        // 2 devices will be added.
        // Will throw over-completion if called more than twice.
        if (addedCount >= 2) {
          added.complete();
        }
      });

      final Completer<void> removed = Completer<void>();
      iosDevices.onRemoved.listen((Device device) {
        // Will throw over-completion if called more than once.
        removed.complete();
      });

      final StreamController<Map<XCDeviceEvent, String>> eventStream = StreamController<Map<XCDeviceEvent, String>>();
      when(mockXcdevice.observedDeviceEvents()).thenAnswer((_) => eventStream.stream);

      await iosDevices.startPolling();
      verify(mockXcdevice.getAvailableIOSDevices()).called(1);

      expect(iosDevices.deviceNotifier.items, isEmpty);
      expect(eventStream.hasListener, isTrue);

      eventStream.add(<XCDeviceEvent, String>{
        XCDeviceEvent.attach: 'd83d5bc53967baa0ee18626ba87b6254b2ab5418'
      });
      await added.future;
      expect(iosDevices.deviceNotifier.items.length, 2);
      expect(iosDevices.deviceNotifier.items, contains(device1));
      expect(iosDevices.deviceNotifier.items, contains(device2));

      eventStream.add(<XCDeviceEvent, String>{
        XCDeviceEvent.detach: 'd83d5bc53967baa0ee18626ba87b6254b2ab5418'
      });
      await removed.future;
      expect(iosDevices.deviceNotifier.items, <Device>[device2]);

      // Remove stream will throw over-completion if called more than once
      // which proves this is ignored.
      eventStream.add(<XCDeviceEvent, String>{
        XCDeviceEvent.detach: 'bogus'
      });

      expect(addedCount, 2);

      await iosDevices.stopPolling();

      expect(eventStream.hasListener, isFalse);
    });

    testWithoutContext('polling can be restarted if stream is closed', () async {
      final IOSDevices iosDevices = IOSDevices(
        platform: macPlatform,
        xcdevice: mockXcdevice,
        iosWorkflow: mockIosWorkflow,
        logger: logger,
      );
      when(mockXcdevice.isInstalled).thenReturn(true);

      when(mockXcdevice.getAvailableIOSDevices())
        .thenAnswer((Invocation invocation) => Future<List<IOSDevice>>.value(<IOSDevice>[]));

      final StreamController<Map<XCDeviceEvent, String>> eventStream = StreamController<Map<XCDeviceEvent, String>>();
      final StreamController<Map<XCDeviceEvent, String>> rescheduledStream = StreamController<Map<XCDeviceEvent, String>>();

      bool reschedule = false;
      when(mockXcdevice.observedDeviceEvents()).thenAnswer((Invocation invocation) {
        if (!reschedule) {
          reschedule = true;
          return eventStream.stream;
        }
        return rescheduledStream.stream;
      });

      await iosDevices.startPolling();
      expect(eventStream.hasListener, isTrue);
      verify(mockXcdevice.getAvailableIOSDevices()).called(1);

      // Pretend xcdevice crashed.
      await eventStream.close();
      expect(logger.traceText, contains('xcdevice observe stopped'));

      // Confirm a restart still gets streamed events.
      await iosDevices.startPolling();

      expect(eventStream.hasListener, isFalse);
      expect(rescheduledStream.hasListener, isTrue);

      await iosDevices.stopPolling();
      expect(rescheduledStream.hasListener, isFalse);
483 484
    });

485
    final List<Platform> unsupportedPlatforms = <Platform>[linuxPlatform, windowsPlatform];
486
    for (final Platform unsupportedPlatform in unsupportedPlatforms) {
487
      testWithoutContext('pollingGetDevices throws Unsupported Operation exception on ${unsupportedPlatform.operatingSystem}', () async {
488 489 490 491
        final IOSDevices iosDevices = IOSDevices(
          platform: unsupportedPlatform,
          xcdevice: mockXcdevice,
          iosWorkflow: mockIosWorkflow,
492
          logger: logger,
493
        );
494
        when(mockXcdevice.isInstalled).thenReturn(false);
495
        expect(
496
            () async { await iosDevices.pollingGetDevices(); },
Dan Field's avatar
Dan Field committed
497
            throwsA(isA<UnsupportedError>()),
498 499 500 501
        );
      });
    }

502
    testWithoutContext('pollingGetDevices returns attached devices', () async {
503 504 505 506
      final IOSDevices iosDevices = IOSDevices(
        platform: macPlatform,
        xcdevice: mockXcdevice,
        iosWorkflow: mockIosWorkflow,
507
        logger: logger,
508
      );
509
      when(mockXcdevice.isInstalled).thenReturn(true);
510

511
      when(mockXcdevice.getAvailableIOSDevices())
512
          .thenAnswer((Invocation invocation) => Future<List<IOSDevice>>.value(<IOSDevice>[device1]));
513

514
      final List<Device> devices = await iosDevices.pollingGetDevices();
515
      expect(devices, hasLength(1));
516
      expect(identical(devices.first, device1), isTrue);
517
    });
518
  });
519

520 521
  group('getDiagnostics', () {
    MockXcdevice mockXcdevice;
522
    IOSWorkflow mockIosWorkflow;
523
    Logger logger;
524 525 526

    setUp(() {
      mockXcdevice = MockXcdevice();
527
      mockIosWorkflow = MockIOSWorkflow();
528
      logger = BufferLogger.test();
529 530 531 532 533
    });

    final List<Platform> unsupportedPlatforms = <Platform>[linuxPlatform, windowsPlatform];
    for (final Platform unsupportedPlatform in unsupportedPlatforms) {
      testWithoutContext('throws returns platform diagnostic exception on ${unsupportedPlatform.operatingSystem}', () async {
534 535 536 537
        final IOSDevices iosDevices = IOSDevices(
          platform: unsupportedPlatform,
          xcdevice: mockXcdevice,
          iosWorkflow: mockIosWorkflow,
538
          logger: logger,
539
        );
540
        when(mockXcdevice.isInstalled).thenReturn(false);
541
        expect((await iosDevices.getDiagnostics()).first, 'Control of iOS devices or simulators only supported on macOS.');
542 543 544
      });
    }

545 546 547 548 549
    testWithoutContext('returns diagnostics', () async {
      final IOSDevices iosDevices = IOSDevices(
        platform: macPlatform,
        xcdevice: mockXcdevice,
        iosWorkflow: mockIosWorkflow,
550
        logger: logger,
551
      );
552 553 554 555
      when(mockXcdevice.isInstalled).thenReturn(true);
      when(mockXcdevice.getDiagnostics())
          .thenAnswer((Invocation invocation) => Future<List<String>>.value(<String>['Generic pairing error']));

556
      final List<String> diagnostics = await iosDevices.getDiagnostics();
557 558
      expect(diagnostics, hasLength(1));
      expect(diagnostics.first, 'Generic pairing error');
559
    });
560
  });
561
}
562

563 564 565 566 567
class MockIOSApp extends Mock implements IOSApp {}
class MockArtifacts extends Mock implements Artifacts {}
class MockCache extends Mock implements Cache {}
class MockIMobileDevice extends Mock implements IMobileDevice {}
class MockIOSDeploy extends Mock implements IOSDeploy {}
568
class MockIOSWorkflow extends Mock implements IOSWorkflow {}
569
class MockXcdevice extends Mock implements XCDevice {}
570
class MockVmService extends Mock implements VmService {}