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

5 6
// @dart = 2.8

7
import 'package:file/memory.dart';
8
import 'package:flutter_tools/src/base/file_system.dart';
9 10
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
11
import 'package:flutter_tools/src/base/platform.dart';
12
import 'package:flutter_tools/src/base/process.dart';
13
import 'package:flutter_tools/src/build_info.dart';
14
import 'package:flutter_tools/src/devfs.dart';
15
import 'package:flutter_tools/src/device.dart';
16
import 'package:flutter_tools/src/device_port_forwarder.dart';
17
import 'package:flutter_tools/src/globals.dart' as globals;
18
import 'package:flutter_tools/src/ios/application_package.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:test/fake.dart';
24

25 26
import '../../src/common.dart';
import '../../src/context.dart';
27
import '../../src/fakes.dart';
28

29 30 31 32 33 34 35
final Platform macosPlatform = FakePlatform(
  operatingSystem: 'macos',
  environment: <String, String>{
    'HOME': '/'
  },
);

36
void main() {
37
  FakePlatform osx;
38 39
  FileSystemUtils fsUtils;
  MemoryFileSystem fileSystem;
40 41

  setUp(() {
42 43 44 45
    osx = FakePlatform(
      environment: <String, String>{},
      operatingSystem: 'macos',
    );
46
    fileSystem = MemoryFileSystem.test();
47
    fsUtils = FileSystemUtils(fileSystem: fileSystem, platform: osx);
48 49
  });

50
  group('_IOSSimulatorDevicePortForwarder', () {
51
    FakeSimControl simControl;
52
    Xcode xcode;
53 54

    setUp(() {
55
      simControl = FakeSimControl();
56
      xcode = Xcode.test(processManager: FakeProcessManager.any());
57 58
    });

59
    testUsingContext('dispose() does not throw an exception', () async {
60 61
      final IOSSimulator simulator = IOSSimulator(
        '123',
62
        name: 'iPhone 11',
63
        simControl: simControl,
64
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-14-4',
65
      );
66 67 68 69 70 71
      final DevicePortForwarder portForwarder = simulator.portForwarder;
      await portForwarder.forward(123);
      await portForwarder.forward(124);
      expect(portForwarder.forwardedPorts.length, 2);
      try {
        await portForwarder.dispose();
72
      } on Exception catch (e) {
73 74 75 76 77
        fail('Encountered exception: $e');
      }
      expect(portForwarder.forwardedPorts.length, 0);
    }, overrides: <Type, Generator>{
      Platform: () => osx,
78 79
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
80
      Xcode: () => xcode,
81 82 83
    }, testOn: 'posix');
  });

84 85 86
  testUsingContext('simulators only support debug mode', () async {
    final IOSSimulator simulator = IOSSimulator(
      '123',
87
      name: 'iPhone 11',
88
      simControl: FakeSimControl(),
89
      simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-14-4',
90 91 92 93 94 95 96 97 98 99 100 101
    );

    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(),
  });

102
  group('logFilePath', () {
103
    FakeSimControl simControl;
104 105

    setUp(() {
106
      simControl = FakeSimControl();
107 108
    });

109 110
    testUsingContext('defaults to rooted from HOME', () {
      osx.environment['HOME'] = '/foo/bar';
111 112
      final IOSSimulator simulator = IOSSimulator(
        '123',
113
        name: 'iPhone 11',
114
        simControl: simControl,
115
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-14-4',
116 117
      );
      expect(simulator.logFilePath, '/foo/bar/Library/Logs/CoreSimulator/123/system.log');
118 119
    }, overrides: <Type, Generator>{
      Platform: () => osx,
120 121 122
      FileSystemUtils: () => fsUtils,
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
123 124 125 126 127
    }, 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';
128 129
      final IOSSimulator simulator = IOSSimulator(
        '456',
130
        name: 'iPhone 11',
131
        simControl: simControl,
132
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-14-4',
133 134
      );
      expect(simulator.logFilePath, '/baz/qux/456/system.log');
135 136
    }, overrides: <Type, Generator>{
      Platform: () => osx,
137 138 139
      FileSystemUtils: () => fsUtils,
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
140 141
    });
  });
