build_linux_test.dart 27.2 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:args/command_runner.dart';
6
import 'package:file/memory.dart';
7
import 'package:file_testing/file_testing.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/os.dart';
11
import 'package:flutter_tools/src/base/platform.dart';
12
import 'package:flutter_tools/src/base/utils.dart';
13
import 'package:flutter_tools/src/build_system/build_system.dart';
14
import 'package:flutter_tools/src/cache.dart';
15
import 'package:flutter_tools/src/cmake.dart';
16
import 'package:flutter_tools/src/commands/build.dart';
17
import 'package:flutter_tools/src/commands/build_linux.dart';
18
import 'package:flutter_tools/src/features.dart';
19
import 'package:flutter_tools/src/project.dart';
20
import 'package:flutter_tools/src/reporting/reporting.dart';
21
import 'package:test/fake.dart';
22

23 24
import '../../src/common.dart';
import '../../src/context.dart';
25
import '../../src/fakes.dart';
26
import '../../src/test_build_system.dart';
27
import '../../src/test_flutter_command_runner.dart';
28

29 30
const String _kTestFlutterRoot = '/flutter';

31 32
final Platform linuxPlatform = FakePlatform(
  environment: <String, String>{
33 34
    'FLUTTER_ROOT': _kTestFlutterRoot,
    'HOME': '/',
35 36 37 38 39
  }
);
final Platform notLinuxPlatform = FakePlatform(
  operatingSystem: 'macos',
  environment: <String, String>{
40
    'FLUTTER_ROOT': _kTestFlutterRoot,
41 42 43 44
  }
);

