build_ios_test.dart 40.1 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter 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 'package:args/command_runner.dart';
6
import 'package:file/memory.dart';
7
import 'package:flutter_tools/src/android/android_sdk.dart';
8
import 'package:flutter_tools/src/base/common.dart';
9
import 'package:flutter_tools/src/base/file_system.dart';
10
import 'package:flutter_tools/src/base/logger.dart';
11
import 'package:flutter_tools/src/base/os.dart';
12
import 'package:flutter_tools/src/base/platform.dart';
13
import 'package:flutter_tools/src/build_info.dart';
14
import 'package:flutter_tools/src/build_system/build_system.dart';
15 16
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/build.dart';
17
import 'package:flutter_tools/src/commands/build_ios.dart';
18
import 'package:flutter_tools/src/ios/code_signing.dart';
19
import 'package:flutter_tools/src/ios/mac.dart';
20 21
import 'package:flutter_tools/src/ios/xcodeproj.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';
22
import 'package:test/fake.dart';
23

24
import '../../general.shard/ios/xcresult_test_data.dart';
25 26
import '../../src/common.dart';
import '../../src/context.dart';
27
import '../../src/test_build_system.dart';
28
import '../../src/test_flutter_command_runner.dart';
29 30

class FakeXcodeProjectInterpreterWithBuildSettings extends FakeXcodeProjectInterpreter {
31 32 33

  FakeXcodeProjectInterpreterWithBuildSettings({this.productBundleIdentifier, this.developmentTeam = 'abc'});

34 35 36
  @override
  Future<Map<String, String>> getBuildSettings(
      String projectPath, {
37
        XcodeProjectBuildContext? buildContext,
38 39 40
        Duration timeout = const Duration(minutes: 1),
      }) async {
    return <String, String>{
41
      'PRODUCT_BUNDLE_IDENTIFIER': productBundleIdentifier ?? 'io.flutter.someProject',
42 43
      'TARGET_BUILD_DIR': 'build/ios/Release-iphoneos',
      'WRAPPER_NAME': 'Runner.app',
44
      if (developmentTeam != null) 'DEVELOPMENT_TEAM': developmentTeam!,
45 46
    };
  }
47 48

  /// The value of 'PRODUCT_BUNDLE_IDENTIFIER'.
49
  final String? productBundleIdentifier;
50

51
  final String? developmentTeam;
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
}

final Platform macosPlatform = FakePlatform(
  operatingSystem: 'macos',
  environment: <String, String>{
    'FLUTTER_ROOT': '/',
    'HOME': '/',
  }
);
final Platform notMacosPlatform = FakePlatform(
  environment: <String, String>{
    'FLUTTER_ROOT': '/',
  }
);

