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

5 6
import 'dart:async';

7
import 'package:args/command_runner.dart';
8 9
import 'package:file/memory.dart';
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/platform.dart';
12
import 'package:flutter_tools/src/build_info.dart';
13 14
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/build.dart';
15
import 'package:flutter_tools/src/commands/build_macos.dart';
16
import 'package:flutter_tools/src/features.dart';
17
import 'package:flutter_tools/src/ios/xcodeproj.dart';
18
import 'package:flutter_tools/src/project.dart';
19
import 'package:flutter_tools/src/reporting/reporting.dart';
20 21
import 'package:process/process.dart';

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

26 27
class FakeXcodeProjectInterpreterWithProfile extends FakeXcodeProjectInterpreter {
  @override
28
  Future<XcodeProjectInfo> getInfo(String projectPath, {String projectFilename}) async {
29 30 31 32
    return XcodeProjectInfo(
      <String>['Runner'],
      <String>['Debug', 'Profile', 'Release'],
      <String>['Runner'],
33
      BufferLogger.test(),
34 35 36 37
    );
  }
}

38 39 40 41 42 43 44 45 46 47 48 49 50
final Platform macosPlatform = FakePlatform(
  operatingSystem: 'macos',
  environment: <String, String>{
    'FLUTTER_ROOT': '/',
  }
);
final Platform notMacosPlatform = FakePlatform(
  operatingSystem: 'linux',
  environment: <String, String>{
    'FLUTTER_ROOT': '/',
  }
);

51
void main() {
52
  FileSystem fileSystem;
53
  Usage usage;
54

55 56
  setUpAll(() {
    Cache.disableLocking();
57
  });
58 59

  setUp(() {
60
    fileSystem = MemoryFileSystem.test();
61
    usage = Usage.test();
62
  });
63

64 65
  // Sets up the minimal mock project files necessary to look like a Flutter project.
  void createCoreMockProjectFiles() {
66 67 68
    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('.packages').createSync();
    fileSystem.file(fileSystem.path.join('lib', 'main.dart')).createSync(recursive: true);
69 70
  }

71 72
  // Sets up the minimal mock project files necessary for macOS builds to succeed.
  void createMinimalMockProjectFiles() {
73
    fileSystem.directory(fileSystem.path.join('macos', 'Runner.xcworkspace')).createSync(recursive: true);
74 75 76
    createCoreMockProjectFiles();
  }

77
  // Creates a FakeCommand for the xcodebuild call to build the app
78
  // in the given configuration.
79
  FakeCommand setUpMockXcodeBuildHandler(String configuration, { bool verbose = false, void Function() onRun }) {
80 81 82 83 84 85 86 87 88 89 90 91 92
    final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory);
    final Directory flutterBuildDir = fileSystem.directory(getMacOSBuildDirectory());
    return FakeCommand(
      command: <String>[
        '/usr/bin/env',
        'xcrun',
        'xcodebuild',
        '-workspace', flutterProject.macos.xcodeWorkspace.path,
        '-configuration', configuration,
        '-scheme', 'Runner',
        '-derivedDataPath', flutterBuildDir.absolute.path,
        'OBJROOT=${fileSystem.path.join(flutterBuildDir.absolute.path, 'Build', 'Intermediates.noindex')}',
        'SYMROOT=${fileSystem.path.join(flutterBuildDir.absolute.path, 'Build', 'Products')}',
93
        if (verbose)
94 95 96
          'VERBOSE_SCRIPT_LOGGING=YES'
        else
          '-quiet',
97 98 99 100 101 102 103
        'COMPILER_INDEX_STORE_ENABLE=NO',
      ],
      stdout: 'STDOUT STUFF',
      onRun: () {
        fileSystem.file(fileSystem.path.join('macos', 'Flutter', 'ephemeral', '.app_filename'))
          ..createSync(recursive: true)
          ..writeAsStringSync('example.app');
104 105 106
        if (onRun != null) {
          onRun();
        }
107 108
      }
    );
109 110
  }