void main() {
45 46
  setUpAll(() {
    Cache.disableLocking();
47
  });
48

49 50 51
  late FileSystem fileSystem;
  late ProcessManager processManager;
  late TestUsage usage;
52

53
  setUp(() {
54
    fileSystem = MemoryFileSystem.test();
55
    Cache.flutterRoot = _kTestFlutterRoot;
56
    usage = TestUsage();
57 58
  });

59 60
  // Creates the mock files necessary to look like a Flutter project.
  void setUpMockCoreProjectFiles() {
61 62 63
    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('.packages').createSync();
    fileSystem.file(fileSystem.path.join('lib', 'main.dart')).createSync(recursive: true);
64 65
  }

66
  // Creates the mock files necessary to run a build.
67
  void setUpMockProjectFilesForBuild() {
68
    setUpMockCoreProjectFiles();
69
    fileSystem.file(fileSystem.path.join('linux', 'CMakeLists.txt')).createSync(recursive: true);
70 71
  }

72
  // Returns the command matching the build_linux call to cmake.
73 74
  FakeCommand cmakeCommand(String buildMode, {
    String target = 'x64',
75
    void Function()? onRun,
76
  }) {
77 78 79 80 81
    return FakeCommand(
      command: <String>[
        'cmake',
        '-G',
        'Ninja',
82
        '-DCMAKE_BUILD_TYPE=${sentenceCase(buildMode)}',
83
        '-DFLUTTER_TARGET_PLATFORM=linux-$target',
84 85
        '/linux',
      ],
86
      workingDirectory: 'build/linux/$target/$buildMode',
87 88
      onRun: onRun,
    );
89 90
  }

91 92
  // Returns the command matching the build_linux call to ninja.
  FakeCommand ninjaCommand(String buildMode, {
93
    Map<String, String>? environment,
94
    String target = 'x64',
95
    void Function()? onRun,
96 97 98 99 100 101
    String stdout = '',
  }) {
    return FakeCommand(
      command: <String>[
        'ninja',
        '-C',
102
        'build/linux/$target/$buildMode',
103 104 105 106 107 108
        'install',
      ],
      environment: environment,
      onRun: onRun,
      stdout: stdout,
    );
109 110
  }

111
  testUsingContext('Linux build fails when there is no linux project', () async {
112 113 114 115 116 117 118
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
119
    setUpMockCoreProjectFiles();
120

121
    expect(createTestCommandRunner(command).run(
122
      const <String>['build', 'linux', '--no-pub']
123
    ), throwsToolExit(message: 'No Linux desktop project configured. See '
124
      'https://docs.flutter.dev/desktop#add-desktop-support-to-an-existing-flutter-app '
125
      'to learn about adding Linux support to a project.'));
126 127
  }, overrides: <Type, Generator>{
    Platform: () => linuxPlatform,
128
    FileSystem: () => fileSystem,
129
    ProcessManager: () => FakeProcessManager.any(),
130
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
131 132 133
  });

  testUsingContext('Linux build fails on non-linux platform', () async {
134 135 136 137 138 139 140
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
141
    setUpMockProjectFilesForBuild();
142 143

    expect(createTestCommandRunner(command).run(
144
      const <String>['build', 'linux', '--no-pub']
145
    ), throwsToolExit(message: '"build linux" only supported on Linux hosts.'));
146 147
  }, overrides: <Type, Generator>{
    Platform: () => notLinuxPlatform,
148
    FileSystem: () => fileSystem,
149
    ProcessManager: () => FakeProcessManager.any(),
150
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
151 152
  });

153
  testUsingContext('Linux build fails when feature is disabled', () async {
154 155 156 157 158 159 160
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
161 162 163 164 165 166 167 168 169
    setUpMockProjectFilesForBuild();

    expect(createTestCommandRunner(command).run(
        const <String>['build', 'linux', '--no-pub']
    ), throwsToolExit(message: '"build linux" is not currently supported. To enable, run "flutter config --enable-linux-desktop".'));
  }, overrides: <Type, Generator>{
    Platform: () => linuxPlatform,
    FileSystem: () => fileSystem,
    ProcessManager: () => FakeProcessManager.any(),
170
    FeatureFlags: () => TestFeatureFlags(),
171 172
  });

173
  testUsingContext('Linux build invokes CMake and ninja, and writes temporary files', () async {
174 175 176 177 178 179 180
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
181
    processManager = FakeProcessManager.list(<FakeCommand>[
182 183
      cmakeCommand('release'),
      ninjaCommand('release'),
184 185
    ]);

186
    setUpMockProjectFilesForBuild();
187 188

    await createTestCommandRunner(command).run(
189
      const <String>['build', 'linux', '--no-pub']
190
    );
191
    expect(fileSystem.file('linux/flutter/ephemeral/generated_config.cmake'), exists);
192
  }, overrides: <Type, Generator>{
193 194
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
195
    Platform: () => linuxPlatform,
196
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
197
    OperatingSystemUtils: () => FakeOperatingSystemUtils(),
198
  });
199

200
  testUsingContext('Handles missing cmake', () async {
201 202 203 204 205 206 207
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
208
    setUpMockProjectFilesForBuild();
209 210
    processManager = FakeProcessManager.empty()
        ..excludedExecutables.add('cmake');
211 212

    expect(createTestCommandRunner(command).run(
213
      const <String>['build', 'linux', '--no-pub']
214
    ), throwsToolExit(message: 'CMake is required for Linux development.'));
215 216 217 218 219
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
220
    OperatingSystemUtils: () => FakeOperatingSystemUtils(),
221 222 223
  });

  testUsingContext('Handles argument error from missing ninja', () async {
224 225 226 227 228 229 230
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
231 232
    setUpMockProjectFilesForBuild();
    processManager = FakeProcessManager.list(<FakeCommand>[
233 234
      cmakeCommand('release'),
      ninjaCommand('release', onRun: () {
235
        throw ArgumentError();
236 237 238 239 240 241
      }),
    ]);

    expect(createTestCommandRunner(command).run(
      const <String>['build', 'linux', '--no-pub']
    ), throwsToolExit(message: "ninja not found. Run 'flutter doctor' for more information."));
242
  }, overrides: <Type, Generator>{
243 244
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
245 246
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
247
    OperatingSystemUtils: () => FakeOperatingSystemUtils(),
248 249
  });

250
  testUsingContext('Linux build does not spew stdout to status logger', () async {
251 252 253 254 255 256 257
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
258
    setUpMockProjectFilesForBuild();
259
    processManager = FakeProcessManager.list(<FakeCommand>[
260 261 262 263
      cmakeCommand('debug'),
      ninjaCommand('debug',
        stdout: 'STDOUT STUFF',
      ),
264
    ]);
265 266

    await createTestCommandRunner(command).run(
267
      const <String>['build', 'linux', '--debug', '--no-pub']
268
    );
269
    expect(testLogger.statusText, isNot(contains('STDOUT STUFF')));
270 271
    expect(testLogger.warningText, isNot(contains('STDOUT STUFF')));
    expect(testLogger.errorText, isNot(contains('STDOUT STUFF')));
272
    expect(testLogger.traceText, contains('STDOUT STUFF'));
273
  }, overrides: <Type, Generator>{
274 275
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
276 277
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
278
    OperatingSystemUtils: () => FakeOperatingSystemUtils(),
279 280
  });

281
  testUsingContext('Linux build extracts errors from stdout', () async {
282 283 284 285 286 287 288
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
289 290 291 292 293
    setUpMockProjectFilesForBuild();

    // This contains a mix of routine build output and various types of errors
    // (Dart error, compile error, link error), edited down for compactness.
    const String stdout = r'''
294
ninja: Entering directory `build/linux/x64/release'
295 296 297 298 299 300 301
[1/6] Generating /foo/linux/flutter/ephemeral/libflutter_linux_gtk.so, /foo/linux/flutter/ephemeral/flutter_linux/flutter_linux.h, _phony
lib/main.dart:4:3: Error: Method not found: 'foo'.
[2/6] Building CXX object CMakeFiles/foo.dir/main.cc.o
/foo/linux/main.cc:6:2: error: expected ';' after class
/foo/linux/main.cc:9:7: warning: unused variable 'unused_variable' [-Wunused-variable]
/foo/linux/main.cc:10:3: error: unknown type name 'UnknownType'
/foo/linux/main.cc:12:7: error: 'bar' is a private member of 'Foo'
302
/foo/linux/my_application.h:4:10: fatal error: 'gtk/gtk.h' file not found
303 304 305 306 307 308
[3/6] Building CXX object CMakeFiles/foo_bar.dir/flutter/generated_plugin_registrant.cc.o
[4/6] Building CXX object CMakeFiles/foo_bar.dir/my_application.cc.o
[5/6] Linking CXX executable intermediates_do_not_run/foo_bar
main.cc:(.text+0x13): undefined reference to `Foo::bar()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.
309
ERROR: No file or variants found for asset: images/a_dot_burr.jpeg
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
''';

    processManager = FakeProcessManager.list(<FakeCommand>[
      cmakeCommand('release'),
      ninjaCommand('release',
        stdout: stdout,
      ),
    ]);

    await createTestCommandRunner(command).run(
      const <String>['build', 'linux', '--no-pub']
    );
    // Just the warnings and errors should be surfaced.
    expect(testLogger.errorText, r'''
lib/main.dart:4:3: Error: Method not found: 'foo'.
/foo/linux/main.cc:6:2: error: expected ';' after class
/foo/linux/main.cc:9:7: warning: unused variable 'unused_variable' [-Wunused-variable]
/foo/linux/main.cc:10:3: error: unknown type name 'UnknownType'
/foo/linux/main.cc:12:7: error: 'bar' is a private member of 'Foo'
329
/foo/linux/my_application.h:4:10: fatal error: 'gtk/gtk.h' file not found
330
clang: error: linker command failed with exit code 1 (use -v to see invocation)
331
ERROR: No file or variants found for asset: images/a_dot_burr.jpeg
332 333 334 335 336 337
''');
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
338
    OperatingSystemUtils: () => FakeOperatingSystemUtils(),
339 340
  });

341
  testUsingContext('Linux verbose build sets VERBOSE_SCRIPT_LOGGING', () async {
342 343 344 345 346 347 348
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
349 350
    setUpMockProjectFilesForBuild();
    processManager = FakeProcessManager.list(<FakeCommand>[
351 352
      cmakeCommand('debug'),
      ninjaCommand('debug',
353
        environment: const <String, String>{
354
          'VERBOSE_SCRIPT_LOGGING': 'true',
355 356 357 358 359 360 361 362 363 364
        },
        stdout: 'STDOUT STUFF',
      ),
    ]);

    await createTestCommandRunner(command).run(
      const <String>['build', 'linux', '--debug', '-v', '--no-pub']
    );
    expect(testLogger.statusText, contains('STDOUT STUFF'));
    expect(testLogger.traceText, isNot(contains('STDOUT STUFF')));
365 366
    expect(testLogger.warningText, isNot(contains('STDOUT STUFF')));
    expect(testLogger.errorText, isNot(contains('STDOUT STUFF')));
367 368 369 370 371
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
372
    OperatingSystemUtils: () => FakeOperatingSystemUtils(),
373 374
  });

375
  testUsingContext('Linux on x64 build --debug passes debug mode to cmake and ninja', () async {
376 377 378 379 380 381 382
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
383
    setUpMockProjectFilesForBuild();
384
    processManager = FakeProcessManager.list(<FakeCommand>[
385 386
      cmakeCommand('debug'),
      ninjaCommand('debug'),
387 388
    ]);

389 390 391 392 393 394 395 396 397 398 399 400
    await createTestCommandRunner(command).run(
      const <String>['build', 'linux', '--debug', '--no-pub']
    );
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
    OperatingSystemUtils: () => FakeOperatingSystemUtils(),
  });

  testUsingContext('Linux on ARM64 build --debug passes debug mode to cmake and ninja', () async {
401 402 403 404 405 406 407
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: CustomFakeOperatingSystemUtils(hostPlatform: HostPlatform.linux_arm64),
    );
408 409 410 411 412
    setUpMockProjectFilesForBuild();
    processManager = FakeProcessManager.list(<FakeCommand>[
      cmakeCommand('debug', target: 'arm64'),
      ninjaCommand('debug', target: 'arm64'),
    ]);
413 414

    await createTestCommandRunner(command).run(
415
      const <String>['build', 'linux', '--debug', '--no-pub']
416 417
    );
  }, overrides: <Type, Generator>{
418 419
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
420 421 422 423
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
  });

