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

8
import 'package:args/command_runner.dart';
9
import 'package:file/file.dart';
10
import 'package:file/memory.dart';
11
import 'package:flutter_tools/src/application_package.dart';
12
import 'package:flutter_tools/src/artifacts.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
import 'package:flutter_tools/src/build_info.dart';
17
import 'package:flutter_tools/src/cache.dart';
18
import 'package:flutter_tools/src/commands/create.dart';
19
import 'package:flutter_tools/src/device.dart';
20
import 'package:flutter_tools/src/doctor.dart';
21
import 'package:flutter_tools/src/ios/devices.dart';
22
import 'package:flutter_tools/src/ios/mac.dart';
23
import 'package:flutter_tools/src/ios/ios_deploy.dart';
24
import 'package:flutter_tools/src/ios/ios_workflow.dart';
25
import 'package:flutter_tools/src/macos/xcode.dart';
26
import 'package:flutter_tools/src/mdns_discovery.dart';
27
import 'package:flutter_tools/src/project.dart';
28
import 'package:flutter_tools/src/reporting/reporting.dart';
29 30
import 'package:flutter_tools/src/globals.dart' as globals;

31
import 'package:meta/meta.dart';
32
import 'package:mockito/mockito.dart';
33
import 'package:platform/platform.dart';
34
import 'package:process/process.dart';
35
import 'package:quiver/testing/async.dart';
36

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

41
void main() {
42 43
  final FakePlatform macPlatform = FakePlatform.fromPlatform(const LocalPlatform());
  macPlatform.operatingSystem = 'macos';
44 45 46 47
  final FakePlatform linuxPlatform = FakePlatform.fromPlatform(const LocalPlatform());
  linuxPlatform.operatingSystem = 'linux';
  final FakePlatform windowsPlatform = FakePlatform.fromPlatform(const LocalPlatform());
  windowsPlatform.operatingSystem = 'windows';
48

49 50
  group('IOSDevice', () {
    final List<Platform> unsupportedPlatforms = <Platform>[linuxPlatform, windowsPlatform];
51 52
    Artifacts mockArtifacts;
    MockCache mockCache;
53
    Logger logger;
54 55
    IOSDeploy iosDeploy;
    FileSystem mockFileSystem;
56

57 58 59 60 61 62
    setUp(() {
      mockArtifacts = MockArtifacts();
      mockCache = MockCache();
      const MapEntry<String, String> dyLdLibEntry = MapEntry<String, String>('DYLD_LIBRARY_PATH', '/path/to/libs');
      when(mockCache.dyLdLibEntry).thenReturn(dyLdLibEntry);
      mockFileSystem = MockFileSystem();
63
      logger = BufferLogger.test();
64 65 66
      iosDeploy = IOSDeploy(
        artifacts: mockArtifacts,
        cache: mockCache,
67
        logger: logger,
68 69 70
        platform: macPlatform,
        processManager: FakeProcessManager.any(),
      );
71 72
    });

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    testWithoutContext('successfully instantiates on Mac OS', () {
      IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
        platform: macPlatform,
        iosDeploy: iosDeploy,
        name: 'iPhone 1',
        sdkVersion: '13.3',
        cpuArchitecture: DarwinArch.arm64
      );
    });

    testWithoutContext('parses major version', () {
      expect(IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
        platform: macPlatform,
        iosDeploy: iosDeploy,
        name: 'iPhone 1',
        cpuArchitecture: DarwinArch.arm64,
        sdkVersion: '1.0.0'
      ).majorSdkVersion, 1);
      expect(IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
        platform: macPlatform,
        iosDeploy: iosDeploy,
        name: 'iPhone 1',
        cpuArchitecture: DarwinArch.arm64,
        sdkVersion: '13.1.1'
      ).majorSdkVersion, 13);
      expect(IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
        platform: macPlatform,
        iosDeploy: iosDeploy,
        name: 'iPhone 1',
        cpuArchitecture: DarwinArch.arm64,
        sdkVersion: '10'
      ).majorSdkVersion, 10);
      expect(IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
        platform: macPlatform,
        iosDeploy: iosDeploy,
        name: 'iPhone 1',
        cpuArchitecture: DarwinArch.arm64,
        sdkVersion: '0'
      ).majorSdkVersion, 0);
      expect(IOSDevice(
        'device-123',
        artifacts: mockArtifacts,
        fileSystem: mockFileSystem,
        platform: macPlatform,
        iosDeploy: iosDeploy,
        name: 'iPhone 1',
        cpuArchitecture: DarwinArch.arm64,
        sdkVersion: 'bogus'
      ).majorSdkVersion, 0);
137 138
    });

139
    for (final Platform platform in unsupportedPlatforms) {
140
      testWithoutContext('throws UnsupportedError exception if instantiated on ${platform.operatingSystem}', () {
141
        expect(
142 143 144 145 146 147 148 149 150 151 152 153
          () {
            IOSDevice(
              'device-123',
              artifacts: mockArtifacts,
              fileSystem: mockFileSystem,
              platform: platform,
              iosDeploy: iosDeploy,
              name: 'iPhone 1',
              sdkVersion: '13.3',
              cpuArchitecture: DarwinArch.arm64,
            );
          },
Dan Field's avatar
Dan Field committed
154
          throwsAssertionError,
155
        );
156 157 158
      });
    }

159 160 161 162 163 164 165 166 167 168 169
    group('ios-deploy wrappers', () {
      const String appId = '789';
      IOSDevice device;
      IOSDeploy iosDeploy;
      FullMockProcessManager mockProcessManager;

      setUp(() {
        mockProcessManager = FullMockProcessManager();
        iosDeploy = IOSDeploy(
          artifacts: mockArtifacts,
          cache: mockCache,
170
          logger: logger,
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 229 230 231
          platform: macPlatform,
          processManager: mockProcessManager,
        );

        device = IOSDevice(
          'device-123',
          artifacts: mockArtifacts,
          fileSystem: mockFileSystem,
          platform: macPlatform,
          iosDeploy: iosDeploy,
          name: 'iPhone 1',
          sdkVersion: '13.3',
          cpuArchitecture: DarwinArch.arm64,
        );
      });

      testUsingContext('isAppInstalled() catches ProcessException from ios-deploy', () async {
        final MockIOSApp mockApp = MockIOSApp();
        when(mockApp.id).thenReturn(appId);
        when(mockProcessManager.run(
          any,
          workingDirectory: anyNamed('workingDirectory'),
          environment: anyNamed('environment'),
        )).thenThrow(const ProcessException('ios-deploy', <String>[]));

        final bool result = await device.isAppInstalled(mockApp);
        expect(result, false);
      });

      testUsingContext('installApp() catches ProcessException from ios-deploy', () async {
        const String bundlePath = '/path/to/bundle';
        final MockIOSApp mockApp = MockIOSApp();
        when(mockApp.id).thenReturn(appId);
        when(mockApp.deviceBundlePath).thenReturn(bundlePath);
        final MockDirectory mockDirectory = MockDirectory();
        when(mockFileSystem.directory(bundlePath)).thenReturn(mockDirectory);
        when(mockDirectory.existsSync()).thenReturn(true);
        when(mockProcessManager.start(
          any,
          workingDirectory: anyNamed('workingDirectory'),
          environment: anyNamed('environment'),
        )).thenThrow(const ProcessException('ios-deploy', <String>[]));

        final bool result = await device.installApp(mockApp);
        expect(result, false);
      });

      testUsingContext('uninstallApp() catches ProcessException from ios-deploy', () async {
        final MockIOSApp mockApp = MockIOSApp();
        when(mockApp.id).thenReturn(appId);
        when(mockProcessManager.start(
          any,
          workingDirectory: anyNamed('workingDirectory'),
          environment: anyNamed('environment'),
        )).thenThrow(const ProcessException('ios-deploy', <String>[]));

        final bool result = await device.uninstallApp(mockApp);
        expect(result, false);
      });
    });

