simulators_test.dart 33 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:io' show ProcessResult, Process;
6

7
import 'package:file/file.dart';
8
import 'package:file/memory.dart';
9 10
import 'package:flutter_tools/src/application_package.dart';
import 'package:flutter_tools/src/base/file_system.dart';
11 12
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
13 14
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
15
import 'package:flutter_tools/src/build_system/build_system.dart';
16
import 'package:flutter_tools/src/device.dart';
17
import 'package:flutter_tools/src/globals.dart' as globals;
18
import 'package:flutter_tools/src/ios/mac.dart';
19
import 'package:flutter_tools/src/ios/plist_parser.dart';
20
import 'package:flutter_tools/src/ios/simulators.dart';
21
import 'package:flutter_tools/src/macos/xcode.dart';
22
import 'package:flutter_tools/src/project.dart';
23
import 'package:mockito/mockito.dart';
24 25
import 'package:process/process.dart';

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

class MockFile extends Mock implements File {}
31
class MockIMobileDevice extends Mock implements IMobileDevice {}
32
class MockLogger extends Mock implements Logger {}
33
class MockProcess extends Mock implements Process {}
34 35
class MockProcessManager extends Mock implements ProcessManager {}
class MockXcode extends Mock implements Xcode {}
36
class MockSimControl extends Mock implements SimControl {}
37
class MockPlistUtils extends Mock implements PlistParser {}
38

39 40 41 42 43 44 45
final Platform macosPlatform = FakePlatform(
  operatingSystem: 'macos',
  environment: <String, String>{
    'HOME': '/'
  },
);