424
  testUsingContext('Linux on x64 build --profile passes profile mode to make', () async {
425 426 427 428 429 430 431
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
432
    setUpMockProjectFilesForBuild();
433
    processManager = FakeProcessManager.list(<FakeCommand>[
434 435
      cmakeCommand('profile'),
      ninjaCommand('profile'),
436
    ]);
437 438

    await createTestCommandRunner(command).run(
439
      const <String>['build', 'linux', '--profile', '--no-pub']
440 441
    );
  }, overrides: <Type, Generator>{
442 443
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
444 445
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
446 447 448 449
    OperatingSystemUtils: () => FakeOperatingSystemUtils(),
  });

  testUsingContext('Linux on ARM64 build --profile passes profile mode to make', () async {
450 451 452 453 454 455 456
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: CustomFakeOperatingSystemUtils(hostPlatform: HostPlatform.linux_arm64),
    );
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
    setUpMockProjectFilesForBuild();
    processManager = FakeProcessManager.list(<FakeCommand>[
      cmakeCommand('profile', target: 'arm64'),
      ninjaCommand('profile', target: 'arm64'),
    ]);

    await createTestCommandRunner(command).run(
      const <String>['build', 'linux', '--profile', '--no-pub']
    );
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
  });

  testUsingContext('Not support Linux cross-build for x64 on arm64', () async {
474 475 476 477 478 479 480
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: CustomFakeOperatingSystemUtils(hostPlatform: HostPlatform.linux_arm64),
    );
481 482 483 484 485 486 487

    expect(createTestCommandRunner(command).run(
      const <String>['build', 'linux', '--no-pub', '--target-platform=linux-x64']
    ), throwsToolExit());
  }, overrides: <Type, Generator>{
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
488 489
  });