232 233
    group('.dispose()', () {
      IOSDevice device;
234 235
      MockIOSApp appPackage1;
      MockIOSApp appPackage2;
236 237 238 239 240 241 242
      IOSDeviceLogReader logReader1;
      IOSDeviceLogReader logReader2;
      MockProcess mockProcess1;
      MockProcess mockProcess2;
      MockProcess mockProcess3;
      IOSDevicePortForwarder portForwarder;
      ForwardedPort forwardedPort;
243 244
      Artifacts mockArtifacts;
      MockCache mockCache;
245
      Logger logger;
246 247
      IOSDeploy iosDeploy;
      FileSystem mockFileSystem;
248 249 250 251 252 253 254 255 256 257 258

      IOSDevicePortForwarder createPortForwarder(
          ForwardedPort forwardedPort,
          IOSDevice device) {
        final IOSDevicePortForwarder portForwarder = IOSDevicePortForwarder(device);
        portForwarder.addForwardedPorts(<ForwardedPort>[forwardedPort]);
        return portForwarder;
      }

      IOSDeviceLogReader createLogReader(
          IOSDevice device,
259
          IOSApp appPackage,
260 261 262 263 264 265 266
          Process process) {
        final IOSDeviceLogReader logReader = IOSDeviceLogReader(device, appPackage);
        logReader.idevicesyslogProcess = process;
        return logReader;
      }

      setUp(() {
267 268
        appPackage1 = MockIOSApp();
        appPackage2 = MockIOSApp();
269 270 271 272 273 274
        when(appPackage1.name).thenReturn('flutterApp1');
        when(appPackage2.name).thenReturn('flutterApp2');
        mockProcess1 = MockProcess();
        mockProcess2 = MockProcess();
        mockProcess3 = MockProcess();
        forwardedPort = ForwardedPort.withContext(123, 456, mockProcess3);
275 276 277 278 279 280
        mockArtifacts = MockArtifacts();
        mockCache = MockCache();
        mockFileSystem = MockFileSystem();
        iosDeploy = IOSDeploy(
          artifacts: mockArtifacts,
          cache: mockCache,
281
          logger: logger,
282 283 284
          platform: macPlatform,
          processManager: FakeProcessManager.any(),
        );
285 286
      });

287 288 289 290 291 292 293 294 295 296 297
      testWithoutContext('kills all log readers & port forwarders', () async {
        device = IOSDevice(
          '123',
          artifacts: mockArtifacts,
          fileSystem: mockFileSystem,
          platform: macPlatform,
          iosDeploy: iosDeploy,
          name: 'iPhone 1',
          sdkVersion: '13.3',
          cpuArchitecture: DarwinArch.arm64,
        );
298 299 300 301 302 303 304
        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;

305
        await device.dispose();
306 307 308 309 310 311 312

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

313 314 315 316 317
    group('startApp', () {
      MockIOSApp mockApp;
      MockArtifacts mockArtifacts;
      MockCache mockCache;
      MockFileSystem mockFileSystem;
318
      MockPlatform mockPlatform;
319 320
      MockProcessManager mockProcessManager;
      MockDeviceLogReader mockLogReader;
321
      MockMDnsObservatoryDiscovery mockMDnsObservatoryDiscovery;
322
      MockPortForwarder mockPortForwarder;
323 324
      MockIMobileDevice mockIMobileDevice;
      MockIOSDeploy mockIosDeploy;
325
      MockUsage mockUsage;
326 327 328

      Directory tempDir;
      Directory projectDir;
329 330 331 332 333

      const int devicePort = 499;
      const int hostPort = 42;
      const String installerPath = '/path/to/ideviceinstaller';
      const String iosDeployPath = '/path/to/iosdeploy';
334
      const String iproxyPath = '/path/to/iproxy';
335 336
      const MapEntry<String, String> libraryEntry = MapEntry<String, String>(
          'DYLD_LIBRARY_PATH',
337
          '/path/to/libraries',
338 339 340 341 342 343
      );
      final Map<String, String> env = Map<String, String>.fromEntries(
          <MapEntry<String, String>>[libraryEntry]
      );

      setUp(() {
344 345
        Cache.disableLocking();

346 347 348 349 350
        mockApp = MockIOSApp();
        mockArtifacts = MockArtifacts();
        mockCache = MockCache();
        when(mockCache.dyLdLibEntry).thenReturn(libraryEntry);
        mockFileSystem = MockFileSystem();
351 352
        mockPlatform = MockPlatform();
        when(mockPlatform.isMacOS).thenReturn(true);
353
        mockMDnsObservatoryDiscovery = MockMDnsObservatoryDiscovery();
354 355 356
        mockProcessManager = MockProcessManager();
        mockLogReader = MockDeviceLogReader();
        mockPortForwarder = MockPortForwarder();
357 358
        mockIMobileDevice = MockIMobileDevice();
        mockIosDeploy = MockIOSDeploy();
359
        mockUsage = MockUsage();
360

361
        tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_create_test.');
362
        projectDir = tempDir.childDirectory('flutter_project');
363 364 365 366 367

        when(
            mockArtifacts.getArtifactPath(
                Artifact.ideviceinstaller,
                platform: anyNamed('platform'),
368
            ),
369 370 371 372 373 374
        ).thenReturn(installerPath);

        when(
            mockArtifacts.getArtifactPath(
                Artifact.iosDeploy,
                platform: anyNamed('platform'),
375
            ),
376 377
        ).thenReturn(iosDeployPath);

378 379 380 381 382 383 384
        when(
            mockArtifacts.getArtifactPath(
                Artifact.iproxy,
                platform: anyNamed('platform'),
            ),
        ).thenReturn(iproxyPath);

385 386 387 388 389 390 391
        when(mockPortForwarder.forward(devicePort, hostPort: anyNamed('hostPort')))
          .thenAnswer((_) async => hostPort);
        when(mockPortForwarder.forwardedPorts)
          .thenReturn(<ForwardedPort>[ForwardedPort(hostPort, devicePort)]);
        when(mockPortForwarder.unforward(any))
          .thenAnswer((_) async => null);

392 393 394 395
        final MemoryFileSystem memoryFileSystem = MemoryFileSystem();
        when(mockFileSystem.currentDirectory)
          .thenReturn(memoryFileSystem.currentDirectory);

396 397 398 399 400 401
        const String bundlePath = '/path/to/bundle';
        final List<String> installArgs = <String>[installerPath, '-i', bundlePath];
        when(mockApp.deviceBundlePath).thenReturn(bundlePath);
        final MockDirectory directory = MockDirectory();
        when(mockFileSystem.directory(bundlePath)).thenReturn(directory);
        when(directory.existsSync()).thenReturn(true);
402 403 404
        when(mockProcessManager.run(
          installArgs,
          workingDirectory: anyNamed('workingDirectory'),
405
          environment: env,
406 407 408
        )).thenAnswer(
          (_) => Future<ProcessResult>.value(ProcessResult(1, 0, '', ''))
        );
409 410 411 412
      });

      tearDown(() {
        mockLogReader.dispose();
413 414 415
        tryToDelete(tempDir);

        Cache.enableLocking();
416 417
      });

418
      testUsingContext('disposing device disposes the portForwarder', () async {
419 420 421 422 423 424 425 426 427 428
        final IOSDevice device = IOSDevice(
          '123',
          artifacts: mockArtifacts,
          fileSystem: mockFileSystem,
          platform: macPlatform,
          iosDeploy: iosDeploy,
          name: 'iPhone 1',
          sdkVersion: '13.3',
          cpuArchitecture: DarwinArch.arm64,
        );
429 430 431 432 433 434
        device.portForwarder = mockPortForwarder;
        device.setLogReader(mockApp, mockLogReader);
        await device.dispose();
        verify(mockPortForwarder.dispose()).called(1);
      });

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
      testUsingContext('succeeds in debug mode via mDNS', () async {
        final IOSDevice device = IOSDevice(
          '123',
          name: 'iPhone 1',
          sdkVersion: '13.3',
          artifacts: mockArtifacts,
          fileSystem: mockFileSystem,
          platform: macPlatform,
          iosDeploy: mockIosDeploy,
          cpuArchitecture: DarwinArch.arm64,
        );
        when(mockIosDeploy.installApp(
          deviceId: device.id,
          bundlePath: anyNamed('bundlePath'),
          launchArguments: <String>[],
        )).thenAnswer((Invocation invocation) => Future<int>.value(0));
        when(mockIosDeploy.runApp(
          deviceId: device.id,
          bundlePath: anyNamed('bundlePath'),
          launchArguments: anyNamed('launchArguments'),
        )).thenAnswer((Invocation invocation) => Future<int>.value(0));
456 457
        device.portForwarder = mockPortForwarder;
        device.setLogReader(mockApp, mockLogReader);
458 459 460 461 462 463
        final Uri uri = Uri(
          scheme: 'http',
          host: '127.0.0.1',
          port: 1234,
          path: 'observatory',
        );
464
        when(mockMDnsObservatoryDiscovery.getObservatoryUri(any, any, usesIpv6: anyNamed('usesIpv6')))
465
          .thenAnswer((Invocation invocation) => Future<Uri>.value(uri));
466 467 468

        final LaunchResult launchResult = await device.startApp(mockApp,
          prebuiltApplication: true,
469
          debuggingOptions: DebuggingOptions.enabled(const BuildInfo(BuildMode.debug, null, treeShakeIcons: false)),
470 471
          platformArgs: <String, dynamic>{},
        );
472
        verify(mockUsage.sendEvent('ios-handshake', 'mdns-success')).called(1);
473 474 475 476 477 478 479
        expect(launchResult.started, isTrue);
        expect(launchResult.hasObservatory, isTrue);
        expect(await device.stopApp(mockApp), isFalse);
      }, overrides: <Type, Generator>{
        Artifacts: () => mockArtifacts,
        Cache: () => mockCache,
        FileSystem: () => mockFileSystem,
480
        MDnsObservatoryDiscovery: () => mockMDnsObservatoryDiscovery,
481 482
        Platform: () => macPlatform,
        ProcessManager: () => mockProcessManager,
483
        Usage: () => mockUsage,
484 485
      });

486 487 488
      // By default, the .forward() method will try every port between 1024
      // and 65535; this test verifies we are killing iproxy processes when
      // we timeout on a port
489
      testUsingContext('.forward() will kill iproxy processes before invoking a second', () async {
490 491
        const String deviceId = '123';
        const int devicePort = 456;
492 493 494 495 496 497 498 499 500 501
        final IOSDevice device = IOSDevice(
          deviceId,
          artifacts: mockArtifacts,
          fileSystem: mockFileSystem,
          platform: macPlatform,
          iosDeploy: iosDeploy,
          name: 'iPhone 1',
          sdkVersion: '13.3',
          cpuArchitecture: DarwinArch.arm64,
        );
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
        final IOSDevicePortForwarder portForwarder = IOSDevicePortForwarder(device);
        bool firstRun = true;
        final MockProcess successProcess = MockProcess(
          exitCode: Future<int>.value(0),
          stdout: Stream<List<int>>.fromIterable(<List<int>>['Hello'.codeUnits]),
        );
        final MockProcess failProcess = MockProcess(
          exitCode: Future<int>.value(1),
          stdout: const Stream<List<int>>.empty(),
        );

        final ProcessFactory factory = (List<String> command) {
          if (!firstRun) {
            return successProcess;
          }
          firstRun = false;
          return failProcess;
        };
        mockProcessManager.processFactory = factory;
        final int hostPort = await portForwarder.forward(devicePort);
        // First port tried (1024) should fail, then succeed on the next
        expect(hostPort, 1024 + 1);
        verifyNever(successProcess.kill());
        verify(failProcess.kill());
      }, overrides: <Type, Generator>{
        Artifacts: () => mockArtifacts,
        Cache: () => mockCache,
        Platform: () => macPlatform,
        ProcessManager: () => mockProcessManager,
        Usage: () => mockUsage,
      });

534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
      testUsingContext('succeeds in debug mode when mDNS fails by falling back to manual protocol discovery', () async {
        final IOSDevice device = IOSDevice(
          '123',
          artifacts: mockArtifacts,
          fileSystem: mockFileSystem,
          platform: macPlatform,
          iosDeploy: mockIosDeploy,
          name: 'iPhone 1',
          sdkVersion: '13.3',
          cpuArchitecture: DarwinArch.arm64,
        );
        when(
          mockIosDeploy.installApp(deviceId: device.id, bundlePath: anyNamed('bundlePath'), launchArguments: <String>[])
        ).thenAnswer((Invocation invocation) => Future<int>.value(0));
        when(mockIosDeploy.runApp(
          deviceId: device.id,
          bundlePath: anyNamed('bundlePath'),
          launchArguments: anyNamed('launchArguments'),
        )).thenAnswer((Invocation invocation) => Future<int>.value(0));
553 554 555 556 557 558 559
        device.portForwarder = mockPortForwarder;
        device.setLogReader(mockApp, mockLogReader);
        // 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');
        });
560
        when(mockMDnsObservatoryDiscovery.getObservatoryUri(any, any, usesIpv6: anyNamed('usesIpv6')))
561 562
          .thenAnswer((Invocation invocation) => Future<Uri>.value(null));

563 564
        final LaunchResult launchResult = await device.startApp(mockApp,
          prebuiltApplication: true,
565
          debuggingOptions: DebuggingOptions.enabled(const BuildInfo(BuildMode.debug, null, treeShakeIcons: false)),
566 567 568
          platformArgs: <String, dynamic>{},
        );
        expect(launchResult.started, isTrue);
569
        expect(launchResult.hasObservatory, isTrue);
570 571
        verify(mockUsage.sendEvent('ios-handshake', 'mdns-failure')).called(1);
        verify(mockUsage.sendEvent('ios-handshake', 'fallback-success')).called(1);
572 573 574 575 576
        expect(await device.stopApp(mockApp), isFalse);
      }, overrides: <Type, Generator>{
        Artifacts: () => mockArtifacts,
        Cache: () => mockCache,
        FileSystem: () => mockFileSystem,
577
        MDnsObservatoryDiscovery: () => mockMDnsObservatoryDiscovery,
578 579
        Platform: () => macPlatform,
        ProcessManager: () => mockProcessManager,
580
        Usage: () => mockUsage,
581 582
      });

583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
      testUsingContext('fails in debug mode when mDNS fails and when Observatory URI is malformed', () async {
        final IOSDevice device = IOSDevice(
          '123',
          artifacts: mockArtifacts,
          fileSystem: mockFileSystem,
          platform: macPlatform,
          iosDeploy: mockIosDeploy,
          name: 'iPhone 1',
          sdkVersion: '13.3',
          cpuArchitecture: DarwinArch.arm64,
        );
        when(mockIosDeploy.installApp(
          deviceId: device.id,
          bundlePath: anyNamed('bundlePath'),
          launchArguments: <String>[],
        )).thenAnswer((Invocation invocation) => Future<int>.value(0));
        when(mockIosDeploy.runApp(
          deviceId: device.id,
          bundlePath: anyNamed('bundlePath'),
          launchArguments: anyNamed('launchArguments'),
        )).thenAnswer((Invocation invocation) => Future<int>.value(0));
604 605 606 607 608 609 610 611
        device.portForwarder = mockPortForwarder;
        device.setLogReader(mockApp, mockLogReader);

        // 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');
        });
612
        when(mockMDnsObservatoryDiscovery.getObservatoryUri(any, any, usesIpv6: anyNamed('usesIpv6')))
613
          .thenAnswer((Invocation invocation) => Future<Uri>.value(null));
614 615 616

        final LaunchResult launchResult = await device.startApp(mockApp,
            prebuiltApplication: true,
617
            debuggingOptions: DebuggingOptions.enabled(const BuildInfo(BuildMode.debug, null, treeShakeIcons: false)),
618 619
            platformArgs: <String, dynamic>{},
        );
620 621
        expect(launchResult.started, isFalse);
        expect(launchResult.hasObservatory, isFalse);
622 623
        verify(mockUsage.sendEvent(
          'ios-handshake',
624
          'failure-other',
625 626 627
          label: anyNamed('label'),
          value: anyNamed('value'),
        )).called(1);
628 629
        verify(mockUsage.sendEvent('ios-handshake', 'mdns-failure')).called(1);
        verify(mockUsage.sendEvent('ios-handshake', 'fallback-failure')).called(1);
630 631 632 633 634 635 636
      }, overrides: <Type, Generator>{
        Artifacts: () => mockArtifacts,
        Cache: () => mockCache,
        FileSystem: () => mockFileSystem,
        MDnsObservatoryDiscovery: () => mockMDnsObservatoryDiscovery,
        Platform: () => macPlatform,
        ProcessManager: () => mockProcessManager,
637
        Usage: () => mockUsage,
638 639
      });

640
      testUsingContext('succeeds in release mode', () async {
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
        final IOSDevice device = IOSDevice(
          '123',
          name: 'iPhone 1',
          fileSystem: mockFileSystem,
          sdkVersion: '13.3',
          cpuArchitecture: DarwinArch.arm64,
          platform: mockPlatform,
          artifacts: mockArtifacts,
          iosDeploy: mockIosDeploy,
        );
        when(mockIosDeploy.installApp(
          deviceId: device.id,
          bundlePath: anyNamed('bundlePath'),
          launchArguments: <String>[],
        )).thenAnswer((Invocation invocation) => Future<int>.value(0));
        when(mockIosDeploy.runApp(
          deviceId: device.id,
          bundlePath: anyNamed('bundlePath'),
          launchArguments: anyNamed('launchArguments'),
        )).thenAnswer((Invocation invocation) => Future<int>.value(0));
661 662
        final LaunchResult launchResult = await device.startApp(mockApp,
          prebuiltApplication: true,
663
          debuggingOptions: DebuggingOptions.disabled(const BuildInfo(BuildMode.release, null, treeShakeIcons: false)),
664 665
          platformArgs: <String, dynamic>{},
        );
666 667 668 669 670 671 672 673 674 675
        verify(mockIosDeploy.installApp(
          deviceId: device.id,
          bundlePath: anyNamed('bundlePath'),
          launchArguments: <String>[],
        ));
        verify(mockIosDeploy.runApp(
          deviceId: device.id,
          bundlePath: anyNamed('bundlePath'),
          launchArguments: anyNamed('launchArguments'),
        ));
676 677 678
        expect(launchResult.started, isTrue);
        expect(launchResult.hasObservatory, isFalse);
        expect(await device.stopApp(mockApp), isFalse);
679
      });
680

681
      testUsingContext('succeeds with --cache-sksl', () async {
682 683 684 685 686 687 688 689 690 691
        final IOSDevice device = IOSDevice(
          '123',
          name: 'iPhone 1',
          sdkVersion: '13.3',
          artifacts: mockArtifacts,
          fileSystem: mockFileSystem,
          platform: macPlatform,
          iosDeploy: mockIosDeploy,
          cpuArchitecture: DarwinArch.arm64,
        );
692 693 694 695 696 697 698
        device.setLogReader(mockApp, mockLogReader);
        final Uri uri = Uri(
          scheme: 'http',
          host: '127.0.0.1',
          port: 1234,
          path: 'observatory',
        );
699
        when(mockMDnsObservatoryDiscovery.getObservatoryUri(any, any, usesIpv6: anyNamed('usesIpv6')))
700 701 702 703 704 705 706 707
            .thenAnswer((Invocation invocation) => Future<Uri>.value(uri));

        List<String> args;
        when(mockIosDeploy.runApp(
          deviceId: anyNamed('deviceId'),
          bundlePath: anyNamed('bundlePath'),
          launchArguments: anyNamed('launchArguments'),
        )).thenAnswer((Invocation inv) {
708
          args = inv.namedArguments[const Symbol('launchArguments')] as List<String>;
709 710
          return Future<int>.value(0);
        });
711 712 713 714 715
        when(mockIosDeploy.installApp(
          deviceId: device.id,
          bundlePath: anyNamed('bundlePath'),
          launchArguments: anyNamed('launchArguments'),
        )).thenAnswer((Invocation invocation) => Future<int>.value(0));
716 717 718 719

        final LaunchResult launchResult = await device.startApp(mockApp,
          prebuiltApplication: true,
          debuggingOptions: DebuggingOptions.enabled(
720
              const BuildInfo(BuildMode.debug, null, treeShakeIcons: false),
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
              cacheSkSL: true,
          ),
          platformArgs: <String, dynamic>{},
        );
        expect(launchResult.started, isTrue);
        expect(args, contains('--cache-sksl'));
        expect(await device.stopApp(mockApp), isFalse);
      }, overrides: <Type, Generator>{
        Artifacts: () => mockArtifacts,
        Cache: () => mockCache,
        FileSystem: () => mockFileSystem,
        MDnsObservatoryDiscovery: () => mockMDnsObservatoryDiscovery,
        Platform: () => macPlatform,
        ProcessManager: () => mockProcessManager,
        Usage: () => mockUsage,
        IOSDeploy: () => mockIosDeploy,
      });

739
      testUsingContext('succeeds with --device-vmservice-port', () async {
740 741 742 743 744 745 746 747 748 749
        final IOSDevice device = IOSDevice(
          '123',
          name: 'iPhone 1',
          sdkVersion: '13.3',
          artifacts: mockArtifacts,
          fileSystem: mockFileSystem,
          platform: macPlatform,
          iosDeploy: mockIosDeploy,
          cpuArchitecture: DarwinArch.arm64,
        );
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
        device.setLogReader(mockApp, mockLogReader);
        final Uri uri = Uri(
          scheme: 'http',
          host: '127.0.0.1',
          port: 1234,
          path: 'observatory',
        );
        when(mockMDnsObservatoryDiscovery.getObservatoryUri(any, any, usesIpv6: anyNamed('usesIpv6')))
            .thenAnswer((Invocation invocation) => Future<Uri>.value(uri));

        List<String> args;
        when(mockIosDeploy.runApp(
          deviceId: anyNamed('deviceId'),
          bundlePath: anyNamed('bundlePath'),
          launchArguments: anyNamed('launchArguments'),
        )).thenAnswer((Invocation inv) {
          args = inv.namedArguments[const Symbol('launchArguments')] as List<String>;
          return Future<int>.value(0);
        });

770 771 772 773 774
        when(mockIosDeploy.installApp(
          deviceId: device.id,
          bundlePath: anyNamed('bundlePath'),
          launchArguments: anyNamed('launchArguments'),
        )).thenAnswer((Invocation invocation) => Future<int>.value(0));
775 776 777
        final LaunchResult launchResult = await device.startApp(mockApp,
          prebuiltApplication: true,
          debuggingOptions: DebuggingOptions.enabled(
778
            const BuildInfo(BuildMode.debug, null, treeShakeIcons: false),
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
            deviceVmServicePort: 8181,
          ),
          platformArgs: <String, dynamic>{},
        );
        expect(launchResult.started, isTrue);
        expect(args, contains('--observatory-port=8181'));
        expect(await device.stopApp(mockApp), isFalse);
      }, overrides: <Type, Generator>{
        Artifacts: () => mockArtifacts,
        Cache: () => mockCache,
        FileSystem: () => mockFileSystem,
        MDnsObservatoryDiscovery: () => mockMDnsObservatoryDiscovery,
        Platform: () => macPlatform,
        ProcessManager: () => mockProcessManager,
        Usage: () => mockUsage,
        IOSDeploy: () => mockIosDeploy,
      });

797 798
      void testNonPrebuilt(
        String name, {
799
        @required bool showBuildSettingsFlakes,
800 801
        void Function() additionalSetup,
        void Function() additionalExpectations,
802
      }) {
803
        testUsingContext('non-prebuilt succeeds in debug mode $name', () async {
804 805 806 807
          final Directory targetBuildDir =
              projectDir.childDirectory('build/ios/iphoneos/Debug-arm64');

          // The -showBuildSettings calls have a timeout and so go through
808
          // globals.processManager.start().
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
          mockProcessManager.processFactory = flakyProcessFactory(
            flakes: showBuildSettingsFlakes ? 1 : 0,
            delay: const Duration(seconds: 62),
            filter: (List<String> args) => args.contains('-showBuildSettings'),
            stdout:
                () => Stream<String>
                  .fromIterable(
                      <String>['TARGET_BUILD_DIR = ${targetBuildDir.path}\n'])
                  .transform(utf8.encoder),
          );

          // Make all other subcommands succeed.
          when(mockProcessManager.run(
              any,
              workingDirectory: anyNamed('workingDirectory'),
              environment: anyNamed('environment'),
          )).thenAnswer((Invocation inv) {
            return Future<ProcessResult>.value(ProcessResult(0, 0, '', ''));
          });

829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
          when(mockProcessManager.run(
            argThat(contains('find-identity')),
            environment: anyNamed('environment'),
            workingDirectory: anyNamed('workingDirectory'),
          )).thenAnswer((_) => Future<ProcessResult>.value(ProcessResult(
                1, // pid
                0, // exitCode
                '''
    1) 86f7e437faa5a7fce15d1ddcb9eaeaea377667b8 "iPhone Developer: Profile 1 (1111AAAA11)"
    2) da4b9237bacccdf19c0760cab7aec4a8359010b0 "iPhone Developer: Profile 2 (2222BBBB22)"
    3) 5bf1fd927dfb8679496a2e6cf00cbe50c1c87145 "iPhone Developer: Profile 3 (3333CCCC33)"
        3 valid identities found''',
                '',
          )));

844 845 846 847 848 849 850 851 852 853 854 855
          // Deploy works.
          when(mockIosDeploy.runApp(
            deviceId: anyNamed('deviceId'),
            bundlePath: anyNamed('bundlePath'),
            launchArguments: anyNamed('launchArguments'),
          )).thenAnswer((_) => Future<int>.value(0));

          // Create a dummy project to avoid mocking out the whole directory
          // structure expected by device.startApp().
          Cache.flutterRoot = '../..';
          final CreateCommand command = CreateCommand();
          final CommandRunner<void> runner = createTestCommandRunner(command);
856 857 858 859 860
          await runner.run(<String>[
            'create',
            '--no-pub',
            projectDir.path,
          ]);
861

862 863 864 865
          if (additionalSetup != null) {
            additionalSetup();
          }

866 867
          final IOSApp app = await AbsoluteBuildableIOSApp.fromProject(
            FlutterProject.fromDirectory(projectDir).ios);
868 869 870 871 872 873 874 875 876 877
          final IOSDevice device = IOSDevice(
            '123',
            name: 'iPhone 1',
            sdkVersion: '13.3',
            artifacts: mockArtifacts,
            fileSystem: globals.fs,
            platform: macPlatform,
            iosDeploy: mockIosDeploy,
            cpuArchitecture: DarwinArch.arm64,
          );
878 879 880

          // Pre-create the expected build products.
          targetBuildDir.createSync(recursive: true);
881
          projectDir.childDirectory('build/ios/iphoneos/Runner.app').createSync(recursive: true);
882 883 884 885 886 887

          final Completer<LaunchResult> completer = Completer<LaunchResult>();
          FakeAsync().run((FakeAsync time) {
            device.startApp(
              app,
              prebuiltApplication: false,
888
              debuggingOptions: DebuggingOptions.disabled(const BuildInfo(BuildMode.debug, null, treeShakeIcons: false)),
889 890 891 892 893 894 895 896 897 898 899
              platformArgs: <String, dynamic>{},
            ).then((LaunchResult result) {
              completer.complete(result);
            });
            time.flushMicrotasks();
            time.elapse(const Duration(seconds: 65));
          });
          final LaunchResult launchResult = await completer.future;
          expect(launchResult.started, isTrue);
          expect(launchResult.hasObservatory, isFalse);
          expect(await device.stopApp(mockApp), isFalse);
900 901 902 903

          if (additionalExpectations != null) {
            additionalExpectations();
          }
904 905 906 907 908 909 910 911
        }, overrides: <Type, Generator>{
          DoctorValidatorsProvider: () => FakeIosDoctorProvider(),
          IMobileDevice: () => mockIMobileDevice,
          Platform: () => macPlatform,
          ProcessManager: () => mockProcessManager,
        });
      }

912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
      testNonPrebuilt('flaky: false', showBuildSettingsFlakes: false);
      testNonPrebuilt('flaky: true', showBuildSettingsFlakes: true);
      testNonPrebuilt('with concurrent build failiure',
        showBuildSettingsFlakes: false,
        additionalSetup: () {
          int callCount = 0;
          when(mockProcessManager.run(
            argThat(allOf(
              contains('xcodebuild'),
              contains('-configuration'),
              contains('Debug'),
            )),
            workingDirectory: anyNamed('workingDirectory'),
            environment: anyNamed('environment'),
          )).thenAnswer((Invocation inv) {
            // Succeed after 2 calls.
            if (++callCount > 2) {
              return Future<ProcessResult>.value(ProcessResult(0, 0, '', ''));
            }
            // Otherwise fail with the Xcode concurrent error.
            return Future<ProcessResult>.value(ProcessResult(
              0,
              1,
              '''
                "/Developer/Xcode/DerivedData/foo/XCBuildData/build.db":
                database is locked
                Possibly there are two concurrent builds running in the same filesystem location.
                ''',
              '',
            ));
          });
        },
        additionalExpectations: () {
          expect(testLogger.statusText, contains('will retry in 2 seconds'));
          expect(testLogger.statusText, contains('will retry in 4 seconds'));
          expect(testLogger.statusText, contains('Xcode build done.'));
        },
      );
950 951
    });