void main() {
68 69
  late FileSystem fileSystem;
  late TestUsage usage;
70 71 72 73 74 75 76 77 78 79 80

  setUpAll(() {
    Cache.disableLocking();
  });

  setUp(() {
    fileSystem = MemoryFileSystem.test();
    usage = TestUsage();
  });

  // Sets up the minimal mock project files necessary to look like a Flutter project.
81
  void createCoreMockProjectFiles() {
82 83 84 85 86 87
    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('.packages').createSync();
    fileSystem.file(fileSystem.path.join('lib', 'main.dart')).createSync(recursive: true);
  }

  // Sets up the minimal mock project files necessary for iOS builds to succeed.
88
  void createMinimalMockProjectFiles() {
89 90 91
    fileSystem.directory(fileSystem.path.join('ios', 'Runner.xcodeproj')).createSync(recursive: true);
    fileSystem.directory(fileSystem.path.join('ios', 'Runner.xcworkspace')).createSync(recursive: true);
    fileSystem.file(fileSystem.path.join('ios', 'Runner.xcodeproj', 'project.pbxproj')).createSync();
92
    createCoreMockProjectFiles();
93 94 95
  }

  const FakeCommand xattrCommand = FakeCommand(command: <String>[
96
    'xattr', '-r', '-d', 'com.apple.FinderInfo', '/',
97 98
  ]);

99
  FakeCommand setUpRsyncCommand({void Function()? onRun}) {
100 101 102
    return FakeCommand(
      command: const <String>[
        'rsync',
103
        '-8',
104 105 106 107 108
        '-av',
        '--delete',
        'build/ios/Release-iphoneos/Runner.app',
        'build/ios/iphoneos',
      ],
109 110 111 112
      onRun: onRun,
    );
  }

113
  FakeCommand setUpXCResultCommand({String stdout = '', void Function()? onRun}) {
114 115 116 117 118 119 120 121 122 123 124 125 126
    return FakeCommand(
      command: const <String>[
        'xcrun',
        'xcresulttool',
        'get',
        '--path',
        _xcBundleFilePath,
        '--format',
        'json',
      ],
      stdout: stdout,
      onRun: onRun,
    );
127 128 129 130
  }

  // Creates a FakeCommand for the xcodebuild call to build the app
  // in the given configuration.
131
  FakeCommand setUpFakeXcodeBuildHandler({
132 133
    bool verbose = false,
    bool simulator = false,
134
    bool customNaming = false,
135
    String? deviceId,
136
    int exitCode = 0,
137 138
    String? stdout,
    void Function()? onRun,
139
  }) {
140 141 142 143
    return FakeCommand(
      command: <String>[
        'xcrun',
        'xcodebuild',
144 145 146 147 148
        '-configuration',
        if (simulator)
          'Debug'
        else
          'Release',
149 150 151 152
        if (verbose)
          'VERBOSE_SCRIPT_LOGGING=YES'
        else
          '-quiet',
153 154 155 156 157
        '-workspace',
        if (customNaming)
          'RenamedWorkspace.xcworkspace'
        else
          'Runner.xcworkspace',
158 159
        '-scheme', 'Runner',
        'BUILD_DIR=/build/ios',
160
        '-sdk',
161 162
        if (simulator) ...<String>[
          'iphonesimulator',
163 164 165 166 167 168 169
        ] else ...<String>[
          'iphoneos',
        ],
        if (deviceId != null) ...<String>[
          '-destination',
          'id=$deviceId',
        ] else if (simulator) ...<String>[
170 171 172 173 174 175
          '-destination',
          'generic/platform=iOS Simulator',
        ] else ...<String>[
          '-destination',
          'generic/platform=iOS',
        ],
176 177
        '-resultBundlePath', _xcBundleFilePath,
        '-resultBundleVersion', '3',
178 179 180 181 182 183
        'FLUTTER_SUPPRESS_ANALYTICS=true',
        'COMPILER_INDEX_STORE_ENABLE=NO',
      ],
      stdout: '''
      TARGET_BUILD_DIR=build/ios/Release-iphoneos
      WRAPPER_NAME=Runner.app
184
      $stdout
185
''',
186
      exitCode: exitCode,
187 188 189 190 191
      onRun: onRun,
    );
  }

  testUsingContext('ios build fails when there is no ios project', () async {
192 193 194 195
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
196
      logger: BufferLogger.test(),
197 198
      osUtils: FakeOperatingSystemUtils(),
    );
199
    createCoreMockProjectFiles();
200 201 202 203 204 205 206 207 208 209 210 211

    expect(createTestCommandRunner(command).run(
      const <String>['build', 'ios', '--no-pub']
    ), throwsToolExit(message: 'Application not configured for iOS'));
  }, overrides: <Type, Generator>{
    Platform: () => macosPlatform,
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.any(),
    XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
  });

  testUsingContext('ios build fails in debug with code analysis', () async {
212 213 214 215
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
216
      logger: BufferLogger.test(),
217 218
      osUtils: FakeOperatingSystemUtils(),
    );
219
    createCoreMockProjectFiles();
220 221 222 223 224 225 226 227 228 229 230 231

    expect(createTestCommandRunner(command).run(
      const <String>['build', 'ios', '--no-pub', '--debug', '--analyze-size']
    ), throwsToolExit(message: '--analyze-size" can only be used on release builds'));
  }, overrides: <Type, Generator>{
    Platform: () => macosPlatform,
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.any(),
    XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
  });

  testUsingContext('ios build fails on non-macOS platform', () async {
232 233 234 235
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
236
      logger: BufferLogger.test(),
237 238
      osUtils: FakeOperatingSystemUtils(),
    );
239 240 241 242 243
    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('.packages').createSync();
    fileSystem.file(fileSystem.path.join('lib', 'main.dart'))
      .createSync(recursive: true);

244
    final bool supported = BuildIOSCommand(logger: BufferLogger.test(), verboseHelp: false).supported;
245 246
    expect(createTestCommandRunner(command).run(
      const <String>['build', 'ios', '--no-pub']
247
    ), supported ? throwsToolExit() : throwsA(isA<UsageException>()));
248 249 250 251 252 253 254 255
  }, overrides: <Type, Generator>{
    Platform: () => notMacosPlatform,
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.any(),
    XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
  });

  testUsingContext('ios build invokes xcode build', () async {
256 257 258 259
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
260
      logger: BufferLogger.test(),
261 262
      osUtils: FakeOperatingSystemUtils(),
    );
263
    createMinimalMockProjectFiles();
264 265 266 267

    await createTestCommandRunner(command).run(
      const <String>['build', 'ios', '--no-pub']
    );
268
    expect(testLogger.statusText, contains('build/ios/iphoneos/Runner.app'));
269 270 271 272
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      xattrCommand,
273
      setUpFakeXcodeBuildHandler(onRun: () {
274 275
        fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true);
      }),