490
  testUsingContext('Linux build configures CMake exports', () async {
491 492 493 494 495 496 497
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
498 499
    setUpMockProjectFilesForBuild();
    processManager = FakeProcessManager.list(<FakeCommand>[
500 501
      cmakeCommand('release'),
      ninjaCommand('release'),
502 503 504
    ]);
    fileSystem.file('lib/other.dart')
      .createSync(recursive: true);
505 506
    fileSystem.file('foo/bar.sksl.json')
      .createSync(recursive: true);
507 508 509 510 511 512 513 514 515 516 517 518 519 520

    await createTestCommandRunner(command).run(
      const <String>[
        'build',
        'linux',
        '--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',
521
        '--bundle-sksl-path=foo/bar.sksl.json',
522 523 524
      ]
    );

525
    final File cmakeConfig = fileSystem.currentDirectory
526 527 528
      .childDirectory('linux')
      .childDirectory('flutter')
      .childDirectory('ephemeral')
529
      .childFile('generated_config.cmake');
530

531
    expect(cmakeConfig, exists);
532

533
    final List<String> configLines = cmakeConfig.readAsLinesSync();
534 535

    expect(configLines, containsAll(<String>[
536 537
      'file(TO_CMAKE_PATH "$_kTestFlutterRoot" FLUTTER_ROOT)',
      'file(TO_CMAKE_PATH "${fileSystem.currentDirectory.path}" PROJECT_DIR)',
538 539 540 541 542
      'set(FLUTTER_VERSION "1.0.0" PARENT_SCOPE)',
      'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)',
      'set(FLUTTER_VERSION_MINOR 0 PARENT_SCOPE)',
      'set(FLUTTER_VERSION_PATCH 0 PARENT_SCOPE)',
      'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)',
543
      '  "DART_DEFINES=Zm9vLmJhcj0y,Zml6ei5mYXI9Mw=="',
544
      '  "DART_OBFUSCATION=true"',
545 546
      '  "EXTRA_FRONT_END_OPTIONS=--enable-experiment=non-nullable"',
      '  "EXTRA_GEN_SNAPSHOT_OPTIONS=--enable-experiment=non-nullable"',
547 548 549 550 551 552 553
      '  "SPLIT_DEBUG_INFO=foo/"',
      '  "TRACK_WIDGET_CREATION=true"',
      '  "TREE_SHAKE_ICONS=true"',
      '  "FLUTTER_ROOT=$_kTestFlutterRoot"',
      '  "PROJECT_DIR=${fileSystem.currentDirectory.path}"',
      '  "FLUTTER_TARGET=lib/other.dart"',
      '  "BUNDLE_SKSL_PATH=foo/bar.sksl.json"',
554 555 556 557 558 559
    ]));
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
560
    OperatingSystemUtils: () => FakeOperatingSystemUtils(),
561 562
  });