952
    group('Process calls', () {
953 954 955
      const String bundlePath = '/path/to/bundle';
      FileSystem fs;
      MockDirectory directory;
956 957 958 959
      MockIOSApp mockApp;
      MockArtifacts mockArtifacts;
      MockCache mockCache;
      MockFileSystem mockFileSystem;
960
      Logger logger;
961 962 963
      MockPlatform mockPlatform;
      FullMockProcessManager mockProcessManager;
      const String iosDeployPath = '/path/to/ios-deploy';
964 965
      const String appId = '789';
      const MapEntry<String, String> libraryEntry = MapEntry<String, String>(
966 967
        'DYLD_LIBRARY_PATH',
        '/path/to/libraries',
968
      );
969
      IOSDeploy iosDeploy;
970

971
      setUp(() {
972 973 974 975
        mockFileSystem = MockFileSystem();
        directory = MockDirectory();
        when(mockFileSystem.directory(bundlePath)).thenReturn(directory);

976
        mockApp = MockIOSApp();
977 978 979 980 981
        when(mockApp.id).thenReturn(appId);
        when(mockApp.deviceBundlePath).thenReturn(bundlePath);
        when(directory.existsSync()).thenReturn(true);
        when(directory.path).thenReturn(bundlePath);

982 983
        mockArtifacts = MockArtifacts();
        mockCache = MockCache();
984
        logger = BufferLogger.test();
985 986 987 988 989 990 991 992 993 994 995 996 997
        mockPlatform = MockPlatform();
        when(mockPlatform.environment).thenReturn(<String, String>{});
        when(mockPlatform.isMacOS).thenReturn(true);
        mockProcessManager = FullMockProcessManager();
        when(
            mockArtifacts.getArtifactPath(
                Artifact.iosDeploy,
                platform: anyNamed('platform'),
            ),
        ).thenReturn(iosDeployPath);
        iosDeploy = IOSDeploy(
          artifacts: mockArtifacts,
          cache: mockCache,
998
          logger: logger,
999 1000 1001
          platform: mockPlatform,
          processManager: mockProcessManager,
        );
1002 1003
        when(mockCache.dyLdLibEntry).thenReturn(libraryEntry);
        mockFileSystem = MockFileSystem();
1004 1005 1006
        final MemoryFileSystem memoryFileSystem = MemoryFileSystem();
        when(mockFileSystem.currentDirectory)
          .thenReturn(memoryFileSystem.currentDirectory);
1007 1008
      });

1009
      testWithoutContext('installApp() calls ios-deploy', () async {
1010
        when(mockFileSystem.directory(bundlePath)).thenReturn(directory);
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
        final IOSDevice device = IOSDevice(
          '123',
          name: 'iPhone 1',
          fileSystem: mockFileSystem,
          sdkVersion: '13.3',
          cpuArchitecture: DarwinArch.arm64,
          platform: mockPlatform,
          artifacts: mockArtifacts,
          iosDeploy: iosDeploy,
        );
        final List<String> args = <String>[
          iosDeployPath,
          '--id',
          device.id,
          '--bundle',
          bundlePath,
          '--no-wifi',
        ];
        when(mockProcessManager.start(any, workingDirectory: anyNamed('workingDirectory'), environment: anyNamed('environment'))).
            thenAnswer((Invocation invocation) {
              return Future<Process>.value(createMockProcess());
            });

1034 1035
        await device.installApp(mockApp);

1036 1037 1038 1039 1040 1041
        final List<String> invocationArguments = verify(mockProcessManager.start(
          captureAny,
          workingDirectory: anyNamed('workingDirectory'),
          environment: anyNamed('environment'),
        )).captured.first as List<String>;
        expect(invocationArguments, args);
1042 1043
      });

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
      testWithoutContext('uninstallApp() calls ios-deploy', () async {
        final IOSDevice device = IOSDevice(
          '123',
          name: 'iPhone 1',
          fileSystem: fs,
          sdkVersion: '13.3',
          cpuArchitecture: DarwinArch.arm64,
          platform: mockPlatform,
          artifacts: mockArtifacts,
          iosDeploy: iosDeploy,
        );
        final List<String> args = <String>[
          iosDeployPath,
          '--id',
          device.id,
          '--uninstall_only',
          '--bundle_id',
          appId,
        ];
        when(mockProcessManager.start(args, workingDirectory: anyNamed('workingDirectory'), environment: anyNamed('environment'))).
            thenAnswer((Invocation invocation) {
              return Future<Process>.value(createMockProcess());
            });
1067
        await device.uninstallApp(mockApp);
1068 1069 1070 1071 1072 1073
        final List<String> invocationArguments = verify(mockProcessManager.start(
          captureAny,
          workingDirectory: anyNamed('workingDirectory'),
          environment: anyNamed('environment'),
        )).captured.first as List<String>;
        expect(invocationArguments, args);
1074
      });
1075 1076
    });
  });