111 112
  testUsingContext('macOS build fails when there is no macos project', () async {
    final BuildCommand command = BuildCommand();
113
    createCoreMockProjectFiles();
114

115
    expect(createTestCommandRunner(command).run(
116
      const <String>['build', 'macos', '--no-pub']
117
    ), throwsToolExit(message: 'No macOS desktop project configured'));
118 119
  }, overrides: <Type, Generator>{
    Platform: () => macosPlatform,
120
    FileSystem: () => fileSystem,
121
    ProcessManager: () => FakeProcessManager.any(),
122
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
123 124 125 126
  });

  testUsingContext('macOS build fails on non-macOS platform', () async {
    final BuildCommand command = BuildCommand();
127 128 129 130
    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('.packages').createSync();
    fileSystem.file(fileSystem.path.join('lib', 'main.dart'))
      .createSync(recursive: true);
131 132

    expect(createTestCommandRunner(command).run(
133
      const <String>['build', 'macos', '--no-pub']
Dan Field's avatar
Dan Field committed
134
    ), throwsToolExit());
135 136
  }, overrides: <Type, Generator>{
    Platform: () => notMacosPlatform,
137
    FileSystem: () => fileSystem,
138
    ProcessManager: () => FakeProcessManager.any(),
139
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
140 141
  });

142
  testUsingContext('macOS build forwards error stdout to status logger error', () async {
143 144 145 146
    final BuildCommand command = BuildCommand();
    createMinimalMockProjectFiles();

    await createTestCommandRunner(command).run(
147
      const <String>['build', 'macos', '--debug', '--no-pub']
148
    );
149
    expect(testLogger.statusText, isNot(contains('STDOUT STUFF')));
150 151
    expect(testLogger.traceText, isNot(contains('STDOUT STUFF')));
    expect(testLogger.errorText, contains('STDOUT STUFF'));
152
  }, overrides: <Type, Generator>{
153 154 155 156
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      setUpMockXcodeBuildHandler('Debug')
    ]),
157 158
    Platform: () => macosPlatform,
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
159 160
  });

161
  testUsingContext('macOS build invokes xcode build (debug)', () async {
162
    final BuildCommand command = BuildCommand();
163 164 165
    createMinimalMockProjectFiles();

    await createTestCommandRunner(command).run(
166
      const <String>['build', 'macos', '--debug', '--no-pub']
167 168
    );
  }, overrides: <Type, Generator>{
169 170 171 172
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      setUpMockXcodeBuildHandler('Debug')
    ]),
173 174 175 176
    Platform: () => macosPlatform,
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
  });

177 178 179 180 181
  testUsingContext('macOS build invokes xcode build (debug) with verbosity', () async {
    final BuildCommand command = BuildCommand();
    createMinimalMockProjectFiles();

    await createTestCommandRunner(command).run(
182
      const <String>['build', 'macos', '--debug', '--no-pub', '-v']
183 184 185 186 187 188 189 190 191 192 193
    );
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      setUpMockXcodeBuildHandler('Debug', verbose: true)
    ]),
    Platform: () => macosPlatform,
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
  });


194 195 196 197 198
  testUsingContext('macOS build invokes xcode build (profile)', () async {
    final BuildCommand command = BuildCommand();
    createMinimalMockProjectFiles();

    await createTestCommandRunner(command).run(
199
      const <String>['build', 'macos', '--profile', '--no-pub']
200 201
    );
  }, overrides: <Type, Generator>{
202 203 204 205
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      setUpMockXcodeBuildHandler('Profile')
    ]),
206 207 208 209 210 211 212 213
    Platform: () => macosPlatform,
    XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithProfile(),
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
  });

  testUsingContext('macOS build invokes xcode build (release)', () async {
    final BuildCommand command = BuildCommand();
    createMinimalMockProjectFiles();
214

215
    await createTestCommandRunner(command).run(
216
      const <String>['build', 'macos', '--release', '--no-pub']
217
    );
218
  }, overrides: <Type, Generator>{
219 220 221 222
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      setUpMockXcodeBuildHandler('Release')
    ]),
223
    Platform: () => macosPlatform,
224 225 226
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
  });