276
      setUpRsyncCommand(),
277 278 279 280 281
    ]),
    Platform: () => macosPlatform,
    XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
  });

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
  testUsingContext('ios build invokes xcode build with renamed xcodeproj and xcworkspace', () async {
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );

    fileSystem.directory(fileSystem.path.join('ios', 'RenamedProj.xcodeproj')).createSync(recursive: true);
    fileSystem.directory(fileSystem.path.join('ios', 'RenamedWorkspace.xcworkspace')).createSync(recursive: true);
    fileSystem.file(fileSystem.path.join('ios', 'RenamedProj.xcodeproj', 'project.pbxproj')).createSync();
    createCoreMockProjectFiles();

    await createTestCommandRunner(command).run(
        const <String>['build', 'ios', '--no-pub']
    );
    expect(testLogger.statusText, contains('build/ios/iphoneos/Runner.app'));
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      xattrCommand,
      setUpFakeXcodeBuildHandler(customNaming: true, onRun: () {
        fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true);
      }),
      setUpRsyncCommand(),
    ]),
    Platform: () => macosPlatform,
    XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
  });

313
  testUsingContext('ios build invokes xcode build with device ID', () async {
314 315 316 317
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
318
      logger: BufferLogger.test(),
319 320
      osUtils: FakeOperatingSystemUtils(),
    );
321
    createMinimalMockProjectFiles();
322 323 324 325 326 327 328 329 330

    await createTestCommandRunner(command).run(
        const <String>['build', 'ios', '--no-pub', '--device-id', '1234']
    );
    expect(testLogger.statusText, contains('build/ios/iphoneos/Runner.app'));
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      xattrCommand,
331
      setUpFakeXcodeBuildHandler(deviceId: '1234', onRun: () {
332 333
        fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true);
      }),
334
      setUpRsyncCommand(),
335 336 337 338 339
    ]),
    Platform: () => macosPlatform,
    XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
  });