46
void main() {
47
  FakePlatform osx;
48 49
  FileSystemUtils fsUtils;
  MemoryFileSystem fileSystem;
50 51

  setUp(() {
52 53 54 55
    osx = FakePlatform(
      environment: <String, String>{},
      operatingSystem: 'macos',
    );
56
    fileSystem = MemoryFileSystem.test();
57
    fsUtils = FileSystemUtils(fileSystem: fileSystem, platform: osx);
58 59
  });

60
  group('_IOSSimulatorDevicePortForwarder', () {
61 62 63 64 65 66 67 68
    MockSimControl mockSimControl;
    MockXcode mockXcode;

    setUp(() {
      mockSimControl = MockSimControl();
      mockXcode = MockXcode();
    });

69
    testUsingContext('dispose() does not throw an exception', () async {
70 71 72 73 74
      final IOSSimulator simulator = IOSSimulator(
        '123',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
75 76 77 78 79 80
      final DevicePortForwarder portForwarder = simulator.portForwarder;
      await portForwarder.forward(123);
      await portForwarder.forward(124);
      expect(portForwarder.forwardedPorts.length, 2);
      try {
        await portForwarder.dispose();
81
      } on Exception catch (e) {
82 83 84 85 86
        fail('Encountered exception: $e');
      }
      expect(portForwarder.forwardedPorts.length, 0);
    }, overrides: <Type, Generator>{
      Platform: () => osx,
87 88
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
89 90 91
    }, testOn: 'posix');
  });

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  testUsingContext('simulators only support debug mode', () async {
    final IOSSimulator simulator = IOSSimulator(
      '123',
      simControl: MockSimControl(),
      xcode: MockXcode(),
    );

    expect(simulator.supportsRuntimeMode(BuildMode.debug), true);
    expect(simulator.supportsRuntimeMode(BuildMode.profile), false);
    expect(simulator.supportsRuntimeMode(BuildMode.release), false);
    expect(simulator.supportsRuntimeMode(BuildMode.jitRelease), false);
  }, overrides: <Type, Generator>{
    Platform: () => osx,
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.any(),
  });

109
  group('logFilePath', () {
110 111 112 113 114 115 116 117
    MockSimControl mockSimControl;
    MockXcode mockXcode;

    setUp(() {
      mockSimControl = MockSimControl();
      mockXcode = MockXcode();
    });

118 119
    testUsingContext('defaults to rooted from HOME', () {
      osx.environment['HOME'] = '/foo/bar';
120 121 122 123 124 125
      final IOSSimulator simulator = IOSSimulator(
        '123',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
      expect(simulator.logFilePath, '/foo/bar/Library/Logs/CoreSimulator/123/system.log');
126 127
    }, overrides: <Type, Generator>{
      Platform: () => osx,
128 129 130
      FileSystemUtils: () => fsUtils,
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
131 132 133 134 135
    }, testOn: 'posix');

    testUsingContext('respects IOS_SIMULATOR_LOG_FILE_PATH', () {
      osx.environment['HOME'] = '/foo/bar';
      osx.environment['IOS_SIMULATOR_LOG_FILE_PATH'] = '/baz/qux/%{id}/system.log';
136 137 138 139 140 141
      final IOSSimulator simulator = IOSSimulator(
        '456',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
      expect(simulator.logFilePath, '/baz/qux/456/system.log');
142 143
    }, overrides: <Type, Generator>{
      Platform: () => osx,
144 145 146
      FileSystemUtils: () => fsUtils,
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
147 148
    });
  });
149

150
  group('compareIosVersions', () {
151
    testWithoutContext('compares correctly', () {
152
      // This list must be sorted in ascending preference order
153
      final List<String> testList = <String>[
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
        '8', '8.0', '8.1', '8.2',
        '9', '9.0', '9.1', '9.2',
        '10', '10.0', '10.1',
      ];

      for (int i = 0; i < testList.length; i++) {
        expect(compareIosVersions(testList[i], testList[i]), 0);
      }

      for (int i = 0; i < testList.length - 1; i++) {
        for (int j = i + 1; j < testList.length; j++) {
          expect(compareIosVersions(testList[i], testList[j]), lessThan(0));
          expect(compareIosVersions(testList[j], testList[i]), greaterThan(0));
        }
      }
    });
  });

  group('compareIphoneVersions', () {
173
    testWithoutContext('compares correctly', () {
174
      // This list must be sorted in ascending preference order
175
      final List<String> testList = <String>[
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
        'com.apple.CoreSimulator.SimDeviceType.iPhone-4s',
        'com.apple.CoreSimulator.SimDeviceType.iPhone-5',
        'com.apple.CoreSimulator.SimDeviceType.iPhone-5s',
        'com.apple.CoreSimulator.SimDeviceType.iPhone-6strange',
        'com.apple.CoreSimulator.SimDeviceType.iPhone-6-Plus',
        'com.apple.CoreSimulator.SimDeviceType.iPhone-6',
        'com.apple.CoreSimulator.SimDeviceType.iPhone-6s-Plus',
        'com.apple.CoreSimulator.SimDeviceType.iPhone-6s',
      ];

      for (int i = 0; i < testList.length; i++) {
        expect(compareIphoneVersions(testList[i], testList[i]), 0);
      }

      for (int i = 0; i < testList.length - 1; i++) {
        for (int j = i + 1; j < testList.length; j++) {
          expect(compareIphoneVersions(testList[i], testList[j]), lessThan(0));
          expect(compareIphoneVersions(testList[j], testList[i]), greaterThan(0));
        }
      }
    });
  });
198

199
  group('sdkMajorVersion', () {
200 201 202 203 204 205 206 207
    MockSimControl mockSimControl;
    MockXcode mockXcode;

    setUp(() {
      mockSimControl = MockSimControl();
      mockXcode = MockXcode();
    });

208
    // This new version string appears in SimulatorApp-850 CoreSimulator-518.16 beta.
209 210 211 212 213 214 215 216
    testWithoutContext('can be parsed from iOS-11-3', () async {
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
217 218 219 220

      expect(await device.sdkMajorVersion, 11);
    });

221 222 223 224 225 226 227 228
    testWithoutContext('can be parsed from iOS 11.2', () async {
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 11.2',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
229 230 231

      expect(await device.sdkMajorVersion, 11);
    });
232

233 234 235 236 237 238 239 240
    testWithoutContext('Has a simulator category', () async {
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 11.2',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
241 242 243

      expect(device.category, Category.mobile);
    });
244 245
  });

246
  group('IOSSimulator.isSupported', () {
247 248 249 250 251 252 253 254
    MockSimControl mockSimControl;
    MockXcode mockXcode;

    setUp(() {
      mockSimControl = MockSimControl();
      mockXcode = MockXcode();
    });

255
    testUsingContext('Apple TV is unsupported', () {
256 257 258 259 260 261 262
      final IOSSimulator simulator = IOSSimulator(
        'x',
        name: 'Apple TV',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
      expect(simulator.isSupported(), false);
263 264
    }, overrides: <Type, Generator>{
      Platform: () => osx,
265 266
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
267 268
    });

269
    testUsingContext('Apple Watch is unsupported', () {
270 271 272 273 274 275
      expect(IOSSimulator(
        'x',
        name: 'Apple Watch',
        simControl: mockSimControl,
        xcode: mockXcode,
      ).isSupported(), false);
276 277
    }, overrides: <Type, Generator>{
      Platform: () => osx,
278 279
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
280 281
    });

282
    testUsingContext('iPad 2 is supported', () {
283 284 285 286 287 288
      expect(IOSSimulator(
        'x',
        name: 'iPad 2',
        simControl: mockSimControl,
        xcode: mockXcode,
      ).isSupported(), true);
289 290
    }, overrides: <Type, Generator>{
      Platform: () => osx,
291 292
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
293 294
    });

295
    testUsingContext('iPad Retina is supported', () {
296 297 298 299 300 301
      expect(IOSSimulator(
        'x',
        name: 'iPad Retina',
        simControl: mockSimControl,
        xcode: mockXcode,
      ).isSupported(), true);
302 303
    }, overrides: <Type, Generator>{
      Platform: () => osx,
304 305
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
306 307
    });

308
    testUsingContext('iPhone 5 is supported', () {
309 310 311 312 313 314
      expect(IOSSimulator(
        'x',
        name: 'iPhone 5',
        simControl: mockSimControl,
        xcode: mockXcode,
      ).isSupported(), true);
315 316
    }, overrides: <Type, Generator>{
      Platform: () => osx,
317 318
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
319 320
    });

321
    testUsingContext('iPhone 5s is supported', () {
322 323 324 325 326 327
      expect(IOSSimulator(
        'x',
        name: 'iPhone 5s',
        simControl: mockSimControl,
        xcode: mockXcode,
      ).isSupported(), true);
328 329
    }, overrides: <Type, Generator>{
      Platform: () => osx,
330 331
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
332 333
    });

334
    testUsingContext('iPhone SE is supported', () {
335 336 337 338 339 340
      expect(IOSSimulator(
        'x',
        name: 'iPhone SE',
        simControl: mockSimControl,
        xcode: mockXcode,
      ).isSupported(), true);
341 342
    }, overrides: <Type, Generator>{
      Platform: () => osx,
343 344
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
345 346
    });

347
    testUsingContext('iPhone 7 Plus is supported', () {
348 349 350 351 352 353
      expect(IOSSimulator(
        'x',
        name: 'iPhone 7 Plus',
        simControl: mockSimControl,
        xcode: mockXcode,
      ).isSupported(), true);
354 355
    }, overrides: <Type, Generator>{
      Platform: () => osx,
356 357
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
358
    });
359 360

    testUsingContext('iPhone X is supported', () {
361 362 363 364 365 366
      expect(IOSSimulator(
        'x',
        name: 'iPhone X',
        simControl: mockSimControl,
        xcode: mockXcode,
      ).isSupported(), true);
367 368
    }, overrides: <Type, Generator>{
      Platform: () => osx,
369 370
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
371
    });
372
  });
373 374 375

  group('Simulator screenshot', () {
    MockXcode mockXcode;
376
    MockLogger mockLogger;
377 378
    MockProcessManager mockProcessManager;
    IOSSimulator deviceUnderTest;
379 380
    // only used for fs.path.join()
    final FileSystem fs = globals.fs;
381 382

    setUp(() {
383
      mockXcode = MockXcode();
384
      mockLogger = MockLogger();
385
      mockProcessManager = MockProcessManager();
386 387
      // Let everything else return exit code 0 so process.dart doesn't crash.
      when(
388
        mockProcessManager.run(any, environment: null, workingDirectory: null)
389
      ).thenAnswer((Invocation invocation) =>
390
        Future<ProcessResult>.value(ProcessResult(2, 0, '', ''))
391
      );
392 393
      // Test a real one. Screenshot doesn't require instance states.
      final SimControl simControl = SimControl(processManager: mockProcessManager, logger: mockLogger);
394
      // Doesn't matter what the device is.
395 396 397 398 399 400
      deviceUnderTest = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simControl: simControl,
        xcode: mockXcode,
      );
401 402
    });

403
    testWithoutContext(
404
      "old Xcode doesn't support screenshot",
405
      () {
406 407
        when(mockXcode.majorVersion).thenReturn(7);
        when(mockXcode.minorVersion).thenReturn(1);
408 409 410 411
        expect(deviceUnderTest.supportsScreenshot, false);
      },
    );

412
    testWithoutContext(
413
      'Xcode 8.2+ supports screenshots',
414
      () async {
415 416
        when(mockXcode.majorVersion).thenReturn(8);
        when(mockXcode.minorVersion).thenReturn(2);
417
        expect(deviceUnderTest.supportsScreenshot, true);
418
        final MockFile mockFile = MockFile();
419
        when(mockFile.path).thenReturn(fs.path.join('some', 'path', 'to', 'screenshot.png'));
420 421
        await deviceUnderTest.takeScreenshot(mockFile);
        verify(mockProcessManager.run(
422
          <String>[
423 424 425 426 427
            '/usr/bin/xcrun',
            'simctl',
            'io',
            'x',
            'screenshot',
428
            fs.path.join('some', 'path', 'to', 'screenshot.png'),
429 430
          ],
          environment: null,
431
          workingDirectory: null,
432 433 434 435
        ));
      },
    );
  });
436

437
  group('device log tool', () {
438
    MockProcessManager mockProcessManager;
439 440
    MockXcode mockXcode;
    MockSimControl mockSimControl;
441 442

    setUp(() {
443
      mockProcessManager = MockProcessManager();
444
      when(mockProcessManager.start(any, environment: null, workingDirectory: null))
445
        .thenAnswer((Invocation invocation) => Future<Process>.value(MockProcess()));
446 447
      mockSimControl = MockSimControl();
      mockXcode = MockXcode();
448 449
    });

450
    testUsingContext('syslog uses tail', () async {
451 452 453 454 455 456 457
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 9.3',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
458
      await launchDeviceSystemLogTool(device);
459
      expect(
460
        verify(mockProcessManager.start(captureAny, environment: null, workingDirectory: null)).captured.single,
461 462 463 464 465
        contains('tail'),
      );
    },
    overrides: <Type, Generator>{
      ProcessManager: () => mockProcessManager,
466
      FileSystem: () => fileSystem,
467 468 469 470 471
      Platform: () => macosPlatform,
      FileSystemUtils: () => FileSystemUtils(
        fileSystem: fileSystem,
        platform: macosPlatform,
      )
472 473
    });

474
    testUsingContext('unified logging with app name', () async {
475 476 477 478 479 480 481
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 11.0',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
482
      await launchDeviceUnifiedLogging(device, 'My Super Awesome App');
483 484

      const String expectedPredicate = 'eventType = logEvent AND '
485
        'processImagePath ENDSWITH "My Super Awesome App" AND '
486 487 488 489 490 491 492 493 494 495
        '(senderImagePath ENDSWITH "/Flutter" OR senderImagePath ENDSWITH "/libswiftCore.dylib" OR processImageUUID == senderImageUUID) AND '
        'NOT(eventMessage CONTAINS ": could not find icon for representation -> com.apple.") AND '
        'NOT(eventMessage BEGINSWITH "assertion failed: ") AND '
        'NOT(eventMessage CONTAINS " libxpc.dylib ")';

      final List<String> command = verify(mockProcessManager.start(captureAny, environment: null, workingDirectory: null)).captured.single as List<String>;
      expect(command, <String>[
        '/usr/bin/xcrun',
        'simctl',
        'spawn',
496
        'x',
497 498 499 500 501 502 503
        'log',
        'stream',
        '--style',
        'json',
        '--predicate',
        expectedPredicate
      ]);
504
    },
505
      overrides: <Type, Generator>{
506
      ProcessManager: () => mockProcessManager,
507
      FileSystem: () => fileSystem,
508 509
    });

510
    testUsingContext('unified logging without app name', () async {
511 512 513 514 515 516 517
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 11.0',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
      await launchDeviceUnifiedLogging(device, null);

      const String expectedPredicate = 'eventType = logEvent AND '
        '(senderImagePath ENDSWITH "/Flutter" OR senderImagePath ENDSWITH "/libswiftCore.dylib" OR processImageUUID == senderImageUUID) AND '
        'NOT(eventMessage CONTAINS ": could not find icon for representation -> com.apple.") AND '
        'NOT(eventMessage BEGINSWITH "assertion failed: ") AND '
        'NOT(eventMessage CONTAINS " libxpc.dylib ")';

      final List<String> command = verify(mockProcessManager.start(captureAny, environment: null, workingDirectory: null)).captured.single as List<String>;
      expect(command, <String>[
        '/usr/bin/xcrun',
        'simctl',
        'spawn',
        'x',
        'log',
        'stream',
        '--style',
        'json',
        '--predicate',
        expectedPredicate
      ]);
539
    },
540 541 542 543
      overrides: <Type, Generator>{
        ProcessManager: () => mockProcessManager,
        FileSystem: () => fileSystem,
      });
544
  });
545 546

  group('log reader', () {
547
    FakeProcessManager fakeProcessManager;
548
    MockIosProject mockIosProject;
549 550
    MockSimControl mockSimControl;
    MockXcode mockXcode;
551 552

    setUp(() {
553
      fakeProcessManager = FakeProcessManager.list(<FakeCommand>[]);
554
      mockIosProject = MockIosProject();
555 556
      mockSimControl = MockSimControl();
      mockXcode = MockXcode();
557 558
    });

559 560 561 562 563 564
    group('syslog', () {
      setUp(() {
        final File syslog = fileSystem.file('system.log')..createSync();
        osx.environment['IOS_SIMULATOR_LOG_FILE_PATH'] = syslog.path;
      });

565 566 567 568
      testUsingContext('simulator can parse Xcode 8/iOS 10-style logs', () async {
        fakeProcessManager
          ..addCommand(const FakeCommand(
            command:  <String>['tail', '-n', '0', '-F', 'system.log'],
569 570 571
            stdout: '''
Dec 20 17:04:32 md32-11-vm1 My Super Awesome App[88374]: flutter: Observatory listening on http://127.0.0.1:64213/1Uoeu523990=/
Dec 20 17:04:32 md32-11-vm1 Another App[88374]: Ignore this text'''
572 573 574 575 576 577 578 579 580 581 582 583
          ))
          ..addCommand(const FakeCommand(
            command:  <String>['tail', '-n', '0', '-F', '/private/var/log/system.log']
          ));

        final IOSSimulator device = IOSSimulator(
          '123456',
          simulatorCategory: 'iOS 10.0',
          simControl: mockSimControl,
          xcode: mockXcode,
        );
        final DeviceLogReader logReader = device.getLogReader(
584
          app: await BuildableIOSApp.fromProject(mockIosProject, null),
585 586 587 588 589 590 591 592 593 594 595 596 597
        );

        final List<String> lines = await logReader.logLines.toList();
        expect(lines, <String>[
          'flutter: Observatory listening on http://127.0.0.1:64213/1Uoeu523990=/',
        ]);
        expect(fakeProcessManager.hasRemainingExpectations, isFalse);
      }, overrides: <Type, Generator>{
        ProcessManager: () => fakeProcessManager,
        FileSystem: () => fileSystem,
        Platform: () => osx,
      });

598
      testUsingContext('simulator can output `)`', () async {
599 600 601 602
        fakeProcessManager
          ..addCommand(const FakeCommand(
            command:  <String>['tail', '-n', '0', '-F', 'system.log'],
            stdout: '''
603 604 605
2017-09-13 15:26:57.228948-0700  localhost My Super Awesome App[37195]: (Flutter) Observatory listening on http://127.0.0.1:57701/
2017-09-13 15:26:57.228948-0700  localhost My Super Awesome App[37195]: (Flutter) ))))))))))
2017-09-13 15:26:57.228948-0700  localhost My Super Awesome App[37195]: (Flutter) #0      Object.noSuchMethod (dart:core-patch/dart:core/object_patch.dart:46)'''
606 607 608 609
          ))
          ..addCommand(const FakeCommand(
            command:  <String>['tail', '-n', '0', '-F', '/private/var/log/system.log']
          ));
610

611 612 613 614 615 616 617
        final IOSSimulator device = IOSSimulator(
          '123456',
          simulatorCategory: 'iOS 10.3',
          simControl: mockSimControl,
          xcode: mockXcode,
        );
        final DeviceLogReader logReader = device.getLogReader(
618
          app: await BuildableIOSApp.fromProject(mockIosProject, null),
619 620 621 622 623 624 625 626
        );

        final List<String> lines = await logReader.logLines.toList();
        expect(lines, <String>[
          'Observatory listening on http://127.0.0.1:57701/',
          '))))))))))',
          '#0      Object.noSuchMethod (dart:core-patch/dart:core/object_patch.dart:46)',
        ]);
627
        expect(fakeProcessManager.hasRemainingExpectations, isFalse);
628
      }, overrides: <Type, Generator>{
629
        ProcessManager: () => fakeProcessManager,
630 631 632 633
        FileSystem: () => fileSystem,
        Platform: () => osx,
      });

634 635 636 637 638
      testUsingContext('multiline messages', () async {
        fakeProcessManager
          ..addCommand(const FakeCommand(
            command:  <String>['tail', '-n', '0', '-F', 'system.log'],
            stdout: '''
639 640
2017-09-13 15:26:57.228948-0700  localhost My Super Awesome App[37195]: (Flutter) Single line message
2017-09-13 15:26:57.228948-0700  localhost My Super Awesome App[37195]: (Flutter) Multi line message
641 642
  continues...
  continues...
643
2020-03-11 15:58:28.207175-0700  localhost My Super Awesome App[72166]: (libnetwork.dylib) [com.apple.network:] [28 www.googleapis.com:443 stream, pid: 72166, tls] cancelled
644 645 646 647
	[28.1 64A98447-EABF-4983-A387-7DB9D0C1785F 10.0.1.200.57912<->172.217.6.74:443]
	Connected Path: satisfied (Path is satisfied), interface: en18
	Duration: 0.271s, DNS @0.000s took 0.001s, TCP @0.002s took 0.019s, TLS took 0.046s
	bytes in/out: 4468/1933, packets in/out: 11/10, rtt: 0.016s, retransmitted packets: 0, out-of-order packets: 0
648
2017-09-13 15:36:57.228948-0700  localhost My Super Awesome App[37195]: (Flutter) Multi line message again
649 650
  and it goes...
  and goes...
651
2017-09-13 15:36:57.228948-0700  localhost My Super Awesome App[37195]: (Flutter) Single line message, not the part of the above
652
'''
653 654 655 656
          ))
          ..addCommand(const FakeCommand(
            command:  <String>['tail', '-n', '0', '-F', '/private/var/log/system.log']
          ));
657

658 659 660 661 662 663 664
        final IOSSimulator device = IOSSimulator(
          '123456',
          simulatorCategory: 'iOS 10.3',
          simControl: mockSimControl,
          xcode: mockXcode,
        );
        final DeviceLogReader logReader = device.getLogReader(
665
          app: await BuildableIOSApp.fromProject(mockIosProject, null),
666 667 668 669 670 671 672 673 674 675 676 677 678
        );

        final List<String> lines = await logReader.logLines.toList();
        expect(lines, <String>[
          'Single line message',
          'Multi line message',
          '  continues...',
          '  continues...',
          'Multi line message again',
          '  and it goes...',
          '  and goes...',
          'Single line message, not the part of the above'
        ]);
679
        expect(fakeProcessManager.hasRemainingExpectations, isFalse);
680
      }, overrides: <Type, Generator>{
681
        ProcessManager: () => fakeProcessManager,
682 683 684 685
        FileSystem: () => fileSystem,
        Platform: () => osx,
      });
    });
686

687 688
    group('unified logging', () {
      testUsingContext('log reader handles escaped multiline messages', () async {
689
        const String logPredicate = 'eventType = logEvent AND processImagePath ENDSWITH "My Super Awesome App" '
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
          'AND (senderImagePath ENDSWITH "/Flutter" OR senderImagePath ENDSWITH "/libswiftCore.dylib" '
          'OR processImageUUID == senderImageUUID) AND NOT(eventMessage CONTAINS ": could not find icon '
          'for representation -> com.apple.") AND NOT(eventMessage BEGINSWITH "assertion failed: ") '
          'AND NOT(eventMessage CONTAINS " libxpc.dylib ")';
        fakeProcessManager.addCommand(const FakeCommand(
            command:  <String>[
              '/usr/bin/xcrun',
              'simctl',
              'spawn',
              '123456',
              'log',
              'stream',
              '--style',
              'json',
              '--predicate',
              logPredicate,
            ],
            stdout: '''
708 709 710 711 712 713 714 715 716 717 718 719 720
},{
  "traceID" : 37579774151491588,
  "eventMessage" : "Single line message",
  "eventType" : "logEvent"
},{
  "traceID" : 37579774151491588,
  "eventMessage" : "Multi line message\\n  continues...\\n  continues..."
},{
  "traceID" : 37579774151491588,
  "eventMessage" : "Single line message, not the part of the above",
  "eventType" : "logEvent"
},{
'''
721
          ));
722 723 724 725 726 727 728 729

        final IOSSimulator device = IOSSimulator(
          '123456',
          simulatorCategory: 'iOS 11.0',
          simControl: mockSimControl,
          xcode: mockXcode,
        );
        final DeviceLogReader logReader = device.getLogReader(
730
          app: await BuildableIOSApp.fromProject(mockIosProject, null),
731 732 733 734 735 736 737
        );

        final List<String> lines = await logReader.logLines.toList();
        expect(lines, <String>[
          'Single line message', 'Multi line message\n  continues...\n  continues...',
          'Single line message, not the part of the above'
        ]);
738
        expect(fakeProcessManager.hasRemainingExpectations, isFalse);
739
      }, overrides: <Type, Generator>{
740
        ProcessManager: () => fakeProcessManager,
741 742
        FileSystem: () => fileSystem,
      });
743
    });
744
  });
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778

  group('SimControl', () {
    const int mockPid = 123;
    const String validSimControlOutput = '''
{
  "devices" : {
    "watchOS 4.3" : [
      {
        "state" : "Shutdown",
        "availability" : "(available)",
        "name" : "Apple Watch - 38mm",
        "udid" : "TEST-WATCH-UDID"
      }
    ],
    "iOS 11.4" : [
      {
        "state" : "Booted",
        "availability" : "(available)",
        "name" : "iPhone 5s",
        "udid" : "TEST-PHONE-UDID"
      }
    ],
    "tvOS 11.4" : [
      {
        "state" : "Shutdown",
        "availability" : "(available)",
        "name" : "Apple TV",
        "udid" : "TEST-TV-UDID"
      }
    ]
  }
}
    ''';

779
    MockLogger mockLogger;
780
    MockProcessManager mockProcessManager;
781
    MockXcode mockXcode;
782
    SimControl simControl;
783 784
    const String deviceId = 'smart-phone';
    const String appId = 'flutterApp';
785 786

    setUp(() {
787
      mockLogger = MockLogger();
788
      mockProcessManager = MockProcessManager();
789 790 791
      when(mockProcessManager.run(any)).thenAnswer((Invocation _) async {
        return ProcessResult(mockPid, 0, validSimControlOutput, '');
      });
792

793 794 795 796 797
      simControl = SimControl(
        logger: mockLogger,
        processManager: mockProcessManager,
      );
      mockXcode = MockXcode();
798 799
    });

800
    testWithoutContext('getDevices succeeds', () async {
801
      final List<SimDevice> devices = await simControl.getDevices();
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826

      final SimDevice watch = devices[0];
      expect(watch.category, 'watchOS 4.3');
      expect(watch.state, 'Shutdown');
      expect(watch.availability, '(available)');
      expect(watch.name, 'Apple Watch - 38mm');
      expect(watch.udid, 'TEST-WATCH-UDID');
      expect(watch.isBooted, isFalse);

      final SimDevice phone = devices[1];
      expect(phone.category, 'iOS 11.4');
      expect(phone.state, 'Booted');
      expect(phone.availability, '(available)');
      expect(phone.name, 'iPhone 5s');
      expect(phone.udid, 'TEST-PHONE-UDID');
      expect(phone.isBooted, isTrue);

      final SimDevice tv = devices[2];
      expect(tv.category, 'tvOS 11.4');
      expect(tv.state, 'Shutdown');
      expect(tv.availability, '(available)');
      expect(tv.name, 'Apple TV');
      expect(tv.udid, 'TEST-TV-UDID');
      expect(tv.isBooted, isFalse);
    });
827

828
    testWithoutContext('getDevices handles bad simctl output', () async {
829 830 831 832 833 834
      when(mockProcessManager.run(any))
          .thenAnswer((Invocation _) async => ProcessResult(mockPid, 0, 'Install Started', ''));
      final List<SimDevice> devices = await simControl.getDevices();

      expect(devices, isEmpty);
    });
835

836 837 838 839 840 841 842 843
    testWithoutContext('sdkMajorVersion defaults to 11 when sdkNameAndVersion is junk', () async {
      final IOSSimulator iosSimulatorA = IOSSimulator(
        'x',
        name: 'Testo',
        simulatorCategory: 'NaN',
        simControl: simControl,
        xcode: mockXcode,
      );
844 845 846

      expect(await iosSimulatorA.sdkMajorVersion, 11);
    });
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882

    testWithoutContext('.install() handles exceptions', () async {
      when(mockProcessManager.run(
        <String>['/usr/bin/xcrun', 'simctl', 'install', deviceId, appId],
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenThrow(const ProcessException('xcrun', <String>[]));
      expect(
        () async => await simControl.install(deviceId, appId),
        throwsToolExit(message: r'Unable to install'),
      );
    });

    testWithoutContext('.uninstall() handles exceptions', () async {
      when(mockProcessManager.run(
        <String>['/usr/bin/xcrun', 'simctl', 'uninstall', deviceId, appId],
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenThrow(const ProcessException('xcrun', <String>[]));
      expect(
        () async => await simControl.uninstall(deviceId, appId),
        throwsToolExit(message: r'Unable to uninstall'),
      );
    });

    testWithoutContext('.launch() handles exceptions', () async {
      when(mockProcessManager.run(
        <String>['/usr/bin/xcrun', 'simctl', 'launch', deviceId, appId],
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenThrow(const ProcessException('xcrun', <String>[]));
      expect(
        () async => await simControl.launch(deviceId, appId),
        throwsToolExit(message: r'Unable to launch'),
      );
    });
883
  });
884

885 886
  group('startApp', () {
    SimControl simControl;
887
    MockXcode mockXcode;
888 889 890

    setUp(() {
      simControl = MockSimControl();
891
      mockXcode = MockXcode();
892 893 894
    });

    testUsingContext("startApp uses compiled app's Info.plist to find CFBundleIdentifier", () async {
895 896 897 898 899 900 901
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 11.2',
        simControl: simControl,
        xcode: mockXcode,
      );
902
      when(globals.plistParser.getValueFromFile(any, any)).thenReturn('correct');
903

904
      final Directory mockDir = globals.fs.currentDirectory;
905
      final IOSApp package = PrebuiltIOSApp(projectBundleId: 'incorrect', bundleName: 'name', bundleDir: mockDir);
906

907
      const BuildInfo mockInfo = BuildInfo(BuildMode.debug, 'flavor', treeShakeIcons: false);
908 909
      final DebuggingOptions mockOptions = DebuggingOptions.disabled(mockInfo);
      await device.startApp(package, prebuiltApplication: true, debuggingOptions: mockOptions);
910

911 912 913
      verify(simControl.launch(any, 'correct', any));
    }, overrides: <Type, Generator>{
      PlistParser: () => MockPlistUtils(),
914 915
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
916
    });
917 918
  });

919 920 921 922 923 924 925 926 927 928 929 930 931
  group('IOSDevice.isSupportedForProject', () {
    MockSimControl mockSimControl;
    MockXcode mockXcode;

    setUp(() {
      mockSimControl = MockSimControl();
      mockXcode = MockXcode();
    });

    testUsingContext('is true on module project', () async {
      globals.fs.file('pubspec.yaml')
        ..createSync()
        ..writeAsStringSync(r'''
932 933 934 935 936
name: example

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

940 941 942 943 944 945 946 947 948 949
      final IOSSimulator simulator = IOSSimulator(
        'test',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
      expect(simulator.isSupportedForProject(flutterProject), true);
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem(),
      ProcessManager: () => FakeProcessManager.any(),
    });
950 951


952 953 954 955 956
    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();
957

958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
      final IOSSimulator simulator = IOSSimulator(
        'test',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
      expect(simulator.isSupportedForProject(flutterProject), true);
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem(),
      ProcessManager: () => FakeProcessManager.any(),
    });

    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();
973

974 975 976 977 978 979 980 981 982 983
      final IOSSimulator simulator = IOSSimulator(
        'test',
        simControl: mockSimControl,
        xcode: mockXcode,
      );
      expect(simulator.isSupportedForProject(flutterProject), false);
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem(),
      ProcessManager: () => FakeProcessManager.any(),
    });
984
  });
985
}
986 987

class MockBuildSystem extends Mock implements BuildSystem {}