563 564
  testUsingContext('linux can extract binary name from CMake file', () async {
    fileSystem.file('linux/CMakeLists.txt')
565 566
      ..createSync(recursive: true)
      ..writeAsStringSync(r'''
567 568
cmake_minimum_required(VERSION 3.10)
project(runner LANGUAGES CXX)
569

570
set(BINARY_NAME "fizz_bar")
571
''');
572 573
    fileSystem.file('pubspec.yaml').createSync();
    fileSystem.file('.packages').createSync();
574
    final FlutterProject flutterProject = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory);
575

576
    expect(getCmakeExecutableName(flutterProject.linux), 'fizz_bar');
577
  }, overrides: <Type, Generator>{
578
    FileSystem: () => fileSystem,
579
    ProcessManager: () => FakeProcessManager.any(),
580 581 582 583
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
  });

  testUsingContext('Refuses to build for Linux when feature is disabled', () {
584 585 586 587 588 589 590
    final CommandRunner<void> runner = createTestCommandRunner(BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    ));
591

592
    expect(() => runner.run(<String>['build', 'linux', '--no-pub']),
593
      throwsToolExit());
594
  }, overrides: <Type, Generator>{
595
    FeatureFlags: () => TestFeatureFlags(),
596
  });
597

598
  testUsingContext('hidden when not enabled on Linux host', () {
599
    expect(BuildLinuxCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()).hidden, true);
600
  }, overrides: <Type, Generator>{
601
    FeatureFlags: () => TestFeatureFlags(),
602
    Platform: () => notLinuxPlatform,
603 604 605
  });

  testUsingContext('Not hidden when enabled and on Linux host', () {
606
    expect(BuildLinuxCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()).hidden, false);
607 608
  }, overrides: <Type, Generator>{
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
609
    Platform: () => linuxPlatform,
610
  });