340
  testUsingContext('ios simulator build invokes xcode build', () async {
341 342 343 344
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
345
      logger: BufferLogger.test(),
346 347
      osUtils: FakeOperatingSystemUtils(),
    );
348
    createMinimalMockProjectFiles();
349 350 351 352 353 354 355 356

    await createTestCommandRunner(command).run(
      const <String>['build', 'ios', '--simulator', '--no-pub']
    );
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      xattrCommand,
357
      setUpFakeXcodeBuildHandler(simulator: true, onRun: () {
358 359
        fileSystem.directory('build/ios/Debug-iphonesimulator/Runner.app').createSync(recursive: true);
      }),
360
      setUpRsyncCommand(),
361 362 363 364 365 366
    ]),
    Platform: () => macosPlatform,
    XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
  });

  testUsingContext('ios build invokes xcode build with verbosity', () async {
367 368 369 370
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
371
      logger: BufferLogger.test(),
372 373
      osUtils: FakeOperatingSystemUtils(),
    );
374
    createMinimalMockProjectFiles();
375 376 377 378 379 380 381 382

    await createTestCommandRunner(command).run(
      const <String>['build', 'ios', '--no-pub', '-v']
    );
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      xattrCommand,
383
      setUpFakeXcodeBuildHandler(verbose: true, onRun: () {
384 385
        fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true);
      }),
386
      setUpRsyncCommand(),
387 388 389 390 391 392
    ]),
    Platform: () => macosPlatform,
    XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
  });

  testUsingContext('Performs code size analysis and sends analytics', () async {
393 394 395 396
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
397
      logger: BufferLogger.test(),
398 399
      osUtils: FakeOperatingSystemUtils(),
    );
400
    createMinimalMockProjectFiles();
401 402 403 404 405 406

    await createTestCommandRunner(command).run(
      const <String>['build', 'ios', '--no-pub', '--analyze-size']
    );

    expect(testLogger.statusText, contains('A summary of your iOS bundle analysis can be found at'));
407
    expect(testLogger.statusText, contains('dart devtools --appSizeBase='));
408 409 410 411 412 413 414
    expect(usage.events, contains(
      const TestUsageEvent('code-size-analysis', 'ios'),
    ));
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      xattrCommand,
415
      setUpFakeXcodeBuildHandler(onRun: () {
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
        fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true);
        fileSystem.file('build/flutter_size_01/snapshot.arm64.json')
          ..createSync(recursive: true)
          ..writeAsStringSync('''
[
  {
    "l": "dart:_internal",
    "c": "SubListIterable",
    "n": "[Optimized] skip",
    "s": 2400
  }
]''');
        fileSystem.file('build/flutter_size_01/trace.arm64.json')
          ..createSync(recursive: true)
          ..writeAsStringSync('{}');
      }),
432
      setUpRsyncCommand(onRun: () => fileSystem.file('build/ios/iphoneos/Runner.app/Frameworks/App.framework/App')
433 434 435 436 437 438 439 440
        ..createSync(recursive: true)
        ..writeAsBytesSync(List<int>.generate(10000, (int index) => 0))),
    ]),
    Platform: () => macosPlatform,
    FileSystemUtils: () => FileSystemUtils(fileSystem: fileSystem, platform: macosPlatform),
    Usage: () => usage,
    XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
  });
441 442
  group('xcresults device', () {
    testUsingContext('Trace error if xcresult is empty.', () async {
443 444 445 446
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
447
        logger: BufferLogger.test(),
448 449
        osUtils: FakeOperatingSystemUtils(),
      );
450

451
      createMinimalMockProjectFiles();
452 453 454 455 456 457 458 459 460 461 462

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.traceText, contains('xcresult parser: Unrecognized top level json format.'));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
463
        setUpFakeXcodeBuildHandler(exitCode: 1, onRun: () {
464 465
          fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
        }),
466 467
        setUpXCResultCommand(),
        setUpRsyncCommand(),
468 469 470 471 472
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });

473
    testUsingContext('Display xcresult issues on console if parsed, suppress Xcode output', () async {
474 475 476 477
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
478
        logger: BufferLogger.test(),
479 480
        osUtils: FakeOperatingSystemUtils(),
      );
481

482
      createMinimalMockProjectFiles();
483 484 485 486 487 488 489 490

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.errorText, contains("Use of undeclared identifier 'asdas'"));
      expect(testLogger.errorText, contains('/Users/m/Projects/test_create/ios/Runner/AppDelegate.m:7:56'));
491 492
      expect(testLogger.statusText, isNot(contains("Xcode's output")));
      expect(testLogger.statusText, isNot(contains('Lots of spew from Xcode')));
493 494 495 496
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
497
        setUpFakeXcodeBuildHandler(exitCode: 1, onRun: () {
498
          fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
499 500
        }, stdout: 'Lots of spew from Xcode',
        ),
501 502
        setUpXCResultCommand(stdout: kSampleResultJsonWithIssues),
        setUpRsyncCommand(),
503 504 505 506 507 508
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });

    testUsingContext('Do not display xcresult issues that needs to be discarded.', () async {
509 510 511 512
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
513
        logger: BufferLogger.test(),
514 515
        osUtils: FakeOperatingSystemUtils(),
      );
516

517
      createMinimalMockProjectFiles();
518 519 520 521 522 523 524 525 526 527 528 529 530 531

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.errorText, contains("Use of undeclared identifier 'asdas'"));
      expect(testLogger.errorText, contains('/Users/m/Projects/test_create/ios/Runner/AppDelegate.m:7:56'));
      expect(testLogger.errorText, isNot(contains('Command PhaseScriptExecution failed with a nonzero exit code')));
      expect(testLogger.warningText, isNot(contains("The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.0.99.")));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
532
        setUpFakeXcodeBuildHandler(exitCode: 1, onRun: () {
533 534
          fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
        }),
535 536
        setUpXCResultCommand(stdout: kSampleResultJsonWithIssuesToBeDiscarded),
        setUpRsyncCommand(),
537 538 539 540 541 542
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });

    testUsingContext('Trace if xcresult bundle does not exist.', () async {
543 544 545 546
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
547
        logger: BufferLogger.test(),
548 549
        osUtils: FakeOperatingSystemUtils(),
      );
550

551
      createMinimalMockProjectFiles();
552 553 554 555 556 557 558 559 560 561 562

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.traceText, contains('The xcresult bundle are not generated. Displaying xcresult is disabled.'));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
563 564 565
        setUpFakeXcodeBuildHandler(exitCode: 1),
        setUpXCResultCommand(stdout: kSampleResultJsonWithIssues),
        setUpRsyncCommand(),
566 567 568 569 570
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });

571
    testUsingContext('Extra error message for provision profile issue in xcresult bundle.', () async {
572 573 574 575
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
576
        logger: BufferLogger.test(),
577 578
        osUtils: FakeOperatingSystemUtils(),
      );
579

580
      createMinimalMockProjectFiles();
581 582 583 584 585 586 587 588 589 590

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.errorText, contains('Some Provisioning profile issue.'));
      expect(testLogger.errorText, contains('It appears that there was a problem signing your application prior to installation on the device.'));
      expect(testLogger.errorText, contains('Verify that the Bundle Identifier in your project is your signing id in Xcode'));
      expect(testLogger.errorText, contains('open ios/Runner.xcworkspace'));
591
      expect(testLogger.errorText, contains("Also try selecting 'Product > Build' to fix the problem."));
592 593 594 595
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
596
        setUpFakeXcodeBuildHandler(exitCode: 1, onRun: () {
597 598
          fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
        }),
599 600
        setUpXCResultCommand(stdout: kSampleResultJsonWithProvisionIssue),
        setUpRsyncCommand(),
601 602 603 604
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });
605 606

    testUsingContext('Display xcresult issues with no provisioning profile.', () async {
607 608 609 610
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
611
        logger: BufferLogger.test(),
612 613
        osUtils: FakeOperatingSystemUtils(),
      );
614

615
      createMinimalMockProjectFiles();
616 617 618 619 620 621 622 623 624 625 626 627

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.errorText, contains('Runner requires a provisioning profile. Select a provisioning profile in the Signing & Capabilities editor'));
      expect(testLogger.errorText, contains(noProvisioningProfileInstruction));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