1077

1078
  group('getAttachedDevices', () {
1079
    MockXcdevice mockXcdevice;
1080 1081 1082
    MockArtifacts mockArtifacts;
    MockCache mockCache;
    MockFileSystem mockFileSystem;
1083
    Logger logger;
1084 1085
    FullMockProcessManager mockProcessManager;
    IOSDeploy iosDeploy;
1086 1087

    setUp(() {
1088
      mockXcdevice = MockXcdevice();
1089 1090
      mockArtifacts = MockArtifacts();
      mockCache = MockCache();
1091
      logger = BufferLogger.test();
1092 1093 1094 1095 1096
      mockFileSystem = MockFileSystem();
      mockProcessManager = FullMockProcessManager();
      iosDeploy = IOSDeploy(
        artifacts: mockArtifacts,
        cache: mockCache,
1097
        logger: logger,
1098 1099 1100
        platform: macPlatform,
        processManager: mockProcessManager,
      );
1101 1102
    });

1103
    final List<Platform> unsupportedPlatforms = <Platform>[linuxPlatform, windowsPlatform];
1104 1105 1106
    for (final Platform unsupportedPlatform in unsupportedPlatforms) {
      testWithoutContext('throws Unsupported Operation exception on ${unsupportedPlatform.operatingSystem}', () async {
        when(mockXcdevice.isInstalled).thenReturn(false);
1107
        expect(
1108
            () async { await IOSDevice.getAttachedDevices(unsupportedPlatform, mockXcdevice); },
Dan Field's avatar
Dan Field committed
1109
            throwsA(isA<UnsupportedError>()),
1110 1111 1112 1113
        );
      });
    }

1114
    testWithoutContext('returns attached devices', () async {
1115
      when(mockXcdevice.isInstalled).thenReturn(true);
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

      final IOSDevice device = IOSDevice(
        'd83d5bc53967baa0ee18626ba87b6254b2ab5418',
        name: 'Paired iPhone',
        sdkVersion: '13.3',
        cpuArchitecture: DarwinArch.arm64,
        artifacts: mockArtifacts,
        iosDeploy: iosDeploy,
        platform: macPlatform,
        fileSystem: mockFileSystem,
      );
1127 1128 1129 1130 1131 1132
      when(mockXcdevice.getAvailableTetheredIOSDevices())
          .thenAnswer((Invocation invocation) => Future<List<IOSDevice>>.value(<IOSDevice>[device]));

      final List<IOSDevice> devices = await IOSDevice.getAttachedDevices(macPlatform, mockXcdevice);
      expect(devices, hasLength(1));
      expect(identical(devices.first, device), isTrue);
1133
    });
1134
  });
