mac_test.dart 16.8 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 'package:file/file.dart';
6
import 'package:file/memory.dart';
7
import 'package:flutter_tools/src/artifacts.dart';
8
import 'package:flutter_tools/src/base/file_system.dart';
9
import 'package:flutter_tools/src/base/io.dart' show ProcessResult;
10
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/cache.dart';
14
import 'package:flutter_tools/src/ios/devices.dart';
15
import 'package:flutter_tools/src/ios/mac.dart';
16
import 'package:flutter_tools/src/ios/xcodeproj.dart';
17
import 'package:flutter_tools/src/project.dart';
18
import 'package:flutter_tools/src/reporting/reporting.dart';
19 20
import 'package:mockito/mockito.dart';
import 'package:process/process.dart';
21

22 23
import '../../src/common.dart';
import '../../src/context.dart';
24
import '../../src/fakes.dart';
25

26
final Generator _kNoColorTerminalPlatform = () => FakePlatform(stdoutSupportsAnsi: false);
27 28 29 30
final Map<Type, Generator> noColorTerminalOverride = <Type, Generator>{
  Platform: _kNoColorTerminalPlatform,
};

31
class MockProcessManager extends Mock implements ProcessManager {}
32
class MockXcodeProjectInterpreter extends Mock implements XcodeProjectInterpreter {}
33
class MockIosProject extends Mock implements IosProject {}
34

