simulators_test.dart 18 KB
Newer Older
1 2 3 4
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:async';
6
import 'dart:io' show ProcessResult, Process;
7

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

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

class MockFile extends Mock implements File {}
28
class MockIMobileDevice extends Mock implements IMobileDevice {}
29
class MockProcess extends Mock implements Process {}
30 31
class MockProcessManager extends Mock implements ProcessManager {}
class MockXcode extends Mock implements Xcode {}
32
class MockSimControl extends Mock implements SimControl {}
33
class MockPlistUtils extends Mock implements PlistParser {}
34

35
void main() {
36 37 38
  FakePlatform osx;

  setUp(() {
39
    osx = FakePlatform.fromPlatform(const LocalPlatform());
40 41 42 43 44 45
    osx.operatingSystem = 'macos';
  });

  group('logFilePath', () {
    testUsingContext('defaults to rooted from HOME', () {
      osx.environment['HOME'] = '/foo/bar';
46
      expect(IOSSimulator('123').logFilePath, '/foo/bar/Library/Logs/CoreSimulator/123/system.log');
47 48 49 50 51 52 53
    }, overrides: <Type, Generator>{
      Platform: () => osx,
    }, 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';
54
      expect(IOSSimulator('456').logFilePath, '/baz/qux/456/system.log');
55 56 57 58
    }, overrides: <Type, Generator>{
      Platform: () => osx,
    });
  });
59