1135

1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
  group('getDiagnostics', () {
    MockXcdevice mockXcdevice;

    setUp(() {
      mockXcdevice = MockXcdevice();
    });

    final List<Platform> unsupportedPlatforms = <Platform>[linuxPlatform, windowsPlatform];
    for (final Platform unsupportedPlatform in unsupportedPlatforms) {
      testWithoutContext('throws returns platform diagnostic exception on ${unsupportedPlatform.operatingSystem}', () async {
        when(mockXcdevice.isInstalled).thenReturn(false);
        expect((await IOSDevice.getDiagnostics(unsupportedPlatform, mockXcdevice)).first, 'Control of iOS devices or simulators only supported on macOS.');
      });
    }

    testUsingContext('returns diagnostics', () async {
      when(mockXcdevice.isInstalled).thenReturn(true);
      when(mockXcdevice.getDiagnostics())
          .thenAnswer((Invocation invocation) => Future<List<String>>.value(<String>['Generic pairing error']));

      final List<String> diagnostics = await IOSDevice.getDiagnostics(macPlatform, mockXcdevice);
      expect(diagnostics, hasLength(1));
      expect(diagnostics.first, 'Generic pairing error');
1159
    }, overrides: <Type, Generator>{
1160
      Platform: () => macPlatform,
1161
    });
1162 1163
  });