628
        setUpFakeXcodeBuildHandler(
629 630 631 632 633
          exitCode: 1,
          onRun: () {
            fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
          }
        ),
634 635
        setUpXCResultCommand(stdout: kSampleResultJsonWithNoProvisioningProfileIssue),
        setUpRsyncCommand(),
636 637 638 639 640
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
    testUsingContext('Delete xcresult bundle before each xcodebuild command.', () async {
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
        logger: BufferLogger.test(),
        osUtils: FakeOperatingSystemUtils(),
      );

      createMinimalMockProjectFiles();

      await createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']);

      expect(testLogger.statusText, contains('Xcode build done.'));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
        // Intentionally fail the first xcodebuild command with concurrent run failure message.
        setUpFakeXcodeBuildHandler(
          exitCode: 1,
          stdout: '$kConcurrentRunFailureMessage1 $kConcurrentRunFailureMessage2',
          onRun: () {
            fileSystem.systemTempDirectory.childFile(_xcBundleFilePath).createSync();
          }
        ),
        // The second xcodebuild is triggered due to above concurrent run failure message.
        setUpFakeXcodeBuildHandler(
          onRun: () {
            // If the file is not cleaned, throw an error, test failure.
            if (fileSystem.systemTempDirectory.childFile(_xcBundleFilePath).existsSync()) {
              throwToolExit('xcresult bundle file existed.', exitCode: 2);
            }
            fileSystem.systemTempDirectory.childFile(_xcBundleFilePath).createSync();
          }
        ),
        setUpXCResultCommand(stdout: kSampleResultJsonNoIssues),
        setUpRsyncCommand(),
      ],
      ),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });

685
    testUsingContext('Failed to parse xcresult but display missing provisioning profile issue from stdout.', () async {
686 687 688 689
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
690
        logger: BufferLogger.test(),
691 692
        osUtils: FakeOperatingSystemUtils(),
      );
693

694
      createMinimalMockProjectFiles();
695 696 697 698 699 700 701 702 703 704 705

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.errorText, contains(noProvisioningProfileInstruction));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
706
        setUpFakeXcodeBuildHandler(
707 708 709 710 711 712 713 714
          exitCode: 1,
          stdout: '''
Runner requires a provisioning profile. Select a provisioning profile in the Signing & Capabilities editor
''',
          onRun: () {
            fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
          }
        ),
715 716
        setUpXCResultCommand(stdout: kSampleResultJsonInvalidIssuesMap),
        setUpRsyncCommand(),
717 718 719 720 721 722
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });

    testUsingContext('Failed to parse xcresult but detected no development team issue.', () async {
723 724 725 726
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
727
        logger: BufferLogger.test(),
728 729
        osUtils: FakeOperatingSystemUtils(),
      );
730

731
      createMinimalMockProjectFiles();
732 733 734 735 736 737 738 739 740 741 742

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.errorText, contains(noDevelopmentTeamInstruction));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
743
        setUpFakeXcodeBuildHandler(
744 745 746 747 748
          exitCode: 1,
          onRun: () {
            fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
          }
        ),
749 750
        setUpXCResultCommand(stdout: kSampleResultJsonInvalidIssuesMap),
        setUpRsyncCommand(),
751 752 753 754 755 756
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(developmentTeam: null),
    });

    testUsingContext('xcresult did not detect issue but detected by stdout.', () async {
757 758 759 760
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
761
        logger: BufferLogger.test(),
762 763
        osUtils: FakeOperatingSystemUtils(),
      );
764

765
      createMinimalMockProjectFiles();
766 767 768 769 770 771 772 773 774 775 776

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.errorText, contains(noProvisioningProfileInstruction));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
777
        setUpFakeXcodeBuildHandler(
778 779 780 781 782 783 784 785
          exitCode: 1,
          stdout: '''
Runner requires a provisioning profile. Select a provisioning profile in the Signing & Capabilities editor
''',
          onRun: () {
            fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
          }
        ),