142

143
  group('compareIosVersions', () {
144
    testWithoutContext('compares correctly', () {
145
      // This list must be sorted in ascending preference order
146
      final List<String> testList = <String>[
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
        '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));
        }
      }
    });
  });

165
  group('sdkMajorVersion', () {
166
    FakeSimControl simControl;
167 168

    setUp(() {
169
      simControl = FakeSimControl();
170 171
    });

172
    // This new version string appears in SimulatorApp-850 CoreSimulator-518.16 beta.
173 174 175 176 177
    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',
178
        simControl: simControl,
179
      );
180 181 182 183

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

184 185 186 187 188
    testWithoutContext('can be parsed from iOS 11.2', () async {
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 11.2',
189
        simControl: simControl,
190
      );
191 192 193

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

195 196 197 198 199
    testWithoutContext('Has a simulator category', () async {
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 11.2',
200
        simControl: simControl,
201
      );
202 203 204

      expect(device.category, Category.mobile);
    });
205 206
  });

207
  group('IOSSimulator.isSupported', () {
208
    FakeSimControl simControl;
209 210

    setUp(() {
211
      simControl = FakeSimControl();
212 213
    });

214
    testUsingContext('Apple TV is unsupported', () {
215 216 217
      final IOSSimulator simulator = IOSSimulator(
        'x',
        name: 'Apple TV',
218
        simControl: simControl,
219
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.tvOS-14-5',
220 221
      );
      expect(simulator.isSupported(), false);
222 223
    }, overrides: <Type, Generator>{
      Platform: () => osx,
224 225
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
226 227
    });

228
    testUsingContext('Apple Watch is unsupported', () {
229 230 231
      expect(IOSSimulator(
        'x',
        name: 'Apple Watch',
232
        simControl: simControl,
233
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.watchOS-8-0',
234
      ).isSupported(), false);
235 236
    }, overrides: <Type, Generator>{
      Platform: () => osx,
237 238
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
239 240
    });

241
    testUsingContext('iPad 2 is supported', () {
242 243 244
      expect(IOSSimulator(
        'x',
        name: 'iPad 2',
245
        simControl: simControl,
246
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
247
      ).isSupported(), true);
248 249
    }, overrides: <Type, Generator>{
      Platform: () => osx,
250 251
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
252 253
    });

254
    testUsingContext('iPad Retina is supported', () {
255 256 257
      expect(IOSSimulator(
        'x',
        name: 'iPad Retina',
258
        simControl: simControl,
259
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
260
      ).isSupported(), true);
261 262
    }, overrides: <Type, Generator>{
      Platform: () => osx,
263 264
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
265 266
    });

267
    testUsingContext('iPhone 5 is supported', () {
268 269 270
      expect(IOSSimulator(
        'x',
        name: 'iPhone 5',
271
        simControl: simControl,
272
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
273
      ).isSupported(), true);
274 275
    }, overrides: <Type, Generator>{
      Platform: () => osx,
276 277
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
278 279
    });

280
    testUsingContext('iPhone 5s is supported', () {
281 282 283
      expect(IOSSimulator(
        'x',
        name: 'iPhone 5s',
284
        simControl: simControl,
285
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
286
      ).isSupported(), true);
287 288
    }, overrides: <Type, Generator>{
      Platform: () => osx,
289 290
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
291 292
    });

293
    testUsingContext('iPhone SE is supported', () {
294 295 296
      expect(IOSSimulator(
        'x',
        name: 'iPhone SE',
297
        simControl: simControl,
298
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
299
      ).isSupported(), true);
300 301
    }, overrides: <Type, Generator>{
      Platform: () => osx,
302 303
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
304 305
    });

306
    testUsingContext('iPhone 7 Plus is supported', () {
307 308 309
      expect(IOSSimulator(
        'x',
        name: 'iPhone 7 Plus',
310
        simControl: simControl,
311
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
312
      ).isSupported(), true);
313 314
    }, overrides: <Type, Generator>{
      Platform: () => osx,
315 316
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
317
    });
318 319

    testUsingContext('iPhone X is supported', () {
320 321 322
      expect(IOSSimulator(
        'x',
        name: 'iPhone X',
323
        simControl: simControl,
324
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
325
      ).isSupported(), true);
326 327
    }, overrides: <Type, Generator>{
      Platform: () => osx,
328 329
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
330
    });
331
  });