60 61 62
  group('compareIosVersions', () {
    test('compares correctly', () {
      // This list must be sorted in ascending preference order
63
      final List<String> testList = <String>[
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        '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', () {
    test('compares correctly', () {
      // This list must be sorted in ascending preference order
85
      final List<String> testList = <String>[
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        '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));
        }
      }
    });
  });
108

109 110 111
  group('sdkMajorVersion', () {
    // This new version string appears in SimulatorApp-850 CoreSimulator-518.16 beta.
    test('can be parsed from iOS-11-3', () async {
112
      final IOSSimulator device = IOSSimulator('x', name: 'iPhone SE', simulatorCategory: 'com.apple.CoreSimulator.SimRuntime.iOS-11-3');
113 114 115 116 117

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

    test('can be parsed from iOS 11.2', () async {
118
      final IOSSimulator device = IOSSimulator('x', name: 'iPhone SE', simulatorCategory: 'iOS 11.2');
119 120 121

      expect(await device.sdkMajorVersion, 11);
    });
122 123 124 125 126 127

    test('Has a simulator category', () async {
      final IOSSimulator device = IOSSimulator('x', name: 'iPhone SE', simulatorCategory: 'iOS 11.2');

      expect(device.category, Category.mobile);
    });
128 129
  });

130
  group('IOSSimulator.isSupported', () {
131
    testUsingContext('Apple TV is unsupported', () {
132
      expect(IOSSimulator('x', name: 'Apple TV').isSupported(), false);
133 134
    }, overrides: <Type, Generator>{
      Platform: () => osx,
135 136
    });

137
    testUsingContext('Apple Watch is unsupported', () {
138
      expect(IOSSimulator('x', name: 'Apple Watch').isSupported(), false);
139 140
    }, overrides: <Type, Generator>{
      Platform: () => osx,
141 142
    });

143
    testUsingContext('iPad 2 is supported', () {
144
      expect(IOSSimulator('x', name: 'iPad 2').isSupported(), true);
145 146
    }, overrides: <Type, Generator>{
      Platform: () => osx,
147 148
    });

149
    testUsingContext('iPad Retina is supported', () {
150
      expect(IOSSimulator('x', name: 'iPad Retina').isSupported(), true);
151 152
    }, overrides: <Type, Generator>{
      Platform: () => osx,
153 154
    });

155
    testUsingContext('iPhone 5 is supported', () {
156
      expect(IOSSimulator('x', name: 'iPhone 5').isSupported(), true);
157 158
    }, overrides: <Type, Generator>{
      Platform: () => osx,
159 160
    });

161
    testUsingContext('iPhone 5s is supported', () {
162
      expect(IOSSimulator('x', name: 'iPhone 5s').isSupported(), true);
163 164
    }, overrides: <Type, Generator>{
      Platform: () => osx,
165 166
    });

167
    testUsingContext('iPhone SE is supported', () {
168
      expect(IOSSimulator('x', name: 'iPhone SE').isSupported(), true);
169 170
    }, overrides: <Type, Generator>{
      Platform: () => osx,
171 172
    });

173
    testUsingContext('iPhone 7 Plus is supported', () {
174
      expect(IOSSimulator('x', name: 'iPhone 7 Plus').isSupported(), true);
175 176
    }, overrides: <Type, Generator>{
      Platform: () => osx,
177
    });
178 179

    testUsingContext('iPhone X is supported', () {
180
      expect(IOSSimulator('x', name: 'iPhone X').isSupported(), true);
181 182 183
    }, overrides: <Type, Generator>{
      Platform: () => osx,
    });
184
  });
185 186 187 188 189 190 191

  group('Simulator screenshot', () {
    MockXcode mockXcode;
    MockProcessManager mockProcessManager;
    IOSSimulator deviceUnderTest;

    setUp(() {
192 193
      mockXcode = MockXcode();
      mockProcessManager = MockProcessManager();
194 195
      // Let everything else return exit code 0 so process.dart doesn't crash.
      when(
196
        mockProcessManager.run(any, environment: null, workingDirectory: null)
197
      ).thenAnswer((Invocation invocation) =>
198
        Future<ProcessResult>.value(ProcessResult(2, 0, '', ''))
199 200
      );
      // Doesn't matter what the device is.
201
      deviceUnderTest = IOSSimulator('x', name: 'iPhone SE');
202 203 204 205 206
    });

    testUsingContext(
      'old Xcode doesn\'t support screenshot',
      () {
207 208
        when(mockXcode.majorVersion).thenReturn(7);
        when(mockXcode.minorVersion).thenReturn(1);
209 210
        expect(deviceUnderTest.supportsScreenshot, false);
      },
211
      overrides: <Type, Generator>{Xcode: () => mockXcode},
212 213 214 215
    );

    testUsingContext(
      'Xcode 8.2+ supports screenshots',
216
      () async {
217 218
        when(mockXcode.majorVersion).thenReturn(8);
        when(mockXcode.minorVersion).thenReturn(2);
219
        expect(deviceUnderTest.supportsScreenshot, true);
220
        final MockFile mockFile = MockFile();
221
        when(mockFile.path).thenReturn(fs.path.join('some', 'path', 'to', 'screenshot.png'));
222 223
        await deviceUnderTest.takeScreenshot(mockFile);
        verify(mockProcessManager.run(
224 225 226 227
          <String>[
              '/usr/bin/xcrun',
              'simctl',
              'io',
228
              'x',
229
              'screenshot',
230
              fs.path.join('some', 'path', 'to', 'screenshot.png'),
231 232
          ],
          environment: null,
233
          workingDirectory: null,
234 235 236 237 238
        ));
      },
      overrides: <Type, Generator>{
        ProcessManager: () => mockProcessManager,
        // Test a real one. Screenshot doesn't require instance states.
239
        SimControl: () => SimControl(),
240
        Xcode: () => mockXcode,
241
      },
242 243
    );
  });
244 245 246 247 248

  group('launchDeviceLogTool', () {
    MockProcessManager mockProcessManager;

    setUp(() {
249
      mockProcessManager = MockProcessManager();
250
      when(mockProcessManager.start(any, environment: null, workingDirectory: null))
251
        .thenAnswer((Invocation invocation) => Future<Process>.value(MockProcess()));
252 253 254
    });

    testUsingContext('uses tail on iOS versions prior to iOS 11', () async {
255
      final IOSSimulator device = IOSSimulator('x', name: 'iPhone SE', simulatorCategory: 'iOS 9.3');
256 257
      await launchDeviceLogTool(device);
      expect(
258
        verify(mockProcessManager.start(captureAny, environment: null, workingDirectory: null)).captured.single,
259 260 261 262 263 264 265 266
        contains('tail'),
      );
    },
    overrides: <Type, Generator>{
      ProcessManager: () => mockProcessManager,
    });

    testUsingContext('uses /usr/bin/log on iOS 11 and above', () async {
267
      final IOSSimulator device = IOSSimulator('x', name: 'iPhone SE', simulatorCategory: 'iOS 11.0');
268 269
      await launchDeviceLogTool(device);
      expect(
270
        verify(mockProcessManager.start(captureAny, environment: null, workingDirectory: null)).captured.single,
271 272 273 274 275 276 277 278 279 280 281 282
        contains('/usr/bin/log'),
      );
    },
    overrides: <Type, Generator>{
      ProcessManager: () => mockProcessManager,
    });
  });

  group('launchSystemLogTool', () {
    MockProcessManager mockProcessManager;

    setUp(() {
283
      mockProcessManager = MockProcessManager();
284
      when(mockProcessManager.start(any, environment: null, workingDirectory: null))
285
        .thenAnswer((Invocation invocation) => Future<Process>.value(MockProcess()));
286 287 288
    });

    testUsingContext('uses tail on iOS versions prior to iOS 11', () async {
289
      final IOSSimulator device = IOSSimulator('x', name: 'iPhone SE', simulatorCategory: 'iOS 9.3');
290 291
      await launchSystemLogTool(device);
      expect(
292
        verify(mockProcessManager.start(captureAny, environment: null, workingDirectory: null)).captured.single,
293 294 295 296 297 298 299 300
        contains('tail'),
      );
    },
    overrides: <Type, Generator>{
      ProcessManager: () => mockProcessManager,
    });

    testUsingContext('uses /usr/bin/log on iOS 11 and above', () async {
301
      final IOSSimulator device = IOSSimulator('x', name: 'iPhone SE', simulatorCategory: 'iOS 11.0');
302 303 304 305 306 307 308
      await launchSystemLogTool(device);
      verifyNever(mockProcessManager.start(any, environment: null, workingDirectory: null));
    },
    overrides: <Type, Generator>{
      ProcessManager: () => mockProcessManager,
    });
  });
309 310 311

  group('log reader', () {
    MockProcessManager mockProcessManager;
312
    MockIosProject mockIosProject;
313 314

    setUp(() {
315 316
      mockProcessManager = MockProcessManager();
      mockIosProject = MockIosProject();
317 318 319 320
    });

    testUsingContext('simulator can output `)`', () async {
      when(mockProcessManager.start(any, environment: null, workingDirectory: null))
321 322 323 324 325
        .thenAnswer((Invocation invocation) {
          final Process mockProcess = MockProcess();
          when(mockProcess.stdout)
            .thenAnswer((Invocation invocation) {
              return Stream<List<int>>.fromIterable(<List<int>>['''
326 327 328
2017-09-13 15:26:57.228948-0700  localhost Runner[37195]: (Flutter) Observatory listening on http://127.0.0.1:57701/
2017-09-13 15:26:57.228948-0700  localhost Runner[37195]: (Flutter) ))))))))))
2017-09-13 15:26:57.228948-0700  localhost Runner[37195]: (Flutter) #0      Object.noSuchMethod (dart:core-patch/dart:core/object_patch.dart:46)'''
329 330 331 332 333 334 335 336 337
                .codeUnits]);
            });
          when(mockProcess.stderr)
              .thenAnswer((Invocation invocation) => const Stream<List<int>>.empty());
          // Delay return of exitCode until after stdout stream data, since it terminates the logger.
          when(mockProcess.exitCode)
              .thenAnswer((Invocation invocation) => Future<int>.delayed(Duration.zero, () => 0));
          return Future<Process>.value(mockProcess);
        });
338

339
      final IOSSimulator device = IOSSimulator('123456', simulatorCategory: 'iOS 11.0');
340
      final DeviceLogReader logReader = device.getLogReader(
341
        app: BuildableIOSApp(mockIosProject),
342 343 344 345 346 347 348 349 350 351 352 353
      );

      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)',
      ]);
    }, overrides: <Type, Generator>{
      ProcessManager: () => mockProcessManager,
    });
  });
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391

  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"
      }
    ]
  }
}
    ''';

    MockProcessManager mockProcessManager;
    SimControl simControl;

    setUp(() {
392
      mockProcessManager = MockProcessManager();
393 394 395
      when(mockProcessManager.run(any)).thenAnswer((Invocation _) async {
        return ProcessResult(mockPid, 0, validSimControlOutput, '');
      });
396

397
      simControl = SimControl();
398 399
    });

400 401
    testUsingContext('getDevices succeeds', () async {
      final List<SimDevice> devices = await simControl.getDevices();
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429

      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);
    }, overrides: <Type, Generator>{
      ProcessManager: () => mockProcessManager,
      SimControl: () => simControl,
    });
430 431 432 433 434 435 436 437 438 439 440

    testUsingContext('getDevices handles bad simctl output', () async {
      when(mockProcessManager.run(any))
          .thenAnswer((Invocation _) async => ProcessResult(mockPid, 0, 'Install Started', ''));
      final List<SimDevice> devices = await simControl.getDevices();

      expect(devices, isEmpty);
    }, overrides: <Type, Generator>{
      ProcessManager: () => mockProcessManager,
      SimControl: () => simControl,
    });
441 442 443 444 445 446

    testUsingContext('sdkMajorVersion defaults to 11 when sdkNameAndVersion is junk', () async {
      final IOSSimulator iosSimulatorA = IOSSimulator('x', name: 'Testo', simulatorCategory: 'NaN');

      expect(await iosSimulatorA.sdkMajorVersion, 11);
    });
447
  });
448

449 450 451 452 453 454 455 456
  group('startApp', () {
    SimControl simControl;

    setUp(() {
      simControl = MockSimControl();
    });

    testUsingContext("startApp uses compiled app's Info.plist to find CFBundleIdentifier", () async {
457
        final IOSSimulator device = IOSSimulator('x', name: 'iPhone SE', simulatorCategory: 'iOS 11.2');
458
        when(PlistParser.instance.getValueFromFile(any, any)).thenReturn('correct');
459 460 461 462 463 464 465 466 467 468 469 470

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

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

        verify(simControl.launch(any, 'correct', any));
      },
      overrides: <Type, Generator>{
        SimControl: () => simControl,
471
        PlistParser: () => MockPlistUtils(),
472 473 474 475
      },
    );
  });

476 477 478 479 480 481 482 483 484 485
  testUsingContext('IOSDevice.isSupportedForProject is true on module project', () async {
    fs.file('pubspec.yaml')
      ..createSync()
      ..writeAsStringSync(r'''