227 228 229 230 231
  testUsingContext('macOS build supports standard desktop build options', () async {
    final BuildCommand command = BuildCommand();
    createMinimalMockProjectFiles();
    fileSystem.file('lib/other.dart')
      .createSync(recursive: true);
232 233
    fileSystem.file('foo/bar.sksl.json')
      .createSync(recursive: true);
234 235 236 237 238 239 240 241 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

    await createTestCommandRunner(command).run(
      const <String>[
        'build',
        'macos',
        '--target=lib/other.dart',
        '--no-pub',
        '--track-widget-creation',
        '--split-debug-info=foo/',
        '--enable-experiment=non-nullable',
        '--obfuscate',
        '--dart-define=foo.bar=2',
        '--dart-define=fizz.far=3',
        '--tree-shake-icons',
        '--bundle-sksl-path=foo/bar.sksl.json',
      ]
    );
    final List<String> contents = fileSystem
      .file('./macos/Flutter/ephemeral/Flutter-Generated.xcconfig')
      .readAsLinesSync();

    expect(contents, containsAll(<String>[
      'DART_DEFINES=foo.bar%3D2,fizz.far%3D3',
      'DART_OBFUSCATION=true',
      'EXTRA_FRONT_END_OPTIONS=--enable-experiment%3Dnon-nullable',
      'EXTRA_GEN_SNAPSHOT_OPTIONS=--enable-experiment%3Dnon-nullable',
      'SPLIT_DEBUG_INFO=foo/',
      'TRACK_WIDGET_CREATION=true',
      'TREE_SHAKE_ICONS=true',
      'FLUTTER_TARGET=lib/other.dart',
      'BUNDLE_SKSL_PATH=foo/bar.sksl.json',
    ]));
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      setUpMockXcodeBuildHandler('Release')
    ]),
    Platform: () => macosPlatform,
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
  });

275 276 277 278 279 280 281 282 283
  testUsingContext('macOS build supports build-name and build-number', () async {
    final BuildCommand command = BuildCommand();
    createMinimalMockProjectFiles();

    await createTestCommandRunner(command).run(
      const <String>[
        'build',
        'macos',
        '--debug',
284
        '--no-pub',
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
        '--build-name=1.2.3',
        '--build-number=42',
      ],
    );
    final String contents = fileSystem
      .file('./macos/Flutter/ephemeral/Flutter-Generated.xcconfig')
      .readAsStringSync();

    expect(contents, contains('FLUTTER_BUILD_NAME=1.2.3'));
    expect(contents, contains('FLUTTER_BUILD_NUMBER=42'));
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      setUpMockXcodeBuildHandler('Debug')
    ]),
    Platform: () => macosPlatform,
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
  });

304 305 306
  testUsingContext('Refuses to build for macOS when feature is disabled', () {
    final CommandRunner<void> runner = createTestCommandRunner(BuildCommand());

307
    expect(() => runner.run(<String>['build', 'macos', '--no-pub']),
308
      throwsToolExit());
309 310
  }, overrides: <Type, Generator>{
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: false),
311
  });
312 313

  testUsingContext('hidden when not enabled on macOS host', () {
314
    expect(BuildMacosCommand(verboseHelp: false).hidden, true);
315 316
  }, overrides: <Type, Generator>{
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: false),
317
    Platform: () => macosPlatform,
318 319 320
  });

  testUsingContext('Not hidden when enabled and on macOS host', () {
321
    expect(BuildMacosCommand(verboseHelp: false).hidden, false);
322 323
  }, overrides: <Type, Generator>{
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
324
    Platform: () => macosPlatform,
325
  });
326 327 328 329 330 331 332 333 334

  testUsingContext('Performs code size analysis and sends analytics', () async {
    final BuildCommand command = BuildCommand();
    createMinimalMockProjectFiles();

    fileSystem.file('build/macos/Build/Products/Release/Runner.app/App')
      ..createSync(recursive: true)
      ..writeAsBytesSync(List<int>.generate(10000, (int index) => 0));

335 336 337 338 339
    // Capture Usage.test() events.
    final StringBuffer buffer = await capturedConsolePrint(() =>
      createTestCommandRunner(command).run(
        const <String>['build', 'macos', '--no-pub', '--analyze-size']
      )
340 341 342
    );

    expect(testLogger.statusText, contains('A summary of your macOS bundle analysis can be found at'));
343
    expect(buffer.toString(), contains('event {category: code-size-analysis, action: macos, label: null, value: null, cd33:'));
344 345 346 347 348 349
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
      setUpMockXcodeBuildHandler('Release', onRun: () {
        fileSystem.file('build/flutter_size_01/snapshot.x86_64.json')
          ..createSync(recursive: true)
350 351 352 353 354 355 356 357 358
          ..writeAsStringSync('''
[
  {
    "l": "dart:_internal",
    "c": "SubListIterable",
    "n": "[Optimized] skip",
    "s": 2400
  }
]''');
359 360 361 362 363 364 365 366 367 368 369
        fileSystem.file('build/flutter_size_01/trace.x86_64.json')
          ..createSync(recursive: true)
          ..writeAsStringSync('{}');
      }),
    ]),
    Platform: () => macosPlatform,
    FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
    FileSystemUtils: () => FileSystemUtils(fileSystem: fileSystem, platform: macosPlatform),
    Usage: () => usage,
  });
}