332 333

  group('Simulator screenshot', () {
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
    testWithoutContext('supports screenshots', () async {
      final Xcode xcode = Xcode.test(processManager: FakeProcessManager.any());
      final Logger logger = BufferLogger.test();
      final FakeProcessManager fakeProcessManager = FakeProcessManager.list(<FakeCommand>[
        const FakeCommand(
          command: <String>[
            'xcrun',
            'simctl',
            'io',
            'x',
            'screenshot',
            'screenshot.png',
          ],
        ),
      ]);
349

350
      // Test a real one. Screenshot doesn't require instance states.
351
      final SimControl simControl = SimControl(
352 353 354
        processManager: fakeProcessManager,
        logger: logger,
        xcode: xcode,
355
      );
356
      // Doesn't matter what the device is.
357
      final IOSSimulator deviceUnderTest = IOSSimulator(
358 359 360
        'x',
        name: 'iPhone SE',
        simControl: simControl,
361
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
362
      );
363

364 365 366 367
      final File screenshot = MemoryFileSystem.test().file('screenshot.png');
      await deviceUnderTest.takeScreenshot(screenshot);
      expect(fakeProcessManager.hasRemainingExpectations, isFalse);
    });
368
  });
369

370
  group('device log tool', () {
371
    FakeProcessManager fakeProcessManager;
372
    FakeSimControl simControl;
373 374

    setUp(() {
375
      fakeProcessManager = FakeProcessManager.empty();
376
      simControl = FakeSimControl();
377 378
    });

379
    testUsingContext('syslog uses tail', () async {
380 381 382 383
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 9.3',
384
        simControl: simControl,
385
      );
386 387 388 389 390 391 392
      fakeProcessManager.addCommand(const FakeCommand(command: <String>[
        'tail',
        '-n',
        '0',
        '-F',
        '/Library/Logs/CoreSimulator/x/system.log',
      ]));
393
      await launchDeviceSystemLogTool(device);
394
      expect(fakeProcessManager.hasRemainingExpectations, isFalse);
395 396
    },
    overrides: <Type, Generator>{
397
      ProcessManager: () => fakeProcessManager,
398
      FileSystem: () => fileSystem,
399 400 401 402
      Platform: () => macosPlatform,
      FileSystemUtils: () => FileSystemUtils(
        fileSystem: fileSystem,
        platform: macosPlatform,
403
      ),
404 405
    });

406
    testUsingContext('unified logging with app name', () async {
407 408 409 410
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 11.0',
411
        simControl: simControl,
412
      );
413
      const String expectedPredicate = 'eventType = logEvent AND '
414 415 416 417 418 419
          'processImagePath ENDSWITH "My Super Awesome App" 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>[
420
        'xcrun',
421 422
        'simctl',
        'spawn',
423
        'x',
424 425 426 427 428
        'log',
        'stream',
        '--style',
        'json',
        '--predicate',
429 430 431 432 433
        expectedPredicate,
      ]));

      await launchDeviceUnifiedLogging(device, 'My Super Awesome App');
      expect(fakeProcessManager.hasRemainingExpectations, isFalse);
434
    },
435
      overrides: <Type, Generator>{
436
      ProcessManager: () => fakeProcessManager,
437
      FileSystem: () => fileSystem,
438 439
    });

440
    testUsingContext('unified logging without app name', () async {
441 442 443 444
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 11.0',
445
        simControl: simControl,
446
      );
447
      const String expectedPredicate = 'eventType = logEvent AND '
448 449 450 451 452
          '(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>[
453
        'xcrun',
454 455 456 457 458 459 460 461
        'simctl',
        'spawn',
        'x',
        'log',
        'stream',
        '--style',
        'json',
        '--predicate',
462 463 464 465 466
        expectedPredicate,
      ]));

      await launchDeviceUnifiedLogging(device, null);
      expect(fakeProcessManager.hasRemainingExpectations, isFalse);