name: example

flutter:
  module: {}
''');
    fs.file('.packages').createSync();
486
    final FlutterProject flutterProject = FlutterProject.current();
487 488 489 490 491 492 493 494 495 496

    expect(IOSSimulator('test').isSupportedForProject(flutterProject), true);
  }, overrides: <Type, Generator>{
    FileSystem: () => MemoryFileSystem(),
  });

  testUsingContext('IOSDevice.isSupportedForProject is true with editable host app', () async {
    fs.file('pubspec.yaml').createSync();
    fs.file('.packages').createSync();
    fs.directory('ios').createSync();
497
    final FlutterProject flutterProject = FlutterProject.current();
498 499 500 501 502 503 504 505 506

    expect(IOSSimulator('test').isSupportedForProject(flutterProject), true);
  }, overrides: <Type, Generator>{
    FileSystem: () => MemoryFileSystem(),
  });

  testUsingContext('IOSDevice.isSupportedForProject is false with no host app and no module', () async {
    fs.file('pubspec.yaml').createSync();
    fs.file('.packages').createSync();
507
    final FlutterProject flutterProject = FlutterProject.current();
508 509 510 511 512

    expect(IOSSimulator('test').isSupportedForProject(flutterProject), false);
  }, overrides: <Type, Generator>{
    FileSystem: () => MemoryFileSystem(),
  });
513
}