611 612

  testUsingContext('Performs code size analysis and sends analytics', () async {
613 614 615 616 617 618 619
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
620 621 622 623 624 625
    setUpMockProjectFilesForBuild();
    processManager = FakeProcessManager.list(<FakeCommand>[
      cmakeCommand('release'),
      ninjaCommand('release', onRun: () {
        fileSystem.file('build/flutter_size_01/snapshot.linux-x64.json')
          ..createSync(recursive: true)
626 627 628 629 630 631 632 633 634
          ..writeAsStringSync('''
[
  {
    "l": "dart:_internal",
    "c": "SubListIterable",
    "n": "[Optimized] skip",
    "s": 2400
  }
]''');
635 636 637 638 639 640
        fileSystem.file('build/flutter_size_01/trace.linux-x64.json')
          ..createSync(recursive: true)
          ..writeAsStringSync('{}');
      }),
    ]);

641
    fileSystem.file('build/linux/x64/release/bundle/libapp.so')
642 643 644
      ..createSync(recursive: true)
      ..writeAsBytesSync(List<int>.filled(10000, 0));

645 646
    await createTestCommandRunner(command).run(
      const <String>['build', 'linux', '--no-pub', '--analyze-size']
647
    );
648

649
    expect(testLogger.statusText, contains('A summary of your Linux bundle analysis can be found at'));
650
    expect(testLogger.statusText, contains('flutter pub global activate devtools; flutter pub global run devtools --appSizeBase='));
651 652 653
    expect(usage.events, contains(
      const TestUsageEvent('code-size-analysis', 'linux'),
    ));
654 655 656 657 658 659
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
    Usage: () => usage,
660
    OperatingSystemUtils: () => FakeOperatingSystemUtils(),
661
  });
662 663

  testUsingContext('Linux on ARM64 build --release passes, and check if the LinuxBuildDirectory for arm64 can be referenced correctly by using analytics', () async {
664 665 666 667 668 669 670
    final BuildCommand command = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
      logger: BufferLogger.test(),
      osUtils: CustomFakeOperatingSystemUtils(hostPlatform: HostPlatform.linux_arm64),
    );
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
    setUpMockProjectFilesForBuild();
    processManager = FakeProcessManager.list(<FakeCommand>[
      cmakeCommand('release', target: 'arm64'),
      ninjaCommand('release', target: 'arm64', onRun: () {
        fileSystem.file('build/flutter_size_01/snapshot.linux-arm64.json')
          ..createSync(recursive: true)
          ..writeAsStringSync('''
[
  {
    "l": "dart:_internal",
    "c": "SubListIterable",
    "n": "[Optimized] skip",
    "s": 2400
  }
]''');
        fileSystem.file('build/flutter_size_01/trace.linux-arm64.json')
          ..createSync(recursive: true)
          ..writeAsStringSync('{}');
      }),
    ]);

    fileSystem.file('build/linux/arm64/release/bundle/libapp.so')
      ..createSync(recursive: true)
      ..writeAsBytesSync(List<int>.filled(10000, 0));

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

    // check if libapp.so of "build/linux/arm64/release" directory can be referenced.
    expect(testLogger.statusText,  contains('libapp.so (Dart AOT)'));
    expect(usage.events, contains(
      const TestUsageEvent('code-size-analysis', 'linux'),
    ));
  }, overrides: <Type, Generator>{
    FileSystem: () => fileSystem,
    ProcessManager: () => processManager,
    Platform: () => linuxPlatform,
    FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true),
    Usage: () => usage,
    OperatingSystemUtils: () => CustomFakeOperatingSystemUtils(hostPlatform: HostPlatform.linux_arm64),
  });
}

class CustomFakeOperatingSystemUtils extends Fake implements OperatingSystemUtils {
  CustomFakeOperatingSystemUtils({
    HostPlatform hostPlatform = HostPlatform.linux_x64
  })  : _hostPlatform = hostPlatform;

  final HostPlatform _hostPlatform;

  @override
  String get name => 'Linux';

  @override
  HostPlatform get hostPlatform => _hostPlatform;

  @override
  List<File> whichAll(String execName) => <File>[];
730
}