mac_test.dart 13.9 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/logger.dart';
10
import 'package:flutter_tools/src/base/process.dart';
11
import 'package:flutter_tools/src/build_info.dart';
12
import 'package:flutter_tools/src/cache.dart';
13
import 'package:flutter_tools/src/ios/code_signing.dart';
14
import 'package:flutter_tools/src/ios/iproxy.dart';
15
import 'package:flutter_tools/src/ios/mac.dart';
16
import 'package:flutter_tools/src/project.dart';
17
import 'package:flutter_tools/src/reporting/reporting.dart';
18
import 'package:test/fake.dart';
19

20
import '../../src/common.dart';
21
import '../../src/fake_process_manager.dart';
22
import '../../src/fakes.dart';
23 24

void main() {
25
  late BufferLogger logger;
26 27 28 29 30

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

31
  group('IMobileDevice', () {
32 33
    late Artifacts artifacts;
    late Cache cache;
34 35

    setUp(() {
36 37 38 39
      artifacts = Artifacts.test();
      cache = Cache.test(
        artifacts: <ArtifactSet>[
          FakeDyldEnvironmentArtifact(),
40 41 42
        ],
        processManager: FakeProcessManager.any(),
      );
43 44
    });

45
    group('screenshot', () {
46 47
      late FakeProcessManager fakeProcessManager;
      late File outputFile;
48 49

      setUp(() {
50
        fakeProcessManager = FakeProcessManager.empty();
51
        outputFile = MemoryFileSystem.test().file('image.png');
52 53
      });

54
      testWithoutContext('error if idevicescreenshot is not installed', () async {
55
        // Let `idevicescreenshot` fail with exit code 1.
56 57
        fakeProcessManager.addCommand(FakeCommand(
          command: <String>[
58
            'HostArtifact.idevicescreenshot',
59 60 61 62 63 64 65 66 67
            outputFile.path,
            '--udid',
            '1234',
          ],
          environment: const <String, String>{
            'DYLD_LIBRARY_PATH': '/path/to/libraries',
          },
          exitCode: 1,
        ));
68

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

76
        expect(() async => iMobileDevice.takeScreenshot(
77
          outputFile,
78
          '1234',
79
          IOSDeviceConnectionInterface.usb,
80
        ), throwsA(anything));
81
        expect(fakeProcessManager.hasRemainingExpectations, isFalse);
82 83
      });

84
      testWithoutContext('idevicescreenshot captures and returns USB screenshot', () async {
85 86
        fakeProcessManager.addCommand(FakeCommand(
          command: <String>[
87
            'HostArtifact.idevicescreenshot', outputFile.path, '--udid', '1234',
88 89 90
          ],
          environment: const <String, String>{'DYLD_LIBRARY_PATH': '/path/to/libraries'},
        ));
91

92
        final IMobileDevice iMobileDevice = IMobileDevice(
93 94
          artifacts: artifacts,
          cache: cache,
95
          processManager: fakeProcessManager,
96 97 98
          logger: logger,
        );

99
        await iMobileDevice.takeScreenshot(
100
          outputFile,
101
          '1234',
102
          IOSDeviceConnectionInterface.usb,
103
        );
104
        expect(fakeProcessManager.hasRemainingExpectations, isFalse);
105
      });
106 107

      testWithoutContext('idevicescreenshot captures and returns network screenshot', () async {
108 109
        fakeProcessManager.addCommand(FakeCommand(
          command: <String>[
110
            'HostArtifact.idevicescreenshot', outputFile.path, '--udid', '1234', '--network',
111 112 113
          ],
          environment: const <String, String>{'DYLD_LIBRARY_PATH': '/path/to/libraries'},
        ));
114 115

        final IMobileDevice iMobileDevice = IMobileDevice(
116 117
          artifacts: artifacts,
          cache: cache,
118
          processManager: fakeProcessManager,
119 120 121 122
          logger: logger,
        );

        await iMobileDevice.takeScreenshot(
123
          outputFile,
124
          '1234',
125
          IOSDeviceConnectionInterface.network,
126
        );
127
        expect(fakeProcessManager.hasRemainingExpectations, isFalse);
128
      });
129 130 131
    });
  });

132
  group('Diagnose Xcode build failure', () {
133 134
    late Map<String, String> buildSettings;
    late TestUsage testUsage;
135 136

    setUp(() {
xster's avatar
xster committed
137 138 139
      buildSettings = <String, String>{
        'PRODUCT_BUNDLE_IDENTIFIER': 'test.app',
      };
140
      testUsage = TestUsage();
141 142
    });

143
    testWithoutContext('Sends analytics when bitcode fails', () async {
144 145 146 147 148 149 150
      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',
151
          environmentType: EnvironmentType.physical,
152 153 154 155
          buildSettings: buildSettings,
        ),
      );

156 157 158 159
      await diagnoseXcodeBuildFailure(buildResult, testUsage, logger);
      expect(testUsage.events, contains(
        TestUsageEvent(
          'build',
160
          'ios',
161
          label: 'xcode-bitcode-failure',
162 163 164 165
          parameters: CustomDimensions(
            buildEventCommand: buildCommands.toString(),
            buildEventSettings: buildSettings.toString(),
          ),
166 167
        ),
      ));
168 169
    });

170 171 172 173 174
    testWithoutContext('fallback to stdout: No provisioning profile shows message', () async {
      final Map<String, String> buildSettingsWithDevTeam = <String, String>{
        'PRODUCT_BUNDLE_IDENTIFIER': 'test.app',
        'DEVELOPMENT_TEAM': 'a team',
      };
175
      final XcodeBuildResult buildResult = XcodeBuildResult(
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
        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
202
    [BCEROR]"Runner" requires a provisioning profile. Select a provisioning profile in the Signing & Capabilities editor.
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    [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
224
    No profiles for 'com.example.test' were found:  Xcode couldn't find a provisioning profile matching 'com.example.test'.
225 226 227 228 229 230 231
    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.''',
232
        xcodeBuildExecution: XcodeBuildExecution(
xster's avatar
xster committed
233 234
          buildCommands: <String>['xcrun', 'xcodebuild', 'blah'],
          appDirectory: '/blah/blah',
235
          environmentType: EnvironmentType.physical,
236
          buildSettings: buildSettingsWithDevTeam,
237 238 239
        ),
      );

240
      await diagnoseXcodeBuildFailure(buildResult, testUsage, logger);
241
      expect(
242
        logger.errorText,
243
        contains(noProvisioningProfileInstruction),
244
      );
245
    });
246

247
    testWithoutContext('No development team shows message', () async {
248
      final XcodeBuildResult buildResult = XcodeBuildResult(
249 250
        success: false,
        stdout: '''
251
Running "flutter pub get" in flutter_gallery...  0.6s
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 303 304 305 306 307 308 309 310 311 312
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.''',
313
        xcodeBuildExecution: XcodeBuildExecution(
xster's avatar
xster committed
314 315
          buildCommands: <String>['xcrun', 'xcodebuild', 'blah'],
          appDirectory: '/blah/blah',
316
          environmentType: EnvironmentType.physical,
xster's avatar
xster committed
317
          buildSettings: buildSettings,
318 319 320
        ),
      );

321
      await diagnoseXcodeBuildFailure(buildResult, testUsage, logger);
322
      expect(
323
        logger.errorText,
324
        contains('Building a deployable iOS app requires a selected Development Team with a \nProvisioning Profile.'),
325
      );
326
    });
327
  });
328 329

  group('Upgrades project.pbxproj for old asset usage', () {
330 331 332 333 334 335 336 337 338 339 340 341 342
    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';
343

344
    testWithoutContext('upgradePbxProjWithFlutterAssets', () async {
345 346
      final File pbxprojFile = MemoryFileSystem.test().file('project.pbxproj')
        ..writeAsStringSync(flutterAssetPbxProjLines);
347
      final FakeIosProject project = FakeIosProject(pbxprojFile);
348

349
      bool result = upgradePbxProjWithFlutterAssets(project, logger);
350 351
      expect(result, true);
      expect(
352
        logger.statusText,
353 354
        contains('Removing obsolete reference to flutter_assets'),
      );
355
      logger.clear();
356

357
      pbxprojFile.writeAsStringSync(appFlxPbxProjLines);
358
      result = upgradePbxProjWithFlutterAssets(project, logger);
359 360
      expect(result, true);
      expect(
361
        logger.statusText,
362 363
        contains('Removing obsolete reference to app.flx'),
      );
364
      logger.clear();
365

366
      pbxprojFile.writeAsStringSync(cleanPbxProjLines);
367
      result = upgradePbxProjWithFlutterAssets(project, logger);
368 369
      expect(result, true);
      expect(
370
        logger.statusText,
371 372 373 374
        isEmpty,
      );
    });
  });
375 376

  group('remove Finder extended attributes', () {
377
    late Directory projectDirectory;
378 379
    setUp(() {
      final MemoryFileSystem fs = MemoryFileSystem.test();
380
      projectDirectory = fs.directory('flutter_project');
381 382 383 384 385 386 387 388 389
    });

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

394
      await removeFinderExtendedAttributes(projectDirectory, ProcessUtils(processManager: processManager, logger: logger), logger);
395
      expect(processManager, hasNoRemainingExpectations);
396 397 398 399
    });

    testWithoutContext('ignores errors', () async {
      final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
400 401 402 403 404 405 406 407 408 409
        FakeCommand(
          command: <String>[
            'xattr',
            '-r',
            '-d',
            'com.apple.FinderInfo',
            projectDirectory.path,
          ],
          exitCode: 1,
        ),
410 411
      ]);

412
      await removeFinderExtendedAttributes(projectDirectory, ProcessUtils(processManager: processManager, logger: logger), logger);
413
      expect(logger.traceText, contains('Failed to remove xattr com.apple.FinderInfo'));
414
      expect(processManager, hasNoRemainingExpectations);
415 416
    });
  });
417
}
418 419 420 421 422 423 424

class FakeIosProject extends Fake implements IosProject {
  FakeIosProject(this.xcodeProjectInfoFile);
  @override
  final File xcodeProjectInfoFile;

  @override
425
  Future<String> hostAppBundleName(BuildInfo? buildInfo) async => 'UnitTestRunner.app';
426 427

  @override
428
  Directory get xcodeProject => xcodeProjectInfoFile.fileSystem.directory('Runner.xcodeproj');
429
}