786 787
        setUpXCResultCommand(stdout: kSampleResultJsonNoIssues),
        setUpRsyncCommand(),
788 789 790 791 792 793 794
      ]),
      EnvironmentType: () => EnvironmentType.physical,
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });

    testUsingContext('xcresult did not detect issue, no development team is detected from build setting.', () async {
795 796 797 798
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
799
        logger: BufferLogger.test(),
800 801
        osUtils: FakeOperatingSystemUtils(),
      );
802

803
      createMinimalMockProjectFiles();
804 805 806 807 808 809 810 811 812 813 814

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.errorText, contains(noDevelopmentTeamInstruction));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
815
        setUpFakeXcodeBuildHandler(
816 817 818 819 820
          exitCode: 1,
          onRun: () {
            fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
          }
        ),
821 822
        setUpXCResultCommand(stdout: kSampleResultJsonInvalidIssuesMap),
        setUpRsyncCommand(),
823 824 825 826 827 828
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(developmentTeam: null),
    });

    testUsingContext('No development team issue error message is not displayed if no provisioning profile issue is detected from xcresult first.', () async {
829 830 831 832
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
833
        logger: BufferLogger.test(),
834 835
        osUtils: FakeOperatingSystemUtils(),
      );
836

837
      createMinimalMockProjectFiles();
838 839 840 841 842 843 844 845 846 847 848 849

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.errorText, contains(noProvisioningProfileInstruction));
      expect(testLogger.errorText, isNot(contains(noDevelopmentTeamInstruction)));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
850
        setUpFakeXcodeBuildHandler(
851 852 853 854 855
          exitCode: 1,
          onRun: () {
            fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
          }
        ),
856 857
        setUpXCResultCommand(stdout: kSampleResultJsonWithNoProvisioningProfileIssue),
        setUpRsyncCommand(),
858 859 860 861 862 863
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(developmentTeam: null),
    });

    testUsingContext('General provisioning profile issue error message is not displayed if no development team issue is detected first.', () async {
864 865 866 867
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
868
        logger: BufferLogger.test(),
869 870
        osUtils: FakeOperatingSystemUtils(),
      );
871

872
      createMinimalMockProjectFiles();
873 874 875 876 877 878 879 880 881 882 883 884

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.errorText, contains(noDevelopmentTeamInstruction));
      expect(testLogger.errorText, isNot(contains('It appears that there was a problem signing your application prior to installation on the device.')));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
885
        setUpFakeXcodeBuildHandler(
886 887 888 889 890
          exitCode: 1,
          onRun: () {
            fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
          }
        ),
891 892
        setUpXCResultCommand(stdout: kSampleResultJsonWithProvisionIssue),
        setUpRsyncCommand(),
893 894 895 896
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(developmentTeam: null),
    });