1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
  group('decodeSyslog', () {
    test('decodes a syslog-encoded line', () {
      final String decoded = decodeSyslog(r'I \M-b\M^]\M-$\M-o\M-8\M^O syslog \M-B\M-/\134_(\M-c\M^C\M^D)_/\M-B\M-/ \M-l\M^F\240!');
      expect(decoded, r'I ❤️ syslog ¯\_(ツ)_/¯ 솠!');
    });

    test('passes through un-decodeable lines as-is', () {
      final String decoded = decodeSyslog(r'I \M-b\M^O syslog!');
      expect(decoded, r'I \M-b\M^O syslog!');
    });
  });
1175

1176 1177
  group('logging', () {
    MockIMobileDevice mockIMobileDevice;
1178
    MockIosProject mockIosProject;
1179 1180 1181
    MockArtifacts mockArtifacts;
    MockCache mockCache;
    MockFileSystem mockFileSystem;
1182
    Logger logger;
1183 1184
    FullMockProcessManager mockProcessManager;
    IOSDeploy iosDeploy;
1185 1186

    setUp(() {
1187 1188
      mockIMobileDevice = MockIMobileDevice();
      mockIosProject = MockIosProject();
1189 1190
      mockArtifacts = MockArtifacts();
      mockCache = MockCache();
1191
      logger = BufferLogger.test();
1192 1193 1194 1195 1196
      mockFileSystem = MockFileSystem();
      mockProcessManager = FullMockProcessManager();
      iosDeploy = IOSDeploy(
        artifacts: mockArtifacts,
        cache: mockCache,
1197
        logger: logger,
1198 1199 1200
        platform: macPlatform,
        processManager: mockProcessManager,
      );
1201 1202
    });

1203
    testUsingContext('suppresses non-Flutter lines from output', () async {
1204
      when(mockIMobileDevice.startLogger('123456')).thenAnswer((Invocation invocation) {
1205 1206
        final Process mockProcess = MockProcess(
          stdout: Stream<List<int>>.fromIterable(<List<int>>['''
1207 1208 1209 1210 1211
Runner(Flutter)[297] <Notice>: A is for ari
Runner(libsystem_asl.dylib)[297] <Notice>: libMobileGestalt MobileGestaltSupport.m:153: pid 123 (Runner) does not have sandbox access for frZQaeyWLUvLjeuEK43hmg and IS NOT appropriately entitled
Runner(libsystem_asl.dylib)[297] <Notice>: libMobileGestalt MobileGestalt.c:550: no access to InverseDeviceID (see <rdar://problem/11744455>)
Runner(Flutter)[297] <Notice>: I is for ichigo
Runner(UIKit)[297] <Notice>: E is for enpitsu"
1212 1213
'''.codeUnits])
        );
1214
        return Future<Process>.value(mockProcess);
1215 1216
      });

1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
      final IOSDevice device = IOSDevice(
        '123456',
        name: 'iPhone 1',
        sdkVersion: '10.3',
        cpuArchitecture: DarwinArch.arm64,
        artifacts: mockArtifacts,
        iosDeploy: iosDeploy,
        platform: macPlatform,
        fileSystem: mockFileSystem,
      );
1227
      final DeviceLogReader logReader = device.getLogReader(
1228
        app: await BuildableIOSApp.fromProject(mockIosProject),
1229 1230 1231 1232 1233 1234
      );

      final List<String> lines = await logReader.logLines.toList();
      expect(lines, <String>['A is for ari', 'I is for ichigo']);
    }, overrides: <Type, Generator>{
      IMobileDevice: () => mockIMobileDevice,
1235
      Platform: () => macPlatform,
1236
    });
1237

1238
    testUsingContext('includes multi-line Flutter logs in the output', () async {
1239
      when(mockIMobileDevice.startLogger('123456')).thenAnswer((Invocation invocation) {
1240 1241
        final Process mockProcess = MockProcess(
          stdout: Stream<List<int>>.fromIterable(<List<int>>['''
1242
Runner(Flutter)[297] <Notice>: This is a multi-line message,
1243
  with another Flutter message following it.
1244
Runner(Flutter)[297] <Notice>: This is a multi-line message,
1245
  with a non-Flutter log message following it.
1246
Runner(libsystem_asl.dylib)[297] <Notice>: libMobileGestalt
1247 1248
'''.codeUnits]),
        );
1249
        return Future<Process>.value(mockProcess);
1250 1251
      });

1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
      final IOSDevice device = IOSDevice(
        '123456',
        name: 'iPhone 1',
        sdkVersion: '10.3',
        cpuArchitecture: DarwinArch.arm64,
        artifacts: mockArtifacts,
        iosDeploy: iosDeploy,
        platform: macPlatform,
        fileSystem: mockFileSystem,
      );
1262
      final DeviceLogReader logReader = device.getLogReader(
1263
        app: await BuildableIOSApp.fromProject(mockIosProject),
1264 1265 1266 1267 1268 1269 1270 1271 1272
      );

      final List<String> lines = await logReader.logLines.toList();
      expect(lines, <String>[
        'This is a multi-line message,',
        '  with another Flutter message following it.',
        'This is a multi-line message,',
        '  with a non-Flutter log message following it.',
      ]);
1273
      expect(device.category, Category.mobile);
1274 1275
    }, overrides: <Type, Generator>{
      IMobileDevice: () => mockIMobileDevice,
1276
      Platform: () => macPlatform,
1277
    });
1278
  });