467
    },
468
      overrides: <Type, Generator>{
469
        ProcessManager: () => fakeProcessManager,
470 471
        FileSystem: () => fileSystem,
      });
472
  });
473 474

  group('log reader', () {
475
    FakeProcessManager fakeProcessManager;
476
    FakeIosProject mockIosProject;
477
    FakeSimControl simControl;
478
    Xcode xcode;
479 480

    setUp(() {
481
      fakeProcessManager = FakeProcessManager.empty();
482
      mockIosProject = FakeIosProject();
483
      simControl = FakeSimControl();
484
      xcode = Xcode.test(processManager: FakeProcessManager.any());
485 486
    });

487 488 489 490 491 492
    group('syslog', () {
      setUp(() {
        final File syslog = fileSystem.file('system.log')..createSync();
        osx.environment['IOS_SIMULATOR_LOG_FILE_PATH'] = syslog.path;
      });

493 494 495 496
      testUsingContext('simulator can parse Xcode 8/iOS 10-style logs', () async {
        fakeProcessManager
          ..addCommand(const FakeCommand(
            command:  <String>['tail', '-n', '0', '-F', 'system.log'],
497 498 499
            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'''
500 501 502 503 504 505 506
          ))
          ..addCommand(const FakeCommand(
            command:  <String>['tail', '-n', '0', '-F', '/private/var/log/system.log']
          ));

        final IOSSimulator device = IOSSimulator(
          '123456',
507
          name: 'iPhone 11',
508
          simulatorCategory: 'iOS 10.0',
509
          simControl: simControl,
510 511
        );
        final DeviceLogReader logReader = device.getLogReader(
512
          app: await BuildableIOSApp.fromProject(mockIosProject, null),
513 514 515 516 517 518 519 520 521 522 523
        );

        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,
524
        Xcode: () => xcode,
525 526
      });

527
      testUsingContext('simulator can output `)`', () async {
528 529 530 531
        fakeProcessManager
          ..addCommand(const FakeCommand(
            command:  <String>['tail', '-n', '0', '-F', 'system.log'],
            stdout: '''
532 533 534
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)'''
535 536 537 538
          ))
          ..addCommand(const FakeCommand(
            command:  <String>['tail', '-n', '0', '-F', '/private/var/log/system.log']
          ));
539

540 541
        final IOSSimulator device = IOSSimulator(
          '123456',
542
          name: 'iPhone 11',
543
          simulatorCategory: 'iOS 10.3',
544
          simControl: simControl,
545 546
        );
        final DeviceLogReader logReader = device.getLogReader(
547
          app: await BuildableIOSApp.fromProject(mockIosProject, null),
548 549 550 551 552 553 554 555
        );

        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)',
        ]);
556
        expect(fakeProcessManager.hasRemainingExpectations, isFalse);
557
      }, overrides: <Type, Generator>{
558
        ProcessManager: () => fakeProcessManager,
559 560
        FileSystem: () => fileSystem,
        Platform: () => osx,
561
        Xcode: () => xcode,
562 563
      });

564 565 566 567 568
      testUsingContext('multiline messages', () async {
        fakeProcessManager
          ..addCommand(const FakeCommand(
            command:  <String>['tail', '-n', '0', '-F', 'system.log'],
            stdout: '''
569 570
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
571 572
  continues...
  continues...
573
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
574 575 576 577
	[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
578
2017-09-13 15:36:57.228948-0700  localhost My Super Awesome App[37195]: (Flutter) Multi line message again
579 580
  and it goes...
  and goes...
581
2017-09-13 15:36:57.228948-0700  localhost My Super Awesome App[37195]: (Flutter) Single line message, not the part of the above
582
'''
583 584 585 586
          ))
          ..addCommand(const FakeCommand(
            command:  <String>['tail', '-n', '0', '-F', '/private/var/log/system.log']
          ));
587

588 589
        final IOSSimulator device = IOSSimulator(
          '123456',
590
          name: 'iPhone 11',
591
          simulatorCategory: 'iOS 10.3',
592
          simControl: simControl,
593 594
        );
        final DeviceLogReader logReader = device.getLogReader(
595
          app: await BuildableIOSApp.fromProject(mockIosProject, null),
596 597 598 599 600 601 602 603 604 605 606 607 608
        );

        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'
        ]);
609
        expect(fakeProcessManager.hasRemainingExpectations, isFalse);
610
      }, overrides: <Type, Generator>{
611
        ProcessManager: () => fakeProcessManager,
612 613
        FileSystem: () => fileSystem,
        Platform: () => osx,
614
        Xcode: () => xcode,
615 616
      });
    });
617

618
    group('unified logging', () {
619 620 621 622 623 624
      BufferLogger logger;

      setUp(() {
        logger = BufferLogger.test();
      });

625
      testUsingContext('log reader handles escaped multiline messages', () async {
626
        const String logPredicate = 'eventType = logEvent AND processImagePath ENDSWITH "My Super Awesome App" '
627 628 629 630 631 632
          '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>[
633
              'xcrun',
634 635 636 637 638 639 640 641 642 643
              'simctl',
              'spawn',
              '123456',
              'log',
              'stream',
              '--style',
              'json',
              '--predicate',
              logPredicate,
            ],
644
            stdout: r'''
645 646 647 648 649 650
},{
  "traceID" : 37579774151491588,
  "eventMessage" : "Single line message",
  "eventType" : "logEvent"
},{
  "traceID" : 37579774151491588,
651
  "eventMessage" : "Multi line message\n  continues...\n  continues..."
652 653 654 655 656 657
},{
  "traceID" : 37579774151491588,
  "eventMessage" : "Single line message, not the part of the above",
  "eventType" : "logEvent"
},{
'''
658
          ));
659 660 661

        final IOSSimulator device = IOSSimulator(
          '123456',
662
          name: 'iPhone 11',
663
          simulatorCategory: 'iOS 11.0',
664
          simControl: simControl,
665 666
        );
        final DeviceLogReader logReader = device.getLogReader(
667
          app: await BuildableIOSApp.fromProject(mockIosProject, null),
668 669 670 671 672 673 674
        );

        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'
        ]);
675
        expect(fakeProcessManager.hasRemainingExpectations, isFalse);
676
      }, overrides: <Type, Generator>{
677
        ProcessManager: () => fakeProcessManager,
678 679
        FileSystem: () => fileSystem,
      });
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704

      testUsingContext('log reader handles bad output', () async {
        const String logPredicate = 'eventType = logEvent AND processImagePath ENDSWITH "My Super Awesome App" '
            '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>[
              'xcrun',
              'simctl',
              'spawn',
              '123456',
              'log',
              'stream',
              '--style',
              'json',
              '--predicate',
              logPredicate,
            ],
            stdout: '"eventMessage" : "message with incorrect escaping""',
        ));

        final IOSSimulator device = IOSSimulator(
          '123456',
705
          name: 'iPhone 11',
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
          simulatorCategory: 'iOS 11.0',
          simControl: simControl,
        );
        final DeviceLogReader logReader = device.getLogReader(
          app: await BuildableIOSApp.fromProject(mockIosProject, null),
        );

        final List<String> lines = await logReader.logLines.toList();
        expect(lines, isEmpty);
        expect(logger.errorText, contains('Logger returned non-JSON response'));
        expect(fakeProcessManager.hasRemainingExpectations, isFalse);
      }, overrides: <Type, Generator>{
        ProcessManager: () => fakeProcessManager,
        FileSystem: () => fileSystem,
        Logger: () => logger,
      });
722
    });
723
  });
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747

  group('SimControl', () {
    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",
748
        "availability" : "(available)",
749 750 751 752 753 754 755 756
        "name" : "Apple TV",
        "udid" : "TEST-TV-UDID"
      }
    ]
  }
}
    ''';

757 758
    FakeProcessManager fakeProcessManager;
    Xcode xcode;
759
    SimControl simControl;
760 761
    const String deviceId = 'smart-phone';
    const String appId = 'flutterApp';
762 763

    setUp(() {
764
      fakeProcessManager = FakeProcessManager.empty();
765
      xcode = Xcode.test(processManager: FakeProcessManager.any());
766
      simControl = SimControl(
767 768 769
        logger: BufferLogger.test(),
        processManager: fakeProcessManager,
        xcode: xcode,
770
      );
771 772
    });

773
    testWithoutContext('getDevices succeeds', () async {
774 775 776 777 778 779 780 781 782 783 784
      fakeProcessManager.addCommand(const FakeCommand(
        command: <String>[
          'xcrun',
          'simctl',
          'list',
          '--json',
          'devices',
        ],
        stdout: validSimControlOutput,
      ));

785
      final List<SimDevice> devices = await simControl.getDevices();
786 787 788 789

      final SimDevice watch = devices[0];
      expect(watch.category, 'watchOS 4.3');
      expect(watch.state, 'Shutdown');
790
      expect(watch.availability, '(available)');
791 792 793 794 795 796 797
      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');
798
      expect(phone.availability, '(available)');
799 800 801 802
      expect(phone.name, 'iPhone 5s');
      expect(phone.udid, 'TEST-PHONE-UDID');
      expect(phone.isBooted, isTrue);

803
      final SimDevice tv = devices[2];
804 805
      expect(tv.category, 'tvOS 11.4');
      expect(tv.state, 'Shutdown');
806
      expect(tv.availability, '(available)');
807 808 809
      expect(tv.name, 'Apple TV');
      expect(tv.udid, 'TEST-TV-UDID');
      expect(tv.isBooted, isFalse);
810
      expect(fakeProcessManager.hasRemainingExpectations, isFalse);
811
    });
812

813
    testWithoutContext('getDevices handles bad simctl output', () async {
814 815 816 817 818 819 820 821 822 823 824
      fakeProcessManager.addCommand(const FakeCommand(
        command: <String>[
          'xcrun',
          'simctl',
          'list',
          '--json',
          'devices',
        ],
        stdout: 'Install Started',
      ));

825 826 827
      final List<SimDevice> devices = await simControl.getDevices();

      expect(devices, isEmpty);
828
      expect(fakeProcessManager.hasRemainingExpectations, isFalse);
829
    });
830

831 832 833 834 835 836 837
    testWithoutContext('sdkMajorVersion defaults to 11 when sdkNameAndVersion is junk', () async {
      final IOSSimulator iosSimulatorA = IOSSimulator(
        'x',
        name: 'Testo',
        simulatorCategory: 'NaN',
        simControl: simControl,
      );
838 839 840

      expect(await iosSimulatorA.sdkMajorVersion, 11);
    });
841 842

    testWithoutContext('.install() handles exceptions', () async {
843 844
      fakeProcessManager.addCommand(const FakeCommand(
        command: <String>[
845 846 847 848 849 850
          'xcrun',
          'simctl',
          'install',
          deviceId,
          appId,
        ],
851
        exception: ProcessException('xcrun', <String>[]),
852 853
      ));

854
      expect(
855
        () async => simControl.install(deviceId, appId),
856 857 858 859 860
        throwsToolExit(message: r'Unable to install'),
      );
    });

    testWithoutContext('.uninstall() handles exceptions', () async {
861 862
      fakeProcessManager.addCommand(const FakeCommand(
        command: <String>[
863 864 865 866 867 868
          'xcrun',
          'simctl',
          'uninstall',
          deviceId,
          appId,
        ],
869
        exception: ProcessException('xcrun', <String>[]),
870 871
      ));

872
      expect(
873
        () async => simControl.uninstall(deviceId, appId),
874 875 876 877 878
        throwsToolExit(message: r'Unable to uninstall'),
      );
    });

    testWithoutContext('.launch() handles exceptions', () async {
879 880
      fakeProcessManager.addCommand(const FakeCommand(
        command: <String>[
881 882 883 884 885 886
          'xcrun',
          'simctl',
          'launch',
          deviceId,
          appId,
        ],
887
        exception: ProcessException('xcrun', <String>[]),
888 889
      ));

890
      expect(
891
        () async => simControl.launch(deviceId, appId),
892 893 894
        throwsToolExit(message: r'Unable to launch'),
      );
    });
895
  });
896

897
  group('startApp', () {
898
    FakePlistParser testPlistParser;
899
    FakeSimControl simControl;
900
    Xcode xcode;
901
    BufferLogger logger;
902 903

    setUp(() {
904
      simControl = FakeSimControl();
905
      xcode = Xcode.test(processManager: FakeProcessManager.any());
906
      testPlistParser = FakePlistParser();
907
      logger = BufferLogger.test();
908 909 910
    });

    testUsingContext("startApp uses compiled app's Info.plist to find CFBundleIdentifier", () async {
911 912 913 914 915 916
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 11.2',
        simControl: simControl,
      );
917
      testPlistParser.setProperty('CFBundleIdentifier', 'correct');
918

919
      final Directory mockDir = globals.fs.currentDirectory;
920 921 922 923 924 925
      final IOSApp package = PrebuiltIOSApp(
        projectBundleId: 'incorrect',
        bundleName: 'name',
        uncompressedBundle: mockDir,
        applicationPackage: mockDir,
      );
926

927
      const BuildInfo mockInfo = BuildInfo(BuildMode.debug, 'flavor', treeShakeIcons: false);
928 929
      final DebuggingOptions mockOptions = DebuggingOptions.disabled(mockInfo);
      await device.startApp(package, prebuiltApplication: true, debuggingOptions: mockOptions);
930

931
      expect(simControl.requests.single.appIdentifier, 'correct');
932
    }, overrides: <Type, Generator>{
933
      PlistParser: () => testPlistParser,
934 935
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
936
      Xcode: () => xcode,
937
    });
938

939
    testUsingContext('startApp fails when cannot find CFBundleIdentifier', () async {
940 941 942 943 944 945 946 947
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 11.2',
        simControl: simControl,
      );

      final Directory mockDir = globals.fs.currentDirectory;
948 949 950 951 952 953
      final IOSApp package = PrebuiltIOSApp(
        projectBundleId: 'incorrect',
        bundleName: 'name',
        uncompressedBundle: mockDir,
        applicationPackage: mockDir,
      );
954

955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
      const BuildInfo mockInfo = BuildInfo(BuildMode.debug, 'flavor', treeShakeIcons: false);
      final DebuggingOptions mockOptions = DebuggingOptions.disabled(mockInfo);
      final LaunchResult result = await device.startApp(package, prebuiltApplication: true, debuggingOptions: mockOptions);

      expect(result.started, isFalse);
      expect(simControl.requests, isEmpty);
      expect(logger.errorText, contains('Invalid prebuilt iOS app. Info.plist does not contain bundle identifier'));
    }, overrides: <Type, Generator>{
      PlistParser: () => testPlistParser,
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
      Logger: () => logger,
      Xcode: () => xcode,
    });

    testUsingContext('startApp respects the enable software rendering flag', () async {
      final IOSSimulator device = IOSSimulator(
        'x',
        name: 'iPhone SE',
        simulatorCategory: 'iOS 11.2',
        simControl: simControl,
      );
      testPlistParser.setProperty('CFBundleIdentifier', 'correct');

      final Directory mockDir = globals.fs.currentDirectory;
980 981 982 983 984 985
      final IOSApp package = PrebuiltIOSApp(
        projectBundleId: 'correct',
        bundleName: 'name',
        uncompressedBundle: mockDir,
        applicationPackage: mockDir,
      );
986

987 988 989 990
      const BuildInfo mockInfo = BuildInfo(BuildMode.debug, 'flavor', treeShakeIcons: false);
      final DebuggingOptions mockOptions = DebuggingOptions.enabled(mockInfo, enableSoftwareRendering: true);
      await device.startApp(package, prebuiltApplication: true, debuggingOptions: mockOptions);

991
      expect(simControl.requests.single.launchArgs, contains('--enable-software-rendering'));
992
    }, overrides: <Type, Generator>{
993
      PlistParser: () => testPlistParser,
994 995
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.any(),
996
      Xcode: () => xcode,
997
    });
998 999
  });

1000
  group('IOSDevice.isSupportedForProject', () {
1001
    FakeSimControl simControl;
1002
    Xcode xcode;
1003 1004

    setUp(() {
1005
      simControl = FakeSimControl();
1006
      xcode = Xcode.test(processManager: FakeProcessManager.any());
1007 1008 1009 1010 1011 1012
    });

    testUsingContext('is true on module project', () async {
      globals.fs.file('pubspec.yaml')
        ..createSync()
        ..writeAsStringSync(r'''
1013 1014 1015 1016 1017
name: example

flutter:
  module: {}
''');
1018
      globals.fs.file('.packages').createSync();
1019
      final FlutterProject flutterProject = FlutterProject.fromDirectoryTest(globals.fs.currentDirectory);
1020

1021 1022
      final IOSSimulator simulator = IOSSimulator(
        'test',
1023
        name: 'iPhone 11',
1024
        simControl: simControl,
1025
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
1026 1027 1028
      );
      expect(simulator.isSupportedForProject(flutterProject), true);
    }, overrides: <Type, Generator>{
1029
      FileSystem: () => MemoryFileSystem.test(),
1030
      ProcessManager: () => FakeProcessManager.any(),
1031
      Xcode: () => xcode,
1032
    });
1033 1034


1035 1036 1037 1038
    testUsingContext('is true with editable host app', () async {
      globals.fs.file('pubspec.yaml').createSync();
      globals.fs.file('.packages').createSync();
      globals.fs.directory('ios').createSync();
1039
      final FlutterProject flutterProject = FlutterProject.fromDirectoryTest(globals.fs.currentDirectory);
1040

1041 1042
      final IOSSimulator simulator = IOSSimulator(
        'test',
1043
        name: 'iPhone 11',
1044
        simControl: simControl,
1045
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
1046 1047 1048
      );
      expect(simulator.isSupportedForProject(flutterProject), true);
    }, overrides: <Type, Generator>{
1049
      FileSystem: () => MemoryFileSystem.test(),
1050
      ProcessManager: () => FakeProcessManager.any(),
1051
      Xcode: () => xcode,
1052 1053 1054 1055 1056
    });

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

1059 1060
      final IOSSimulator simulator = IOSSimulator(
        'test',
1061
        name: 'iPhone 11',
1062
        simControl: simControl,
1063
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
1064 1065 1066
      );
      expect(simulator.isSupportedForProject(flutterProject), false);
    }, overrides: <Type, Generator>{
1067
      FileSystem: () => MemoryFileSystem.test(),
1068
      ProcessManager: () => FakeProcessManager.any(),
1069
      Xcode: () => xcode,
1070
    });
1071 1072 1073 1074

    testUsingContext('createDevFSWriter returns a LocalDevFSWriter', () {
      final IOSSimulator simulator = IOSSimulator(
        'test',
1075
        name: 'iPhone 11',
1076
        simControl: simControl,
1077
        simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3',
1078 1079 1080 1081
      );

      expect(simulator.createDevFSWriter(null, ''), isA<LocalDevFSWriter>());
    });
1082
  });
1083
}
1084 1085 1086 1087 1088 1089 1090 1091

class FakeIosProject extends Fake implements IosProject {
  @override
  Future<String> productBundleIdentifier(BuildInfo buildInfo) async => 'com.example.test';

  @override
  Future<String> hostAppBundleName(BuildInfo buildInfo) async => 'My Super Awesome App.app';
}
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

class FakeSimControl extends Fake implements SimControl {
  final List<LaunchRequest> requests = <LaunchRequest>[];

  @override
  Future<RunResult> launch(String deviceId, String appIdentifier, [ List<String> launchArgs ]) async {
    requests.add(LaunchRequest(deviceId, appIdentifier, launchArgs));
    return RunResult(ProcessResult(0, 0, '', ''), <String>['test']);
  }

  @override
  Future<RunResult> install(String deviceId, String appPath) async {
    return RunResult(ProcessResult(0, 0, '', ''), <String>['test']);
  }
}

class LaunchRequest {
  const LaunchRequest(this.deviceId, this.appIdentifier, this.launchArgs);

  final String deviceId;
  final String appIdentifier;
  final List<String> launchArgs;
}