897 898 899 900
  });

  group('xcresults simulator', () {
    testUsingContext('Trace error if xcresult is empty.', () async {
901 902 903 904
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
905
        logger: BufferLogger.test(),
906 907
        osUtils: FakeOperatingSystemUtils(),
      );
908

909
      createMinimalMockProjectFiles();
910 911 912 913 914 915 916 917 918 919 920

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--simulator', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.traceText, contains('xcresult parser: Unrecognized top level json format.'));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
921
        setUpFakeXcodeBuildHandler(
922 923 924 925 926 927
          simulator: true,
          exitCode: 1,
          onRun: () {
            fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
          },
        ),
928 929
        setUpXCResultCommand(),
        setUpRsyncCommand(),
930 931 932 933 934 935
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });

    testUsingContext('Display xcresult issues on console if parsed.', () async {
936 937 938 939
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
940
        logger: BufferLogger.test(),
941 942
        osUtils: FakeOperatingSystemUtils(),
      );
943

944
      createMinimalMockProjectFiles();
945 946 947 948 949 950 951 952 953 954 955 956

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--simulator',  '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.errorText, contains("Use of undeclared identifier 'asdas'"));
      expect(testLogger.errorText, contains('/Users/m/Projects/test_create/ios/Runner/AppDelegate.m:7:56'));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
957
        setUpFakeXcodeBuildHandler(
958 959 960 961 962 963
          simulator: true,
          exitCode: 1,
          onRun: () {
            fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
          },
        ),
964 965
        setUpXCResultCommand(stdout: kSampleResultJsonWithIssues),
        setUpRsyncCommand(),
966 967 968 969 970 971
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });

    testUsingContext('Do not display xcresult issues that needs to be discarded.', () async {
972 973 974 975
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
976
        logger: BufferLogger.test(),
977 978
        osUtils: FakeOperatingSystemUtils(),
      );
979

980
      createMinimalMockProjectFiles();
981 982 983 984 985 986 987 988 989 990 991 992 993 994

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--simulator', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.errorText, contains("Use of undeclared identifier 'asdas'"));
      expect(testLogger.errorText, contains('/Users/m/Projects/test_create/ios/Runner/AppDelegate.m:7:56'));
      expect(testLogger.errorText, isNot(contains('Command PhaseScriptExecution failed with a nonzero exit code')));
      expect(testLogger.warningText, isNot(contains("The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.0.99.")));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
995
        setUpFakeXcodeBuildHandler(
996 997 998 999 1000 1001
          simulator: true,
          exitCode: 1,
          onRun: () {
            fileSystem.systemTempDirectory.childDirectory(_xcBundleFilePath).createSync();
          },
        ),
1002 1003
        setUpXCResultCommand(stdout: kSampleResultJsonWithIssuesToBeDiscarded),
        setUpRsyncCommand(),
1004 1005 1006 1007 1008 1009
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });

    testUsingContext('Trace if xcresult bundle does not exist.', () async {
1010 1011 1012 1013
      final BuildCommand command = BuildCommand(
        androidSdk: FakeAndroidSdk(),
        buildSystem: TestBuildSystem.all(BuildResult(success: true)),
        fileSystem: MemoryFileSystem.test(),
1014
        logger: BufferLogger.test(),
1015 1016
        osUtils: FakeOperatingSystemUtils(),
      );
1017

1018
      createMinimalMockProjectFiles();
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029

      await expectLater(
        createTestCommandRunner(command).run(const <String>['build', 'ios', '--simulator', '--no-pub']),
        throwsToolExit(),
      );

      expect(testLogger.traceText, contains('The xcresult bundle are not generated. Displaying xcresult is disabled.'));
    }, overrides: <Type, Generator>{
      FileSystem: () => fileSystem,
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
        xattrCommand,
1030
        setUpFakeXcodeBuildHandler(
1031 1032 1033
          simulator: true,
          exitCode: 1,
        ),
1034 1035
        setUpXCResultCommand(stdout: kSampleResultJsonWithIssues),
        setUpRsyncCommand(),
1036 1037 1038 1039 1040
      ]),
      Platform: () => macosPlatform,
      XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(),
    });
  });
1041
}
1042 1043

const String _xcBundleFilePath = '/.tmp_rand0/flutter_ios_build_temp_dirrand0/temporary_xcresult_bundle';
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061

class FakeAndroidSdk extends Fake implements AndroidSdk {
  @override
  late bool platformToolsAvailable;

  @override
  late bool licensesAvailable;

  @override
  AndroidSdkVersion? latestVersion;
}

class FakeOperatingSystemUtils extends Fake implements OperatingSystemUtils {
  FakeOperatingSystemUtils({this.hostPlatform = HostPlatform.linux_x64});

  @override
  HostPlatform hostPlatform = HostPlatform.linux_x64;
}