1279

1280 1281 1282
  group('isSupportedForProject', () {
    Artifacts mockArtifacts;
    MockCache mockCache;
1283
    Logger logger;
1284 1285 1286 1287 1288 1289 1290 1291
    IOSDeploy iosDeploy;

    setUp(() {
      mockArtifacts = MockArtifacts();
      mockCache = MockCache();
      iosDeploy = IOSDeploy(
        artifacts: mockArtifacts,
        cache: mockCache,
1292
        logger: logger,
1293 1294 1295 1296
        platform: macPlatform,
        processManager: FakeProcessManager.any(),
      );
    });
1297

1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
    testUsingContext('is true on module project', () async {
      globals.fs.file('pubspec.yaml')
        ..createSync()
        ..writeAsStringSync(r'''
  name: example

  flutter:
    module: {}
  ''');
      globals.fs.file('.packages').createSync();
      final FlutterProject flutterProject = FlutterProject.current();

      final IOSDevice device = IOSDevice(
        'test',
        artifacts: mockArtifacts,
        fileSystem: globals.fs,
        iosDeploy: iosDeploy,
        platform: globals.platform,
        name: 'iPhone 1',
        sdkVersion: '13.3',
        cpuArchitecture: DarwinArch.arm64
      );
      expect(device.isSupportedForProject(flutterProject), true);
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem(),
      ProcessManager: () => FakeProcessManager.any(),
      Platform: () => macPlatform,
    });

    testUsingContext('is true with editable host app', () async {
      globals.fs.file('pubspec.yaml').createSync();
      globals.fs.file('.packages').createSync();
      globals.fs.directory('ios').createSync();
      final FlutterProject flutterProject = FlutterProject.current();
      final IOSDevice device = IOSDevice(
        'test',
        artifacts: mockArtifacts,
        fileSystem: globals.fs,
        iosDeploy: iosDeploy,
        platform: globals.platform,
        name: 'iPhone 1',
        sdkVersion: '13.3',
        cpuArchitecture: DarwinArch.arm64,
      );
      expect(device.isSupportedForProject(flutterProject), true);
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem(),
      ProcessManager: () => FakeProcessManager.any(),
      Platform: () => macPlatform,
    });

    testUsingContext('is false with no host app and no module', () async {
      globals.fs.file('pubspec.yaml').createSync();
      globals.fs.file('.packages').createSync();
      final FlutterProject flutterProject = FlutterProject.current();

      final IOSDevice device = IOSDevice(
        'test',
        artifacts: mockArtifacts,
        fileSystem: globals.fs,
        iosDeploy: iosDeploy,
        platform: globals.platform,
        name: 'iPhone 1',
        sdkVersion: '13.3',
        cpuArchitecture: DarwinArch.arm64,
      );
      expect(device.isSupportedForProject(flutterProject), false);
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem(),
      ProcessManager: () => FakeProcessManager.any(),
      Platform: () => macPlatform,
    });
1370
  });