35
void main() {
36 37 38 39 40 41
  BufferLogger logger;

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

42
  group('IMobileDevice', () {
43 44
    Artifacts artifacts;
    Cache cache;
45 46

    setUp(() {
47 48 49 50 51
      artifacts = Artifacts.test();
      cache = Cache.test(
        artifacts: <ArtifactSet>[
          FakeDyldEnvironmentArtifact(),
        ]);
52 53
    });

54 55
    group('screenshot', () {
      MockProcessManager mockProcessManager;
56
      File outputFile;
57 58

      setUp(() {
59
        mockProcessManager = MockProcessManager();
60
        outputFile = MemoryFileSystem.test().file('image.png');
61 62
      });

63
      testWithoutContext('error if idevicescreenshot is not installed', () async {
64
        // Let `idevicescreenshot` fail with exit code 1.
65 66
        when(mockProcessManager.run(<String>['Artifact.idevicescreenshot.TargetPlatform.ios', outputFile.path],
            environment: <String, String>{'DYLD_LIBRARY_PATH': 'Artifact.idevicescreenshot.TargetPlatform.ios'},
67
            workingDirectory: null,
68
        )).thenAnswer((_) => Future<ProcessResult>.value(ProcessResult(4, 1, '', '')));
69

70
        final IMobileDevice iMobileDevice = IMobileDevice(
71 72
          artifacts: artifacts,
          cache: cache,
73 74 75 76
          processManager: mockProcessManager,
          logger: logger,
        );

77
        expect(() async => await iMobileDevice.takeScreenshot(
78
          outputFile,
79 80 81
          '1234',
          IOSDeviceInterface.usb,
        ), throwsA(anything));
82 83
      });

84
      testWithoutContext('idevicescreenshot captures and returns USB screenshot', () async {
85
        when(mockProcessManager.run(any, environment: anyNamed('environment'), workingDirectory: null)).thenAnswer(
86
            (Invocation invocation) => Future<ProcessResult>.value(ProcessResult(4, 0, '', '')));
87

88
        final IMobileDevice iMobileDevice = IMobileDevice(
89 90
          artifacts: artifacts,
          cache: cache,
91 92 93 94
          processManager: mockProcessManager,
          logger: logger,
        );

95
        await iMobileDevice.takeScreenshot(
96
          outputFile,
97 98 99
          '1234',
          IOSDeviceInterface.usb,
        );
100 101
        verify(mockProcessManager.run(<String>['Artifact.idevicescreenshot.TargetPlatform.ios', outputFile.path, '--udid', '1234'],
            environment: <String, String>{'DYLD_LIBRARY_PATH': '/path/to/libraries'},
102
            workingDirectory: null,
103 104
        ));
      });
105 106 107 108 109 110

      testWithoutContext('idevicescreenshot captures and returns network screenshot', () async {
        when(mockProcessManager.run(any, environment: anyNamed('environment'), workingDirectory: null)).thenAnswer(
            (Invocation invocation) => Future<ProcessResult>.value(ProcessResult(4, 0, '', '')));

        final IMobileDevice iMobileDevice = IMobileDevice(
111 112
          artifacts: artifacts,
          cache: cache,
113 114 115 116 117
          processManager: mockProcessManager,
          logger: logger,
        );

        await iMobileDevice.takeScreenshot(
118
          outputFile,
119 120 121
          '1234',
          IOSDeviceInterface.network,
        );
122 123
        verify(mockProcessManager.run(<String>['Artifact.idevicescreenshot.TargetPlatform.ios', outputFile.path, '--udid', '1234', '--network'],
          environment: <String, String>{'DYLD_LIBRARY_PATH': '/path/to/libraries'},
124 125 126
          workingDirectory: null,
        ));
      });
127 128 129
    });
  });

130
  group('Diagnose Xcode build failure', () {
xster's avatar
xster committed
131
    Map<String, String> buildSettings;
132
    MockUsage mockUsage;
133 134

    setUp(() {
xster's avatar
xster committed
135 136 137
      buildSettings = <String, String>{
        'PRODUCT_BUNDLE_IDENTIFIER': 'test.app',
      };
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
      mockUsage = MockUsage();
    });

    testUsingContext('Sends analytics when bitcode fails', () async {
      const List<String> buildCommands = <String>['xcrun', 'cc', 'blah'];
      final XcodeBuildResult buildResult = XcodeBuildResult(
        success: false,
        stdout: 'BITCODE_ENABLED = YES',
        xcodeBuildExecution: XcodeBuildExecution(
          buildCommands: buildCommands,
          appDirectory: '/blah/blah',
          buildForPhysicalDevice: true,
          buildSettings: buildSettings,
        ),
      );

154
      await diagnoseXcodeBuildFailure(buildResult, mockUsage, logger);
155 156 157
      verify(mockUsage.sendEvent('build',
        any,
        label: 'xcode-bitcode-failure',
158 159 160
        parameters: <String, String>{
          cdKey(CustomDimensions.buildEventCommand): buildCommands.toString(),
          cdKey(CustomDimensions.buildEventSettings): buildSettings.toString(),
161
      })).called(1);
162 163 164
    });

    testUsingContext('No provisioning profile shows message', () async {
165
      final XcodeBuildResult buildResult = XcodeBuildResult(
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
        success: false,
        stdout: '''
Launching lib/main.dart on iPhone in debug mode...
Signing iOS app for device deployment using developer identity: "iPhone Developer: test@flutter.io (1122334455)"
Running Xcode build...                                1.3s
Failed to build iOS app
Error output from Xcode build:

    ** BUILD FAILED **


    The following build commands failed:
    	Check dependencies
    (1 failure)
Xcode's output:

    Build settings from command line:
        ARCHS = arm64
        BUILD_DIR = /Users/blah/blah
        DEVELOPMENT_TEAM = AABBCCDDEE
        ONLY_ACTIVE_ARCH = YES
        SDKROOT = iphoneos10.3

    === CLEAN TARGET Runner OF PROJECT Runner WITH CONFIGURATION Release ===

    Check dependencies
192
    [BCEROR]No profiles for 'com.example.test' were found:  Xcode couldn't find a provisioning profile matching 'com.example.test'.
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    [BCEROR]Code signing is required for product type 'Application' in SDK 'iOS 10.3'
    [BCEROR]Code signing is required for product type 'Application' in SDK 'iOS 10.3'
    [BCEROR]Code signing is required for product type 'Application' in SDK 'iOS 10.3'

    Create product structure
    /bin/mkdir -p /Users/blah/Runner.app

    Clean.Remove clean /Users/blah/Runner.app.dSYM
        builtin-rm -rf /Users/blah/Runner.app.dSYM

    Clean.Remove clean /Users/blah/Runner.app
        builtin-rm -rf /Users/blah/Runner.app

    Clean.Remove clean /Users/blah/Runner-dfvicjniknvzghgwsthwtgcjhtsk/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build
        builtin-rm -rf /Users/blah/Runner-dfvicjniknvzghgwsthwtgcjhtsk/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build

    ** CLEAN SUCCEEDED **

    === BUILD TARGET Runner OF PROJECT Runner WITH CONFIGURATION Release ===

    Check dependencies
214
    No profiles for 'com.example.test' were found:  Xcode couldn't find a provisioning profile matching 'com.example.test'.
215 216 217 218 219 220 221
    Code signing is required for product type 'Application' in SDK 'iOS 10.3'
    Code signing is required for product type 'Application' in SDK 'iOS 10.3'
    Code signing is required for product type 'Application' in SDK 'iOS 10.3'

Could not build the precompiled application for the device.

Error launching application on iPhone.''',
222
        xcodeBuildExecution: XcodeBuildExecution(
xster's avatar
xster committed
223 224 225 226
          buildCommands: <String>['xcrun', 'xcodebuild', 'blah'],
          appDirectory: '/blah/blah',
          buildForPhysicalDevice: true,
          buildSettings: buildSettings,
227 228 229
        ),
      );

230
      await diagnoseXcodeBuildFailure(buildResult, mockUsage, logger);
231
      expect(
232
        logger.errorText,
233
        contains("No Provisioning Profile was found for your project's Bundle Identifier or your \ndevice."),
234
      );
235
    }, overrides: noColorTerminalOverride);
236 237

    testUsingContext('No development team shows message', () async {
238
      final XcodeBuildResult buildResult = XcodeBuildResult(
239 240
        success: false,
        stdout: '''
241
Running "flutter pub get" in flutter_gallery...  0.6s
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
Launching lib/main.dart on x in release mode...
Running pod install...                                1.2s
Running Xcode build...                                1.4s
Failed to build iOS app
Error output from Xcode build:

    ** BUILD FAILED **


    The following build commands failed:
    	Check dependencies
    (1 failure)
Xcode's output:

    blah

    === CLEAN TARGET url_launcher OF PROJECT Pods WITH CONFIGURATION Release ===

    Check dependencies

    blah

    === CLEAN TARGET Pods-Runner OF PROJECT Pods WITH CONFIGURATION Release ===

    Check dependencies

    blah

    === CLEAN TARGET Runner OF PROJECT Runner WITH CONFIGURATION Release ===

    Check dependencies
    [BCEROR]Signing for "Runner" requires a development team. Select a development team in the project editor.
    [BCEROR]Code signing is required for product type 'Application' in SDK 'iOS 10.3'
    [BCEROR]Code signing is required for product type 'Application' in SDK 'iOS 10.3'
    [BCEROR]Code signing is required for product type 'Application' in SDK 'iOS 10.3'

    blah

    ** CLEAN SUCCEEDED **

    === BUILD TARGET url_launcher OF PROJECT Pods WITH CONFIGURATION Release ===

    Check dependencies

    blah

    === BUILD TARGET Pods-Runner OF PROJECT Pods WITH CONFIGURATION Release ===

    Check dependencies

    blah

    === BUILD TARGET Runner OF PROJECT Runner WITH CONFIGURATION Release ===

    Check dependencies
    Signing for "Runner" requires a development team. Select a development team in the project editor.
    Code signing is required for product type 'Application' in SDK 'iOS 10.3'
    Code signing is required for product type 'Application' in SDK 'iOS 10.3'
    Code signing is required for product type 'Application' in SDK 'iOS 10.3'

Could not build the precompiled application for the device.''',
303
        xcodeBuildExecution: XcodeBuildExecution(
xster's avatar
xster committed
304 305 306 307
          buildCommands: <String>['xcrun', 'xcodebuild', 'blah'],
          appDirectory: '/blah/blah',
          buildForPhysicalDevice: true,
          buildSettings: buildSettings,
308 309 310
        ),
      );

311
      await diagnoseXcodeBuildFailure(buildResult, mockUsage, logger);
312
      expect(
313
        logger.errorText,
314
        contains('Building a deployable iOS app requires a selected Development Team with a \nProvisioning Profile.'),
315
      );
316
    }, overrides: noColorTerminalOverride);
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

    testUsingContext('embedded and linked framework iOS mismatch shows message', () async {
      final XcodeBuildResult buildResult = XcodeBuildResult(
        success: false,
        stdout: '''
Launching lib/main.dart on iPhone in debug mode...
Automatically signing iOS for device deployment using specified development team in Xcode project: blah
Xcode build done. 5.7s
Failed to build iOS app
Error output from Xcode build:

** BUILD FAILED **
Xcode's output:

note: Using new build system
note: Building targets in parallel
note: Planning build
note: Constructing build description
error: Building for iOS Simulator, but the linked and embedded framework 'App.framework' was built for iOS. (in target 'Runner' from project 'Runner')
Could not build the precompiled application for the device.

Error launching application on iPhone.
Exited (sigterm)''',
        xcodeBuildExecution: XcodeBuildExecution(
          buildCommands: <String>['xcrun', 'xcodebuild', 'blah'],
          appDirectory: '/blah/blah',
          buildForPhysicalDevice: true,
          buildSettings: buildSettings,
        ),
      );

348
      await diagnoseXcodeBuildFailure(buildResult, mockUsage, logger);
349
      expect(
350
        logger.errorText,
351 352 353 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
        contains('Your Xcode project requires migration.'),
      );
    }, overrides: noColorTerminalOverride);

    testUsingContext('embedded and linked framework iOS simulator mismatch shows message', () async {
      final XcodeBuildResult buildResult = XcodeBuildResult(
        success: false,
        stdout: '''
Launching lib/main.dart on iPhone in debug mode...
Automatically signing iOS for device deployment using specified development team in Xcode project: blah
Xcode build done. 5.7s
Failed to build iOS app
Error output from Xcode build:

** BUILD FAILED **
Xcode's output:

note: Using new build system
note: Building targets in parallel
note: Planning build
note: Constructing build description
error: Building for iOS, but the linked and embedded framework 'App.framework' was built for iOS Simulator. (in target 'Runner' from project 'Runner')
Could not build the precompiled application for the device.

Error launching application on iPhone.
Exited (sigterm)''',
        xcodeBuildExecution: XcodeBuildExecution(
          buildCommands: <String>['xcrun', 'xcodebuild', 'blah'],
          appDirectory: '/blah/blah',
          buildForPhysicalDevice: true,
          buildSettings: buildSettings,
        ),
      );

385
      await diagnoseXcodeBuildFailure(buildResult, mockUsage, logger);
386
      expect(
387
        logger.errorText,
388 389 390
        contains('Your Xcode project requires migration.'),
      );
    }, overrides: noColorTerminalOverride);
391
  });
392 393

  group('Upgrades project.pbxproj for old asset usage', () {
394 395 396 397 398 399 400 401 402 403 404 405 406
    const String flutterAssetPbxProjLines =
      '/* flutter_assets */\n'
      '/* App.framework\n'
      'another line';

    const String appFlxPbxProjLines =
      '/* app.flx\n'
      '/* App.framework\n'
      'another line';

    const String cleanPbxProjLines =
      '/* App.framework\n'
      'another line';
407

408
    testWithoutContext('upgradePbxProjWithFlutterAssets', () async {
409
      final MockIosProject project = MockIosProject();
410 411
      final File pbxprojFile = MemoryFileSystem.test().file('project.pbxproj')
        ..writeAsStringSync(flutterAssetPbxProjLines);
412 413

      when(project.xcodeProjectInfoFile).thenReturn(pbxprojFile);
414
      when(project.hostAppBundleName(any)).thenAnswer((_) => Future<String>.value('UnitTestRunner.app'));
415

416
      bool result = upgradePbxProjWithFlutterAssets(project, logger);
417 418
      expect(result, true);
      expect(
419
        logger.statusText,
420 421
        contains('Removing obsolete reference to flutter_assets'),
      );
422
      logger.clear();
423

424
      pbxprojFile.writeAsStringSync(appFlxPbxProjLines);
425
      result = upgradePbxProjWithFlutterAssets(project, logger);
426 427
      expect(result, true);
      expect(
428
        logger.statusText,
429 430
        contains('Removing obsolete reference to app.flx'),
      );
431
      logger.clear();
432

433
      pbxprojFile.writeAsStringSync(cleanPbxProjLines);
434
      result = upgradePbxProjWithFlutterAssets(project, logger);
435 436
      expect(result, true);
      expect(
437
        logger.statusText,
438 439 440 441
        isEmpty,
      );
    });
  });
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481

  group('remove Finder extended attributes', () {
    Directory iosProjectDirectory;
    setUp(() {
      final MemoryFileSystem fs = MemoryFileSystem.test();
      iosProjectDirectory = fs.directory('ios');
    });

    testWithoutContext('removes xattr', () async {
      final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
        FakeCommand(command: <String>[
          'xattr',
          '-r',
          '-d',
          'com.apple.FinderInfo',
          iosProjectDirectory.path,
        ])
      ]);

      await removeFinderExtendedAttributes(iosProjectDirectory, ProcessUtils(processManager: processManager, logger: logger), logger);
      expect(processManager.hasRemainingExpectations, false);
    });

    testWithoutContext('ignores errors', () async {
      final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
        FakeCommand(command: <String>[
          'xattr',
          '-r',
          '-d',
          'com.apple.FinderInfo',
          iosProjectDirectory.path,
        ], exitCode: 1,
        )
      ]);

      await removeFinderExtendedAttributes(iosProjectDirectory, ProcessUtils(processManager: processManager, logger: logger), logger);
      expect(logger.traceText, contains('Failed to remove xattr com.apple.FinderInfo'));
      expect(processManager.hasRemainingExpectations, false);
    });
  });
482
}
483 484

class MockUsage extends Mock implements Usage {}