1371
}
1372 1373

class AbsoluteBuildableIOSApp extends BuildableIOSApp {
1374 1375 1376 1377 1378 1379 1380
  AbsoluteBuildableIOSApp(IosProject project, String projectBundleId) :
    super(project, projectBundleId);

  static Future<AbsoluteBuildableIOSApp> fromProject(IosProject project) async {
    final String projectBundleId = await project.productBundleIdentifier;
    return AbsoluteBuildableIOSApp(project, projectBundleId);
  }
1381 1382 1383

  @override
  String get deviceBundlePath =>
1384
      globals.fs.path.join(project.parent.directory.path, 'build', 'ios', 'iphoneos', name);
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397

}

class FakeIosDoctorProvider implements DoctorValidatorsProvider {
  List<Workflow> _workflows;

  @override
  List<DoctorValidator> get validators => <DoctorValidator>[];

  @override
  List<Workflow> get workflows {
    if (_workflows == null) {
      _workflows = <Workflow>[];
1398
      if (iosWorkflow.appliesToHostPlatform) {
1399
        _workflows.add(iosWorkflow);
1400
      }
1401 1402 1403 1404
    }
    return _workflows;
  }
}
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425

class MockIOSApp extends Mock implements IOSApp {}
class MockApplicationPackage extends Mock implements ApplicationPackage {}
class MockArtifacts extends Mock implements Artifacts {}
class MockCache extends Mock implements Cache {}
class MockDevicePortForwarder extends Mock implements DevicePortForwarder {}
class MockDirectory extends Mock implements Directory {}
class MockFile extends Mock implements File {}
class MockFileSystem extends Mock implements FileSystem {}
class MockForwardedPort extends Mock implements ForwardedPort {}
class MockIMobileDevice extends Mock implements IMobileDevice {}
class MockIOSDeploy extends Mock implements IOSDeploy {}
class MockMDnsObservatoryDiscovery extends Mock implements MDnsObservatoryDiscovery {}
class MockMDnsObservatoryDiscoveryResult extends Mock implements MDnsObservatoryDiscoveryResult {}
class MockPlatform extends Mock implements Platform {}
class MockPortForwarder extends Mock implements DevicePortForwarder {}
// src/mocks.dart imports `MockProcessManager` which implements some methods, this is a full mock
class FullMockProcessManager extends Mock implements ProcessManager {}
class MockUsage extends Mock implements Usage {}
class MockXcdevice extends Mock implements XCDevice {}
class MockXcode extends Mock implements Xcode {}