gradle_test.dart 93 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:archive/archive.dart';
8
import 'package:file/memory.dart';
9 10
import 'package:flutter_tools/src/android/android_sdk.dart';
import 'package:flutter_tools/src/android/android_studio.dart';
11
import 'package:flutter_tools/src/android/gradle.dart';
12
import 'package:flutter_tools/src/android/gradle_errors.dart';
13
import 'package:flutter_tools/src/android/gradle_utils.dart';
14
import 'package:flutter_tools/src/artifacts.dart';
15
import 'package:flutter_tools/src/base/common.dart';
16
import 'package:flutter_tools/src/base/context.dart';
17
import 'package:flutter_tools/src/base/file_system.dart';
Emmanuel Garcia's avatar
Emmanuel Garcia committed
18
import 'package:flutter_tools/src/base/io.dart';
19
import 'package:flutter_tools/src/base/logger.dart';
20
import 'package:flutter_tools/src/base/platform.dart';
21
import 'package:flutter_tools/src/base/terminal.dart';
22
import 'package:flutter_tools/src/build_info.dart';
23
import 'package:flutter_tools/src/cache.dart';
24
import 'package:flutter_tools/src/globals.dart' as globals;
25
import 'package:flutter_tools/src/ios/xcodeproj.dart';
26
import 'package:flutter_tools/src/project.dart';
27
import 'package:flutter_tools/src/reporting/reporting.dart';
28 29
import 'package:mockito/mockito.dart';
import 'package:process/process.dart';
30

31 32
import '../../src/common.dart';
import '../../src/context.dart';
33
import '../../src/mocks.dart';
34
import '../../src/pubspec_schema.dart';
35

36
void main() {
37
  Cache.flutterRoot = getFlutterRoot();
38 39

  group('build artifacts', () {
40 41 42 43 44 45 46
    FileSystem fileSystem;

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

    testWithoutContext('getApkDirectory in app projects', () {
47 48 49 50
      final FlutterProject project = MockFlutterProject();
      final AndroidProject androidProject = MockAndroidProject();
      when(project.android).thenReturn(androidProject);
      when(project.isModule).thenReturn(false);
51
      when(androidProject.buildDirectory).thenReturn(fileSystem.directory('foo'));
52 53 54

      expect(
        getApkDirectory(project).path,
55
        equals(fileSystem.path.join('foo', 'app', 'outputs', 'flutter-apk')),
56
      );
57 58
    });

59
    testWithoutContext('getApkDirectory in module projects', () {
60 61 62 63
      final FlutterProject project = MockFlutterProject();
      final AndroidProject androidProject = MockAndroidProject();
      when(project.android).thenReturn(androidProject);
      when(project.isModule).thenReturn(true);
64
      when(androidProject.buildDirectory).thenReturn(fileSystem.directory('foo'));
65

66 67
      expect(
        getApkDirectory(project).path,
68
        equals(fileSystem.path.join('foo', 'host', 'outputs', 'apk')),
69
      );
70 71
    });

72
    testWithoutContext('getBundleDirectory in app projects', () {
73 74 75 76
      final FlutterProject project = MockFlutterProject();
      final AndroidProject androidProject = MockAndroidProject();
      when(project.android).thenReturn(androidProject);
      when(project.isModule).thenReturn(false);
77
      when(androidProject.buildDirectory).thenReturn(fileSystem.directory('foo'));
78 79 80

      expect(
        getBundleDirectory(project).path,
81
        equals(fileSystem.path.join('foo', 'app', 'outputs', 'bundle')),
82
      );
83 84
    });

85
    testWithoutContext('getBundleDirectory in module projects', () {
86 87 88 89
      final FlutterProject project = MockFlutterProject();
      final AndroidProject androidProject = MockAndroidProject();
      when(project.android).thenReturn(androidProject);
      when(project.isModule).thenReturn(true);
90
      when(androidProject.buildDirectory).thenReturn(fileSystem.directory('foo'));
91 92 93

      expect(
        getBundleDirectory(project).path,
94
        equals(fileSystem.path.join('foo', 'host', 'outputs', 'bundle')),
95
      );
96 97
    });

98
    testWithoutContext('getRepoDirectory', () {
99
      expect(
100 101
        getRepoDirectory(fileSystem.directory('foo')).path,
        equals(fileSystem.path.join('foo','outputs', 'repo')),
102 103 104 105 106
      );
    });
  });

  group('gradle tasks', () {
107
    testWithoutContext('assemble release', () {
108
      expect(
109
        getAssembleTaskFor(const BuildInfo(BuildMode.release, null, treeShakeIcons: false)),
110 111 112
        equals('assembleRelease'),
      );
      expect(
113
        getAssembleTaskFor(const BuildInfo(BuildMode.release, 'flavorFoo', treeShakeIcons: false)),
114 115 116 117
        equals('assembleFlavorFooRelease'),
      );
    });

118
    testWithoutContext('assemble debug', () {
119
      expect(
120
        getAssembleTaskFor(const BuildInfo(BuildMode.debug, null, treeShakeIcons: false)),
121 122 123
        equals('assembleDebug'),
      );
      expect(
124
        getAssembleTaskFor(const BuildInfo(BuildMode.debug, 'flavorFoo', treeShakeIcons: false)),
125 126
        equals('assembleFlavorFooDebug'),
      );
127
    });
128

129
    testWithoutContext('assemble profile', () {
130
      expect(
131
        getAssembleTaskFor(const BuildInfo(BuildMode.profile, null, treeShakeIcons: false)),
132 133 134
        equals('assembleProfile'),
      );
      expect(
135
        getAssembleTaskFor(const BuildInfo(BuildMode.profile, 'flavorFoo', treeShakeIcons: false)),
136 137 138 139 140 141
        equals('assembleFlavorFooProfile'),
      );
    });
  });

  group('findBundleFile', () {
142 143
    FileSystem fileSystem;
    Usage mockUsage;
144

145 146 147 148 149 150 151
    setUp(() {
      fileSystem = MemoryFileSystem.test();
      mockUsage = MockUsage();
    });

    testWithoutContext('Finds app bundle when flavor contains underscores in release mode', () {
      final FlutterProject project = generateFakeAppBundle('foo_barRelease', 'app.aab', fileSystem);
152
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.release, 'foo_bar', treeShakeIcons: false));
153
      expect(bundle, isNotNull);
154
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'foo_barRelease', 'app.aab'));
155 156
    });

157 158
    testWithoutContext("Finds app bundle when flavor doesn't contain underscores in release mode", () {
      final FlutterProject project = generateFakeAppBundle('fooRelease', 'app.aab', fileSystem);
159
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.release, 'foo', treeShakeIcons: false));
160
      expect(bundle, isNotNull);
161
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'fooRelease', 'app.aab'));
162 163
    });

164 165
    testWithoutContext('Finds app bundle when no flavor is used in release mode', () {
      final FlutterProject project = generateFakeAppBundle('release', 'app.aab', fileSystem);
166
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.release, null, treeShakeIcons: false));
167
      expect(bundle, isNotNull);
168
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'release', 'app.aab'));
169 170
    });

171 172
    testWithoutContext('Finds app bundle when flavor contains underscores in debug mode', () {
      final FlutterProject project = generateFakeAppBundle('foo_barDebug', 'app.aab', fileSystem);
173
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.debug, 'foo_bar', treeShakeIcons: false));
174
      expect(bundle, isNotNull);
175
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'foo_barDebug', 'app.aab'));
176 177
    });

178 179
    testWithoutContext("Finds app bundle when flavor doesn't contain underscores in debug mode", () {
      final FlutterProject project = generateFakeAppBundle('fooDebug', 'app.aab', fileSystem);
180
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.debug, 'foo', treeShakeIcons: false));
181
      expect(bundle, isNotNull);
182
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'fooDebug', 'app.aab'));
183 184
    });

185 186
    testWithoutContext('Finds app bundle when no flavor is used in debug mode', () {
      final FlutterProject project = generateFakeAppBundle('debug', 'app.aab', fileSystem);
187
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.debug, null, treeShakeIcons: false));
188
      expect(bundle, isNotNull);
189
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'debug', 'app.aab'));
190 191
    });

192 193
    testWithoutContext('Finds app bundle when flavor contains underscores in profile mode', () {
      final FlutterProject project = generateFakeAppBundle('foo_barProfile', 'app.aab', fileSystem);
194
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.profile, 'foo_bar', treeShakeIcons: false));
195
      expect(bundle, isNotNull);
196
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'foo_barProfile', 'app.aab'));
197 198
    });

199 200
    testWithoutContext("Finds app bundle when flavor doesn't contain underscores in profile mode", () {
      final FlutterProject project = generateFakeAppBundle('fooProfile', 'app.aab', fileSystem);
201
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.profile, 'foo', treeShakeIcons: false));
202
      expect(bundle, isNotNull);
203
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'fooProfile', 'app.aab'));
204 205
    });

206 207
    testWithoutContext('Finds app bundle when no flavor is used in profile mode', () {
      final FlutterProject project = generateFakeAppBundle('profile', 'app.aab', fileSystem);
208
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.profile, null, treeShakeIcons: false));
209
      expect(bundle, isNotNull);
210
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'profile', 'app.aab'));
211
    });
212

213 214
    testWithoutContext('Finds app bundle in release mode - Gradle 3.5', () {
      final FlutterProject project = generateFakeAppBundle('release', 'app-release.aab', fileSystem);
215
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.release, null, treeShakeIcons: false));
216
      expect(bundle, isNotNull);
217
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'release', 'app-release.aab'));
218
    });
219

220 221
    testWithoutContext('Finds app bundle in profile mode - Gradle 3.5', () {
      final FlutterProject project = generateFakeAppBundle('profile', 'app-profile.aab', fileSystem);
222
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.profile, null, treeShakeIcons: false));
223
      expect(bundle, isNotNull);
224
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'profile', 'app-profile.aab'));
225 226
    });

227 228
    testWithoutContext('Finds app bundle in debug mode - Gradle 3.5', () {
      final FlutterProject project = generateFakeAppBundle('debug', 'app-debug.aab', fileSystem);
229
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.debug, null, treeShakeIcons: false));
230
      expect(bundle, isNotNull);
231
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'debug', 'app-debug.aab'));
232 233
    });

234 235
    testWithoutContext('Finds app bundle when flavor contains underscores in release mode - Gradle 3.5', () {
      final FlutterProject project = generateFakeAppBundle('foo_barRelease', 'app-foo_bar-release.aab', fileSystem);
236
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.release, 'foo_bar', treeShakeIcons: false));
237
      expect(bundle, isNotNull);
238
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'foo_barRelease', 'app-foo_bar-release.aab'));
239 240
    });

241 242
    testWithoutContext('Finds app bundle when flavor contains underscores in profile mode - Gradle 3.5', () {
      final FlutterProject project = generateFakeAppBundle('foo_barProfile', 'app-foo_bar-profile.aab', fileSystem);
243
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.profile, 'foo_bar', treeShakeIcons: false));
244
      expect(bundle, isNotNull);
245
      expect(bundle.path, fileSystem.path.join('irrelevant', 'app', 'outputs', 'bundle', 'foo_barProfile', 'app-foo_bar-profile.aab'));
246 247
    });

248 249
    testWithoutContext('Finds app bundle when flavor contains underscores in debug mode - Gradle 3.5', () {
      final FlutterProject project = generateFakeAppBundle('foo_barDebug', 'app-foo_bar-debug.aab', fileSystem);
250
      final File bundle = findBundleFile(project, const BuildInfo(BuildMode.debug, 'foo_bar', treeShakeIcons: false));
251
      expect(bundle, isNotNull);
252
      expect(bundle.path, fileSystem.path.join('irrelevant','app', 'outputs', 'bundle', 'foo_barDebug', 'app-foo_bar-debug.aab'));
253
    });
254 255 256 257 258

    testUsingContext('aab not found', () {
      final FlutterProject project = FlutterProject.current();
      expect(
        () {
259
          findBundleFile(project, const BuildInfo(BuildMode.debug, 'foo_bar', treeShakeIcons: false));
260 261 262
        },
        throwsToolExit(
          message:
263 264
            "Gradle build failed to produce an .aab file. It's likely that this file "
            "was generated under ${project.android.buildDirectory.path}, but the tool couldn't find it."
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
        )
      );
      verify(
        mockUsage.sendEvent(
          any,
          any,
          label: 'gradle-expected-file-not-found',
          parameters: const <String, String> {
            'cd37': 'androidGradlePluginVersion: 5.6.2, fileExtension: .aab',
          },
        ),
      ).called(1);
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem(),
      ProcessManager: () => FakeProcessManager.any(),
      Usage: () => mockUsage,
    });
282 283
  });

284 285 286
  group('listApkPaths', () {
    testWithoutContext('Finds APK without flavor in release', () {
      final Iterable<String> apks = listApkPaths(
287
        const AndroidBuildInfo(BuildInfo(BuildMode.release, '', treeShakeIcons: false)),
288
      );
289

290 291
      expect(apks, <String>['app-release.apk']);
    });
292

293 294
    testWithoutContext('Finds APK with flavor in release mode', () {
      final Iterable<String> apks = listApkPaths(
295
        const AndroidBuildInfo(BuildInfo(BuildMode.release, 'flavor1', treeShakeIcons: false)),
296 297
      );

298 299
      expect(apks, <String>['app-flavor1-release.apk']);
    });
300

301 302
    testWithoutContext('Finds APK with flavor in release mode - AGP v3', () {
      final Iterable<String> apks = listApkPaths(
303
        const AndroidBuildInfo(BuildInfo(BuildMode.release, 'flavor1', treeShakeIcons: false)),
304
      );
305 306

      expect(apks, <String>['app-flavor1-release.apk']);
307
    });
308

309 310 311
    testWithoutContext('Finds APK with split-per-abi', () {
      final Iterable<String> apks = listApkPaths(
        const AndroidBuildInfo(BuildInfo(BuildMode.release, 'flavor1', treeShakeIcons: false), splitPerAbi: true),
312
      );
313 314 315 316 317 318

      expect(apks, unorderedEquals(<String>[
        'app-armeabi-v7a-flavor1-release.apk',
        'app-arm64-v8a-flavor1-release.apk',
        'app-x86_64-flavor1-release.apk',
      ]));
319
    });
320 321 322 323 324 325 326
  });

  group('gradle build', () {
    testUsingContext('do not crash if there is no Android SDK', () async {
      expect(() {
        updateLocalProperties(project: FlutterProject.current());
      }, throwsToolExit(
327
        message: '$warningMark No Android SDK found. Try setting the ANDROID_SDK_ROOT environment variable.',
328 329 330
      ));
    }, overrides: <Type, Generator>{
      AndroidSdk: () => null,
331
    });
332 333 334 335 336 337 338 339 340 341 342 343 344 345

    test('androidXPluginWarningRegex should match lines with the AndroidX plugin warnings', () {
      final List<String> nonMatchingLines = <String>[
        ':app:preBuild UP-TO-DATE',
        'BUILD SUCCESSFUL in 0s',
        'Generic plugin AndroidX text',
        '',
      ];
      final List<String> matchingLines = <String>[
        '*********************************************************************************************************************************',
        "WARNING: This version of image_picker will break your Android build if it or its dependencies aren't compatible with AndroidX.",
        'See https://goo.gl/CP92wY for more information on the problem and how to fix it.',
        'This warning prints for all Android build failures. The real root cause of the error may be unrelated.',
      ];
346
      for (final String m in nonMatchingLines) {
347 348
        expect(androidXPluginWarningRegex.hasMatch(m), isFalse);
      }
349
      for (final String m in matchingLines) {
350 351
        expect(androidXPluginWarningRegex.hasMatch(m), isTrue);
      }
352
    });
353
  });
354

355 356 357 358
  group('Config files', () {
    Directory tempDir;

    setUp(() {
359
      tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_settings_aar_test.');
360 361 362
    });

    testUsingContext('create settings_aar.gradle when current settings.gradle loads plugins', () {
363
      const String currentSettingsGradle = r'''
364 365 366 367 368 369 370 371 372 373 374 375
include ':app'

def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()

def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
    pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}

plugins.each { name, path ->
    def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
376 377 378 379
    if (pluginDirectory.exists()) {
        include ":$name"
        project(":$name").projectDir = pluginDirectory
    }
380 381 382 383 384 385 386 387 388
}
''';

      const String settingsAarFile = '''
include ':app'
''';

      tempDir.childFile('settings.gradle').writeAsStringSync(currentSettingsGradle);

389 390
      final String toolGradlePath = globals.fs.path.join(
          globals.fs.path.absolute(Cache.flutterRoot),
391 392 393
          'packages',
          'flutter_tools',
          'gradle');
394
      globals.fs.directory(toolGradlePath).createSync(recursive: true);
395
      globals.fs.file(globals.fs.path.join(toolGradlePath, 'settings.gradle.legacy_versions'))
396 397
          .writeAsStringSync(currentSettingsGradle);

398
      globals.fs.file(globals.fs.path.join(toolGradlePath, 'settings_aar.gradle.tmpl'))
399 400 401 402
          .writeAsStringSync(settingsAarFile);

      createSettingsAarGradle(tempDir);

403
      expect(testLogger.statusText, contains('created successfully'));
404 405 406 407
      expect(tempDir.childFile('settings_aar.gradle').existsSync(), isTrue);

    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem(),
408
      ProcessManager: () => FakeProcessManager.any(),
409 410
    });

411
    testUsingContext("create settings_aar.gradle when current settings.gradle doesn't load plugins", () {
412 413 414 415 416 417 418 419 420 421
      const String currentSettingsGradle = '''
include ':app'
''';

      const String settingsAarFile = '''
include ':app'
''';

      tempDir.childFile('settings.gradle').writeAsStringSync(currentSettingsGradle);

422 423
      final String toolGradlePath = globals.fs.path.join(
          globals.fs.path.absolute(Cache.flutterRoot),
424 425 426
          'packages',
          'flutter_tools',
          'gradle');
427
      globals.fs.directory(toolGradlePath).createSync(recursive: true);
428
      globals.fs.file(globals.fs.path.join(toolGradlePath, 'settings.gradle.legacy_versions'))
429 430
          .writeAsStringSync(currentSettingsGradle);

431
      globals.fs.file(globals.fs.path.join(toolGradlePath, 'settings_aar.gradle.tmpl'))
432 433 434 435
          .writeAsStringSync(settingsAarFile);

      createSettingsAarGradle(tempDir);

436
      expect(testLogger.statusText, contains('created successfully'));
437 438 439 440
      expect(tempDir.childFile('settings_aar.gradle').existsSync(), isTrue);

    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem(),
441
      ProcessManager: () => FakeProcessManager.any(),
442 443 444
    });
  });

445
  group('Gradle local.properties', () {
446 447 448 449
    MockLocalEngineArtifacts mockArtifacts;
    MockProcessManager mockProcessManager;
    FakePlatform android;
    FileSystem fs;
450 451

    setUp(() {
452 453 454
      fs = MemoryFileSystem();
      mockArtifacts = MockLocalEngineArtifacts();
      mockProcessManager = MockProcessManager();
455
      android = fakePlatform('android');
456 457
    });

458 459 460 461 462
    void testUsingAndroidContext(String description, dynamic testMethod()) {
      testUsingContext(description, testMethod, overrides: <Type, Generator>{
        Artifacts: () => mockArtifacts,
        Platform: () => android,
        FileSystem: () => fs,
463
        ProcessManager: () => mockProcessManager,
464
      });
465 466 467
    }

    String propertyFor(String key, File file) {
468
      final Iterable<String> result = file.readAsLinesSync()
469
          .where((String line) => line.startsWith('$key='))
470 471
          .map((String line) => line.split('=')[1]);
      return result.isEmpty ? null : result.first;
472 473 474 475 476 477 478 479
    }

    Future<void> checkBuildVersion({
      String manifest,
      BuildInfo buildInfo,
      String expectedBuildName,
      String expectedBuildNumber,
    }) async {
480 481
      when(mockArtifacts.getArtifactPath(Artifact.flutterFramework,
          platform: TargetPlatform.android_arm, mode: anyNamed('mode'))).thenReturn('engine');
482
      when(mockArtifacts.engineOutPath).thenReturn(globals.fs.path.join('out', 'android_arm'));
483

484
      final File manifestFile = globals.fs.file('path/to/project/pubspec.yaml');
485 486
      manifestFile.createSync(recursive: true);
      manifestFile.writeAsStringSync(manifest);
487

488
      // write schemaData otherwise pubspec.yaml file can't be loaded
489
      writeEmptySchemaFile(fs);
490

491
      updateLocalProperties(
492
        project: FlutterProject.fromPath('path/to/project'),
493 494 495 496
        buildInfo: buildInfo,
        requireAndroidSdk: false,
      );

497
      final File localPropertiesFile = globals.fs.file('path/to/project/android/local.properties');
498 499
      expect(propertyFor('flutter.versionName', localPropertiesFile), expectedBuildName);
      expect(propertyFor('flutter.versionCode', localPropertiesFile), expectedBuildNumber);
500 501
    }

502
    testUsingAndroidContext('extract build name and number from pubspec.yaml', () async {
503 504 505 506 507 508 509 510 511
      const String manifest = '''
name: test
version: 1.0.0+1
dependencies:
  flutter:
    sdk: flutter
flutter:
''';

512
      const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, treeShakeIcons: false);
513 514 515 516 517 518 519 520
      await checkBuildVersion(
        manifest: manifest,
        buildInfo: buildInfo,
        expectedBuildName: '1.0.0',
        expectedBuildNumber: '1',
      );
    });

521
    testUsingAndroidContext('extract build name from pubspec.yaml', () async {
522 523 524 525 526 527 528 529
      const String manifest = '''
name: test
version: 1.0.0
dependencies:
  flutter:
    sdk: flutter
flutter:
''';
530
      const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, treeShakeIcons: false);
531 532 533 534 535 536 537 538
      await checkBuildVersion(
        manifest: manifest,
        buildInfo: buildInfo,
        expectedBuildName: '1.0.0',
        expectedBuildNumber: null,
      );
    });

539
    testUsingAndroidContext('allow build info to override build name', () async {
540 541 542 543 544 545 546 547
      const String manifest = '''
name: test
version: 1.0.0+1
dependencies:
  flutter:
    sdk: flutter
flutter:
''';
548
      const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, buildName: '1.0.2', treeShakeIcons: false);
549 550 551 552 553 554 555 556
      await checkBuildVersion(
        manifest: manifest,
        buildInfo: buildInfo,
        expectedBuildName: '1.0.2',
        expectedBuildNumber: '1',
      );
    });

557
    testUsingAndroidContext('allow build info to override build number', () async {
558 559 560 561 562 563 564 565
      const String manifest = '''
name: test
version: 1.0.0+1
dependencies:
  flutter:
    sdk: flutter
flutter:
''';
566
      const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, buildNumber: '3', treeShakeIcons: false);
567 568 569 570 571 572 573 574
      await checkBuildVersion(
        manifest: manifest,
        buildInfo: buildInfo,
        expectedBuildName: '1.0.0',
        expectedBuildNumber: '3',
      );
    });

575
    testUsingAndroidContext('allow build info to override build name and number', () async {
576 577 578 579 580 581 582 583
      const String manifest = '''
name: test
version: 1.0.0+1
dependencies:
  flutter:
    sdk: flutter
flutter:
''';
584
      const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, buildName: '1.0.2', buildNumber: '3', treeShakeIcons: false);
585 586 587 588 589 590 591 592
      await checkBuildVersion(
        manifest: manifest,
        buildInfo: buildInfo,
        expectedBuildName: '1.0.2',
        expectedBuildNumber: '3',
      );
    });

593
    testUsingAndroidContext('allow build info to override build name and set number', () async {
594 595 596 597 598 599 600 601
      const String manifest = '''
name: test
version: 1.0.0
dependencies:
  flutter:
    sdk: flutter
flutter:
''';
602
      const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, buildName: '1.0.2', buildNumber: '3', treeShakeIcons: false);
603 604 605 606 607 608 609 610
      await checkBuildVersion(
        manifest: manifest,
        buildInfo: buildInfo,
        expectedBuildName: '1.0.2',
        expectedBuildNumber: '3',
      );
    });

611
    testUsingAndroidContext('allow build info to set build name and number', () async {
612 613 614 615 616 617 618
      const String manifest = '''
name: test
dependencies:
  flutter:
    sdk: flutter
flutter:
''';
619
      const BuildInfo buildInfo = BuildInfo(BuildMode.release, null, buildName: '1.0.2', buildNumber: '3', treeShakeIcons: false);
620 621 622 623 624 625 626
      await checkBuildVersion(
        manifest: manifest,
        buildInfo: buildInfo,
        expectedBuildName: '1.0.2',
        expectedBuildNumber: '3',
      );
    });
627 628 629 630 631 632 633 634 635 636 637

    testUsingAndroidContext('allow build info to unset build name and number', () async {
      const String manifest = '''
name: test
dependencies:
  flutter:
    sdk: flutter
flutter:
''';
      await checkBuildVersion(
        manifest: manifest,
638
        buildInfo: const BuildInfo(BuildMode.release, null, buildName: null, buildNumber: null, treeShakeIcons: false),
639 640 641 642 643
        expectedBuildName: null,
        expectedBuildNumber: null,
      );
      await checkBuildVersion(
        manifest: manifest,
644
        buildInfo: const BuildInfo(BuildMode.release, null, buildName: '1.0.2', buildNumber: '3', treeShakeIcons: false),
645 646 647 648 649
        expectedBuildName: '1.0.2',
        expectedBuildNumber: '3',
      );
      await checkBuildVersion(
        manifest: manifest,
650
        buildInfo: const BuildInfo(BuildMode.release, null, buildName: '1.0.3', buildNumber: '4', treeShakeIcons: false),
651 652 653 654 655 656 657 658 659 660 661 662 663
        expectedBuildName: '1.0.3',
        expectedBuildNumber: '4',
      );
      // Values don't get unset.
      await checkBuildVersion(
        manifest: manifest,
        buildInfo: null,
        expectedBuildName: '1.0.3',
        expectedBuildNumber: '4',
      );
      // Values get unset.
      await checkBuildVersion(
        manifest: manifest,
664
        buildInfo: const BuildInfo(BuildMode.release, null, buildName: null, buildNumber: null, treeShakeIcons: false),
665 666 667 668
        expectedBuildName: null,
        expectedBuildNumber: null,
      );
    });
669
  });
670 671

  group('gradle version', () {
672
    testWithoutContext('should be compatible with the Android plugin version', () {
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
      // Granular versions.
      expect(getGradleVersionFor('1.0.0'), '2.3');
      expect(getGradleVersionFor('1.0.1'), '2.3');
      expect(getGradleVersionFor('1.0.2'), '2.3');
      expect(getGradleVersionFor('1.0.4'), '2.3');
      expect(getGradleVersionFor('1.0.8'), '2.3');
      expect(getGradleVersionFor('1.1.0'), '2.3');
      expect(getGradleVersionFor('1.1.2'), '2.3');
      expect(getGradleVersionFor('1.1.2'), '2.3');
      expect(getGradleVersionFor('1.1.3'), '2.3');
      // Version Ranges.
      expect(getGradleVersionFor('1.2.0'), '2.9');
      expect(getGradleVersionFor('1.3.1'), '2.9');

      expect(getGradleVersionFor('1.5.0'), '2.2.1');

      expect(getGradleVersionFor('2.0.0'), '2.13');
      expect(getGradleVersionFor('2.1.2'), '2.13');

      expect(getGradleVersionFor('2.1.3'), '2.14.1');
      expect(getGradleVersionFor('2.2.3'), '2.14.1');

      expect(getGradleVersionFor('2.3.0'), '3.3');

      expect(getGradleVersionFor('3.0.0'), '4.1');

      expect(getGradleVersionFor('3.1.0'), '4.4');

      expect(getGradleVersionFor('3.2.0'), '4.6');
      expect(getGradleVersionFor('3.2.1'), '4.6');

      expect(getGradleVersionFor('3.3.0'), '4.10.2');
      expect(getGradleVersionFor('3.3.2'), '4.10.2');

707 708
      expect(getGradleVersionFor('3.4.0'), '5.6.2');
      expect(getGradleVersionFor('3.5.0'), '5.6.2');
709 710
    });

711
    testWithoutContext('throws on unsupported versions', () {
712 713 714 715
      expect(() => getGradleVersionFor('3.6.0'),
          throwsA(predicate<Exception>((Exception e) => e is ToolExit)));
    });
  });
716

717 718 719 720 721 722 723 724
  group('isAppUsingAndroidX', () {
    FileSystem fs;

    setUp(() {
      fs = MemoryFileSystem();
    });

    testUsingContext('returns true when the project is using AndroidX', () async {
725
      final Directory androidDirectory = globals.fs.systemTempDirectory.createTempSync('flutter_android.');
726 727 728 729 730 731 732 733 734

      androidDirectory
        .childFile('gradle.properties')
        .writeAsStringSync('android.useAndroidX=true');

      expect(isAppUsingAndroidX(androidDirectory), isTrue);

    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
735
      ProcessManager: () => FakeProcessManager.any(),
736 737 738
    });

    testUsingContext('returns false when the project is not using AndroidX', () async {
739
      final Directory androidDirectory = globals.fs.systemTempDirectory.createTempSync('flutter_android.');
740 741 742 743 744 745 746 747 748

      androidDirectory
        .childFile('gradle.properties')
        .writeAsStringSync('android.useAndroidX=false');

      expect(isAppUsingAndroidX(androidDirectory), isFalse);

    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
749
      ProcessManager: () => FakeProcessManager.any(),
750 751 752
    });

    testUsingContext('returns false when gradle.properties does not exist', () async {
753
      final Directory androidDirectory = globals.fs.systemTempDirectory.createTempSync('flutter_android.');
754 755 756 757 758

      expect(isAppUsingAndroidX(androidDirectory), isFalse);

    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
759
      ProcessManager: () => FakeProcessManager.any(),
760 761 762 763 764
    });
  });

  group('buildPluginsAsAar', () {
    FileSystem fs;
765
    FakeProcessManager fakeProcessManager;
766 767 768 769
    MockAndroidSdk mockAndroidSdk;

    setUp(() {
      fs = MemoryFileSystem();
770
      fakeProcessManager = FakeProcessManager.list(<FakeCommand>[]);
771 772 773 774 775
      mockAndroidSdk = MockAndroidSdk();
      when(mockAndroidSdk.directory).thenReturn('irrelevant');
    });

    testUsingContext('calls gradle', () async {
776
      final Directory androidDirectory = globals.fs.directory('android.');
777 778 779 780 781
      androidDirectory.createSync();
      androidDirectory
        .childFile('pubspec.yaml')
        .writeAsStringSync('name: irrelevant');

782
      final Directory plugin1 = globals.fs.directory('plugin1.');
783 784 785 786 787 788 789 790 791
      plugin1
        ..createSync()
        ..childFile('pubspec.yaml')
        .writeAsStringSync('''
name: irrelevant
flutter:
  plugin:
    androidPackage: irrelevant
''');
792

793 794 795 796
      plugin1
        .childDirectory('android')
        .childFile('build.gradle')
        .createSync(recursive: true);
797

798
      final Directory plugin2 = globals.fs.directory('plugin2.');
799 800 801 802 803 804 805 806 807 808
      plugin2
        ..createSync()
        ..childFile('pubspec.yaml')
        .writeAsStringSync('''
name: irrelevant
flutter:
  plugin:
    androidPackage: irrelevant
''');

809 810 811 812
      plugin2
        .childDirectory('android')
        .childFile('build.gradle')
        .createSync(recursive: true);
813

814 815 816 817 818 819
      androidDirectory
        .childFile('.flutter-plugins')
        .writeAsStringSync('''
plugin1=${plugin1.path}
plugin2=${plugin2.path}
''');
820 821
      final Directory buildDirectory = androidDirectory
        .childDirectory('build');
822 823 824 825 826
      buildDirectory
        .childDirectory('outputs')
        .childDirectory('repo')
        .createSync(recursive: true);

827 828
      final String flutterRoot = globals.fs.path.absolute(Cache.flutterRoot);
      final String initScript = globals.fs.path.join(
829 830 831 832 833 834
        flutterRoot,
        'packages',
        'flutter_tools',
        'gradle',
        'aar_init_script.gradle',
      );
835

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
      fakeProcessManager
        ..addCommand(FakeCommand(
          command: <String>[
            'gradlew',
            '-I=$initScript',
            '-Pflutter-root=$flutterRoot',
            '-Poutput-dir=${buildDirectory.path}',
            '-Pis-plugin=true',
            '-PbuildNumber=1.0',
            '-q',
            '-Pfont-subset=true',
            '-Ptarget-platform=android-arm,android-arm64,android-x64',
            'assembleAarRelease',
          ],
          workingDirectory: plugin1.childDirectory('android').path,
        ))
        ..addCommand(FakeCommand(
          command: <String>[
            'gradlew',
            '-I=$initScript',
            '-Pflutter-root=$flutterRoot',
            '-Poutput-dir=${buildDirectory.path}',
            '-Pis-plugin=true',
            '-PbuildNumber=1.0',
            '-q',
            '-Pfont-subset=true',
            '-Ptarget-platform=android-arm,android-arm64,android-x64',
            'assembleAarRelease',
          ],
          workingDirectory: plugin2.childDirectory('android').path,
        ));
867

868 869 870 871 872 873 874 875 876 877 878 879
      await buildPluginsAsAar(
        FlutterProject.fromPath(androidDirectory.path),
        const AndroidBuildInfo(BuildInfo(
          BuildMode.release,
          '',
          treeShakeIcons: true,
          dartObfuscation: true,
          buildNumber: '2.0'
        )),
        buildDirectory: buildDirectory,
      );
      expect(fakeProcessManager.hasRemainingExpectations, isFalse);
880 881 882
    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      FileSystem: () => fs,
883
      ProcessManager: () => fakeProcessManager,
884 885 886
      GradleUtils: () => FakeGradleUtils(),
    });

887
    testUsingContext('skips plugin without a android/build.gradle file', () async {
888
      final Directory androidDirectory = globals.fs.directory('android.');
889 890 891 892 893
      androidDirectory.createSync();
      androidDirectory
        .childFile('pubspec.yaml')
        .writeAsStringSync('name: irrelevant');

894
      final Directory plugin1 = globals.fs.directory('plugin1.');
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
      plugin1
        ..createSync()
        ..childFile('pubspec.yaml')
        .writeAsStringSync('''
name: irrelevant
flutter:
  plugin:
    androidPackage: irrelevant
''');

      androidDirectory
        .childFile('.flutter-plugins')
        .writeAsStringSync('''
plugin1=${plugin1.path}
''');
910 911 912 913
      // Create an empty android directory.
      // https://github.com/flutter/flutter/issues/46898
      plugin1.childDirectory('android').createSync();

914 915 916 917 918 919 920 921 922 923 924 925
      final Directory buildDirectory = androidDirectory.childDirectory('build');

      buildDirectory
        .childDirectory('outputs')
        .childDirectory('repo')
        .createSync(recursive: true);

      await buildPluginsAsAar(
        FlutterProject.fromPath(androidDirectory.path),
        const AndroidBuildInfo(BuildInfo.release),
        buildDirectory: buildDirectory,
      );
926
      expect(fakeProcessManager.hasRemainingExpectations, isFalse);
927 928 929
    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      FileSystem: () => fs,
930
      ProcessManager: () => fakeProcessManager,
931
      GradleUtils: () => FakeGradleUtils(),
932 933 934
    });
  });

935
  group('gradle build', () {
936
    Usage mockUsage;
937 938 939 940 941
    MockAndroidSdk mockAndroidSdk;
    MockAndroidStudio mockAndroidStudio;
    MockLocalEngineArtifacts mockArtifacts;
    MockProcessManager mockProcessManager;
    FakePlatform android;
942
    FileSystem fileSystem;
943
    FileSystemUtils fileSystemUtils;
944
    Cache cache;
945 946

    setUp(() {
947
      mockUsage = MockUsage();
948
      fileSystem = MemoryFileSystem();
949
      fileSystemUtils = MockFileSystemUtils();
950 951 952 953 954
      mockAndroidSdk = MockAndroidSdk();
      mockAndroidStudio = MockAndroidStudio();
      mockArtifacts = MockLocalEngineArtifacts();
      mockProcessManager = MockProcessManager();
      android = fakePlatform('android');
955

956 957
      when(mockAndroidSdk.directory).thenReturn('irrelevant');

958 959 960 961 962
      final Directory rootDirectory = fileSystem.currentDirectory;
      cache = Cache(
        rootOverride: rootDirectory,
        fileSystem: fileSystem,
      );
963

964
      final Directory gradleWrapperDirectory = rootDirectory
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
          .childDirectory('bin')
          .childDirectory('cache')
          .childDirectory('artifacts')
          .childDirectory('gradle_wrapper');
      gradleWrapperDirectory.createSync(recursive: true);
      gradleWrapperDirectory
          .childFile('gradlew')
          .writeAsStringSync('irrelevant');
      gradleWrapperDirectory
        .childDirectory('gradle')
        .childDirectory('wrapper')
        .createSync(recursive: true);
      gradleWrapperDirectory
        .childDirectory('gradle')
        .childDirectory('wrapper')
        .childFile('gradle-wrapper.jar')
        .writeAsStringSync('irrelevant');
982 983
    });

984 985 986 987 988 989 990 991 992 993
    testUsingContext('recognizes common errors - tool exit', () async {
      final Process process = createMockProcess(
        exitCode: 1,
        stdout: 'irrelevant\nSome gradle message\nirrelevant',
      );
      when(mockProcessManager.start(any,
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment')))
      .thenAnswer((_) => Future<Process>.value(process));

994
      fileSystem.directory('android')
995 996 997
        .childFile('build.gradle')
        .createSync(recursive: true);

998
      fileSystem.directory('android')
999 1000 1001
        .childFile('gradle.properties')
        .createSync(recursive: true);

1002
      fileSystem.directory('android')
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        .childDirectory('app')
        .childFile('build.gradle')
        ..createSync(recursive: true)
        ..writeAsStringSync('apply from: irrelevant/flutter.gradle');

      bool handlerCalled = false;
      await expectLater(() async {
       await buildGradleApp(
          project: FlutterProject.current(),
          androidBuildInfo: const AndroidBuildInfo(
            BuildInfo(
              BuildMode.release,
              null,
1016
              treeShakeIcons: false,
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
            ),
          ),
          target: 'lib/main.dart',
          isBuildingBundle: false,
          localGradleErrors: <GradleHandledError>[
            GradleHandledError(
              test: (String line) {
                return line.contains('Some gradle message');
              },
              handler: ({
                String line,
                FlutterProject project,
                bool usesAndroidX,
                bool shouldBuildPluginAsAar,
              }) async {
                handlerCalled = true;
                return GradleBuildStatus.exit;
              },
              eventLabel: 'random-event-label',
            ),
          ],
        );
      },
      throwsToolExit(
        message: 'Gradle task assembleRelease failed with exit code 1'
      ));

      expect(handlerCalled, isTrue);

      verify(mockUsage.sendEvent(
        any,
        any,
1049
        label: 'gradle-random-event-label-failure',
1050 1051 1052 1053 1054 1055 1056
        parameters: anyNamed('parameters'),
      )).called(1);

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      Cache: () => cache,
      Platform: () => android,
1057
      FileSystem: () => fileSystem,
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
      ProcessManager: () => mockProcessManager,
      Usage: () => mockUsage,
    });

    testUsingContext('recognizes common errors - retry build', () async {
      when(mockProcessManager.start(any,
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment')))
      .thenAnswer((_) {
        final Process process = createMockProcess(
          exitCode: 1,
          stdout: 'irrelevant\nSome gradle message\nirrelevant',
        );
        return Future<Process>.value(process);
      });

1074
      fileSystem.directory('android')
1075 1076 1077
        .childFile('build.gradle')
        .createSync(recursive: true);

1078
      fileSystem.directory('android')
1079 1080 1081
        .childFile('gradle.properties')
        .createSync(recursive: true);

1082
      fileSystem.directory('android')
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
        .childDirectory('app')
        .childFile('build.gradle')
        ..createSync(recursive: true)
        ..writeAsStringSync('apply from: irrelevant/flutter.gradle');

      int testFnCalled = 0;
      await expectLater(() async {
       await buildGradleApp(
          project: FlutterProject.current(),
          androidBuildInfo: const AndroidBuildInfo(
            BuildInfo(
              BuildMode.release,
              null,
1096
              treeShakeIcons: false,
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
            ),
          ),
          target: 'lib/main.dart',
          isBuildingBundle: false,
          localGradleErrors: <GradleHandledError>[
            GradleHandledError(
              test: (String line) {
                if (line.contains('Some gradle message')) {
                  testFnCalled++;
                  return true;
                }
                return false;
              },
              handler: ({
                String line,
                FlutterProject project,
                bool usesAndroidX,
                bool shouldBuildPluginAsAar,
              }) async {
                return GradleBuildStatus.retry;
              },
              eventLabel: 'random-event-label',
            ),
          ],
        );
      }, throwsToolExit(
        message: 'Gradle task assembleRelease failed with exit code 1'
      ));

      expect(testFnCalled, equals(2));

      verify(mockUsage.sendEvent(
        any,
        any,
1131
        label: 'gradle-random-event-label-failure',
1132 1133 1134 1135 1136 1137 1138
        parameters: anyNamed('parameters'),
      )).called(1);

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      Cache: () => cache,
      Platform: () => android,
1139
      FileSystem: () => fileSystem,
1140 1141 1142 1143
      ProcessManager: () => mockProcessManager,
      Usage: () => mockUsage,
    });

1144 1145 1146 1147 1148 1149
    testUsingContext('recognizes process exceptions - tool exit', () async {
      when(mockProcessManager.start(any,
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment')))
      .thenThrow(const ProcessException('', <String>[], 'Some gradle message'));

1150
      fileSystem.directory('android')
1151 1152 1153
        .childFile('build.gradle')
        .createSync(recursive: true);

1154
      fileSystem.directory('android')
1155 1156 1157
        .childFile('gradle.properties')
        .createSync(recursive: true);

1158
      fileSystem.directory('android')
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
        .childDirectory('app')
        .childFile('build.gradle')
        ..createSync(recursive: true)
        ..writeAsStringSync('apply from: irrelevant/flutter.gradle');

      bool handlerCalled = false;
      await expectLater(() async {
       await buildGradleApp(
          project: FlutterProject.current(),
          androidBuildInfo: const AndroidBuildInfo(
            BuildInfo(
              BuildMode.release,
              null,
1172
              treeShakeIcons: false,
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
            ),
          ),
          target: 'lib/main.dart',
          isBuildingBundle: false,
          localGradleErrors: <GradleHandledError>[
            GradleHandledError(
              test: (String line) {
                return line.contains('Some gradle message');
              },
              handler: ({
                String line,
                FlutterProject project,
                bool usesAndroidX,
                bool shouldBuildPluginAsAar,
              }) async {
                handlerCalled = true;
                return GradleBuildStatus.exit;
              },
              eventLabel: 'random-event-label',
            ),
          ],
        );
      },
      throwsToolExit(
        message: 'Gradle task assembleRelease failed with exit code 1'
      ));

      expect(handlerCalled, isTrue);

      verify(mockUsage.sendEvent(
        any,
        any,
        label: 'gradle-random-event-label-failure',
        parameters: anyNamed('parameters'),
      )).called(1);

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      Cache: () => cache,
      Platform: () => android,
1213
      FileSystem: () => fileSystem,
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
      ProcessManager: () => mockProcessManager,
      Usage: () => mockUsage,
    });

    testUsingContext('rethrows unrecognized ProcessException', () async {
      when(mockProcessManager.start(any,
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment')))
      .thenThrow(const ProcessException('', <String>[], 'Unrecognized'));

1224
      fileSystem.directory('android')
1225 1226 1227
        .childFile('build.gradle')
        .createSync(recursive: true);

1228
      fileSystem.directory('android')
1229 1230 1231
        .childFile('gradle.properties')
        .createSync(recursive: true);

1232
      fileSystem.directory('android')
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
        .childDirectory('app')
        .childFile('build.gradle')
        ..createSync(recursive: true)
        ..writeAsStringSync('apply from: irrelevant/flutter.gradle');

      await expectLater(() async {
       await buildGradleApp(
          project: FlutterProject.current(),
          androidBuildInfo: const AndroidBuildInfo(
            BuildInfo(
              BuildMode.release,
              null,
1245
              treeShakeIcons: false,
1246 1247 1248 1249 1250 1251 1252
            ),
          ),
          target: 'lib/main.dart',
          isBuildingBundle: false,
          localGradleErrors: const <GradleHandledError>[],
        );
      },
Dan Field's avatar
Dan Field committed
1253
      throwsA(isA<ProcessException>()));
1254 1255 1256 1257 1258

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      Cache: () => cache,
      Platform: () => android,
1259
      FileSystem: () => fileSystem,
1260 1261 1262
      ProcessManager: () => mockProcessManager,
    });

1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
    testUsingContext('logs success event after a sucessful retry', () async {
      int testFnCalled = 0;
      when(mockProcessManager.start(any,
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment')))
      .thenAnswer((_) {
        Process process;
        if (testFnCalled == 0) {
          process = createMockProcess(
            exitCode: 1,
            stdout: 'irrelevant\nSome gradle message\nirrelevant',
          );
        } else {
          process = createMockProcess(
            exitCode: 0,
            stdout: 'irrelevant',
          );
        }
        testFnCalled++;
        return Future<Process>.value(process);
      });

1285
      fileSystem.directory('android')
1286 1287 1288
        .childFile('build.gradle')
        .createSync(recursive: true);

1289
      fileSystem.directory('android')
1290 1291 1292
        .childFile('gradle.properties')
        .createSync(recursive: true);

1293
      fileSystem.directory('android')
1294 1295 1296 1297 1298
        .childDirectory('app')
        .childFile('build.gradle')
        ..createSync(recursive: true)
        ..writeAsStringSync('apply from: irrelevant/flutter.gradle');

1299
      fileSystem.directory('build')
1300 1301
        .childDirectory('app')
        .childDirectory('outputs')
1302
        .childDirectory('flutter-apk')
1303
        .childFile('app-release.apk')
1304
        .createSync(recursive: true);
1305 1306 1307 1308 1309 1310 1311

      await buildGradleApp(
        project: FlutterProject.current(),
        androidBuildInfo: const AndroidBuildInfo(
          BuildInfo(
            BuildMode.release,
            null,
1312
            treeShakeIcons: false,
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
          ),
        ),
        target: 'lib/main.dart',
        isBuildingBundle: false,
        localGradleErrors: <GradleHandledError>[
          GradleHandledError(
            test: (String line) {
              return line.contains('Some gradle message');
            },
            handler: ({
              String line,
              FlutterProject project,
              bool usesAndroidX,
              bool shouldBuildPluginAsAar,
            }) async {
              return GradleBuildStatus.retry;
            },
            eventLabel: 'random-event-label',
          ),
        ],
      );

      verify(mockUsage.sendEvent(
        any,
        any,
1338
        label: 'gradle-random-event-label-success',
1339 1340 1341 1342 1343
        parameters: anyNamed('parameters'),
      )).called(1);
    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      Cache: () => cache,
1344
      FileSystem: () => fileSystem,
1345 1346 1347 1348 1349
      Platform: () => android,
      ProcessManager: () => mockProcessManager,
      Usage: () => mockUsage,
    });

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
    testUsingContext('performs code size analyis and sends analytics', () async {
      when(mockProcessManager.start(any,
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment')))
      .thenAnswer((_) {
        return Future<Process>.value(createMockProcess(
          exitCode: 0,
          stdout: 'irrelevant',
        ));
      });

      fileSystem.directory('android')
        .childFile('build.gradle')
        .createSync(recursive: true);

      fileSystem.directory('android')
        .childFile('gradle.properties')
        .createSync(recursive: true);

      fileSystem.directory('android')
        .childDirectory('app')
        .childFile('build.gradle')
        ..createSync(recursive: true)
        ..writeAsStringSync('apply from: irrelevant/flutter.gradle');

      final Archive archive = Archive()
        ..addFile(ArchiveFile('AndroidManifest.xml', 100,  List<int>.filled(100, 0)))
        ..addFile(ArchiveFile('META-INF/CERT.RSA', 10,  List<int>.filled(10, 0)))
        ..addFile(ArchiveFile('META-INF/CERT.SF', 10,  List<int>.filled(10, 0)))
        ..addFile(ArchiveFile('lib/arm64-v8a/libapp.so', 50,  List<int>.filled(50, 0)))
        ..addFile(ArchiveFile('lib/arm64-v8a/libflutter.so', 50, List<int>.filled(50, 0)));

      fileSystem.directory('build')
        .childDirectory('app')
        .childDirectory('outputs')
        .childDirectory('flutter-apk')
        .childFile('app-release.apk')
        ..createSync(recursive: true)
        ..writeAsBytesSync(ZipEncoder().encode(archive));

      fileSystem.file('foo/snapshot.arm64-v8a.json')
        ..createSync(recursive: true)
        ..writeAsStringSync(r'''[
{
  "l": "dart:_internal",
  "c": "SubListIterable",
  "n": "[Optimized] skip",
  "s": 2400
}
]''');
      fileSystem.file('foo/trace.arm64-v8a.json')
        ..createSync(recursive: true)
        ..writeAsStringSync('{}');

      await buildGradleApp(
        project: FlutterProject.current(),
        androidBuildInfo: const AndroidBuildInfo(
          BuildInfo(
            BuildMode.release,
            null,
            treeShakeIcons: false,
            codeSizeDirectory: 'foo',
          ),
          targetArchs: <AndroidArch>[AndroidArch.arm64_v8a],
        ),
        target: 'lib/main.dart',
        isBuildingBundle: false,
        localGradleErrors: <GradleHandledError>[],
      );

      verify(mockUsage.sendEvent(
        'code-size-analysis',
        'apk',
      )).called(1);
    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      Cache: () => cache,
      FileSystem: () => fileSystem,
      Platform: () => android,
      ProcessManager: () => mockProcessManager,
      Usage: () => mockUsage,
    });

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
    testUsingContext('recognizes common errors - retry build with AAR plugins', () async {
      when(mockProcessManager.start(any,
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment')))
      .thenAnswer((_) {
        final Process process = createMockProcess(
          exitCode: 1,
          stdout: 'irrelevant\nSome gradle message\nirrelevant',
        );
        return Future<Process>.value(process);
      });

1445
      fileSystem.directory('android')
1446 1447 1448
        .childFile('build.gradle')
        .createSync(recursive: true);

1449
      fileSystem.directory('android')
1450 1451 1452
        .childFile('gradle.properties')
        .createSync(recursive: true);

1453
      fileSystem.directory('android')
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
        .childDirectory('app')
        .childFile('build.gradle')
        ..createSync(recursive: true)
        ..writeAsStringSync('apply from: irrelevant/flutter.gradle');

      int testFnCalled = 0;
      bool builtPluginAsAar = false;
      await expectLater(() async {
       await buildGradleApp(
          project: FlutterProject.current(),
          androidBuildInfo: const AndroidBuildInfo(
            BuildInfo(
              BuildMode.release,
              null,
1468
              treeShakeIcons: false,
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
            ),
          ),
          target: 'lib/main.dart',
          isBuildingBundle: false,
          localGradleErrors: <GradleHandledError>[
            GradleHandledError(
              test: (String line) {
                if (line.contains('Some gradle message')) {
                  testFnCalled++;
                  return true;
                }
                return false;
              },
              handler: ({
                String line,
                FlutterProject project,
                bool usesAndroidX,
                bool shouldBuildPluginAsAar,
              }) async {
                if (testFnCalled == 2) {
                  builtPluginAsAar = shouldBuildPluginAsAar;
                }
                return GradleBuildStatus.retryWithAarPlugins;
              },
              eventLabel: 'random-event-label',
            ),
          ],
        );
      }, throwsToolExit(
        message: 'Gradle task assembleRelease failed with exit code 1'
      ));

      expect(testFnCalled, equals(2));
      expect(builtPluginAsAar, isTrue);

      verify(mockUsage.sendEvent(
        any,
        any,
1507
        label: 'gradle-random-event-label-failure',
1508 1509 1510 1511 1512 1513 1514
        parameters: anyNamed('parameters'),
      )).called(1);

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      Cache: () => cache,
      Platform: () => android,
1515
      FileSystem: () => fileSystem,
1516 1517 1518 1519 1520
      ProcessManager: () => mockProcessManager,
      Usage: () => mockUsage,
    });

    testUsingContext('indicates that an APK has been built successfully', () async {
1521
      fileSystem.directory('android')
1522 1523 1524
        .childFile('build.gradle')
        .createSync(recursive: true);

1525
      fileSystem.directory('android')
1526 1527 1528
        .childFile('gradle.properties')
        .createSync(recursive: true);

1529
      fileSystem.directory('android')
1530 1531 1532 1533 1534
        .childDirectory('app')
        .childFile('build.gradle')
        ..createSync(recursive: true)
        ..writeAsStringSync('apply from: irrelevant/flutter.gradle');

1535
      fileSystem.directory('build')
1536 1537
        .childDirectory('app')
        .childDirectory('outputs')
1538
        .childDirectory('flutter-apk')
1539
        .childFile('app-release.apk')
1540
        .createSync(recursive: true);
1541 1542 1543 1544 1545 1546 1547

      await buildGradleApp(
        project: FlutterProject.current(),
        androidBuildInfo: const AndroidBuildInfo(
          BuildInfo(
            BuildMode.release,
            null,
1548
            treeShakeIcons: false,
1549 1550 1551 1552
          ),
        ),
        target: 'lib/main.dart',
        isBuildingBundle: false,
1553
        localGradleErrors: const <GradleHandledError>[],
1554 1555 1556
      );

      expect(
1557
        testLogger.statusText,
1558
        contains('Built build/app/outputs/flutter-apk/app-release.apk (0.0MB)'),
1559 1560 1561 1562 1563
      );

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      Cache: () => cache,
1564
      FileSystem: () => fileSystem,
1565
      Platform: () => android,
1566
      ProcessManager: () => FakeProcessManager.any(),
1567 1568
    });

1569
    testUsingContext("doesn't indicate how to consume an AAR when printHowToConsumeAaar is false", () async {
1570
      final File manifestFile = fileSystem.file('pubspec.yaml');
1571 1572 1573 1574 1575 1576 1577 1578
      manifestFile.createSync(recursive: true);
      manifestFile.writeAsStringSync('''
        flutter:
          module:
            androidPackage: com.example.test
        '''
      );

1579
      fileSystem.file('.android/gradlew').createSync(recursive: true);
1580

1581
      fileSystem.file('.android/gradle.properties')
1582 1583
        .writeAsStringSync('irrelevant');

1584
      fileSystem.file('.android/build.gradle')
1585 1586 1587 1588 1589 1590 1591 1592 1593
        .createSync(recursive: true);

      // Let any process start. Assert after.
      when(mockProcessManager.run(
        any,
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenAnswer((_) async => ProcessResult(1, 0, '', ''));

1594
      fileSystem.directory('build/outputs/repo').createSync(recursive: true);
1595 1596

      await buildGradleAar(
1597
        androidBuildInfo: const AndroidBuildInfo(BuildInfo(BuildMode.release, null, treeShakeIcons: false)),
1598
        project: FlutterProject.current(),
1599
        outputDirectory: fileSystem.directory('build/'),
1600
        target: '',
1601
        buildNumber: '1.0',
1602 1603 1604
      );

      expect(
1605
        testLogger.statusText,
1606 1607 1608
        contains('Built build/outputs/repo'),
      );
      expect(
1609
        testLogger.statusText.contains('Consuming the Module'),
1610 1611 1612 1613 1614 1615 1616 1617
        isFalse,
      );

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      AndroidStudio: () => mockAndroidStudio,
      Cache: () => cache,
      Platform: () => android,
1618
      FileSystem: () => fileSystem,
1619 1620 1621
      ProcessManager: () => mockProcessManager,
    });

1622
    testUsingContext('build apk uses selected local engine,the engine abi is arm', () async {
1623 1624
      when(mockArtifacts.getArtifactPath(Artifact.flutterFramework,
          platform: TargetPlatform.android_arm, mode: anyNamed('mode'))).thenReturn('engine');
1625
      when(mockArtifacts.engineOutPath).thenReturn(fileSystem.path.join('out', 'android_arm'));
1626

1627
      fileSystem.file('out/android_arm/flutter_embedding_release.pom')
1628
        ..createSync(recursive: true)
1629 1630
        ..writeAsStringSync('''
<?xml version="1.0" encoding="UTF-8"?>
1631 1632 1633 1634 1635 1636
<project>
  <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version>
  <dependencies>
  </dependencies>
</project>
''');
1637 1638 1639 1640
      fileSystem.file('out/android_arm/armeabi_v7a_release.pom').createSync(recursive: true);
      fileSystem.file('out/android_arm/armeabi_v7a_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_arm/flutter_embedding_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_arm/flutter_embedding_release.pom').createSync(recursive: true);
1641

1642
      fileSystem.file('android/gradlew').createSync(recursive: true);
1643

1644
      fileSystem.directory('android')
1645 1646 1647
        .childFile('gradle.properties')
        .createSync(recursive: true);

1648
      fileSystem.file('android/build.gradle')
1649 1650
        .createSync(recursive: true);

1651
      fileSystem.directory('android')
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
        .childDirectory('app')
        .childFile('build.gradle')
        ..createSync(recursive: true)
        ..writeAsStringSync('apply from: irrelevant/flutter.gradle');

      // Let any process start. Assert after.
      when(mockProcessManager.run(
        any,
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenAnswer((_) async => ProcessResult(1, 0, '', ''));

      when(mockProcessManager.start(any,
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment')))
      .thenAnswer((_) {
        return Future<Process>.value(
          createMockProcess(
            exitCode: 1,
          )
        );
      });

      await expectLater(() async {
        await buildGradleApp(
          project: FlutterProject.current(),
          androidBuildInfo: const AndroidBuildInfo(
            BuildInfo(
              BuildMode.release,
              null,
1682
              treeShakeIcons: false,
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
            ),
          ),
          target: 'lib/main.dart',
          isBuildingBundle: false,
          localGradleErrors: const <GradleHandledError>[],
        );
      }, throwsToolExit());

      final List<String> actualGradlewCall = verify(
        mockProcessManager.start(
          captureAny,
          environment: anyNamed('environment'),
          workingDirectory: anyNamed('workingDirectory')
        ),
1697
      ).captured.last as List<String>;
1698 1699 1700 1701 1702 1703

      expect(actualGradlewCall, contains('/android/gradlew'));
      expect(actualGradlewCall, contains('-Plocal-engine-out=out/android_arm'));
      expect(actualGradlewCall, contains('-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0'));
      expect(actualGradlewCall, contains('-Plocal-engine-build-mode=release'));

1704 1705 1706 1707 1708 1709
    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      AndroidStudio: () => mockAndroidStudio,
      Artifacts: () => mockArtifacts,
      Cache: () => cache,
      Platform: () => android,
1710
      FileSystem: () => fileSystem,
1711 1712 1713
      ProcessManager: () => mockProcessManager,
    });

1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
    testUsingContext(
        'build apk uses selected local engine,the engine abi is arm64', () async {
      when(mockArtifacts.getArtifactPath(Artifact.flutterFramework,
          platform: anyNamed('platform'), mode: anyNamed('mode'))).thenReturn('engine');
      when(mockArtifacts.engineOutPath).thenReturn(fileSystem.path.join('out', 'android_arm64'));

      fileSystem.file('out/android_arm64/flutter_embedding_release.pom')
        ..createSync(recursive: true)
        ..writeAsStringSync('''
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version>
  <dependencies>
  </dependencies>
</project>
''');
      fileSystem.file('out/android_arm64/arm64_v8a_release.pom').createSync(recursive: true);
      fileSystem.file('out/android_arm64/arm64_v8a_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_arm64/flutter_embedding_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_arm64/flutter_embedding_release.pom').createSync(recursive: true);

      fileSystem.file('android/gradlew').createSync(recursive: true);

      fileSystem.directory('android')
          .childFile('gradle.properties')
          .createSync(recursive: true);

      fileSystem.file('android/build.gradle')
          .createSync(recursive: true);

      fileSystem.directory('android')
          .childDirectory('app')
          .childFile('build.gradle')
        ..createSync(recursive: true)
        ..writeAsStringSync('apply from: irrelevant/flutter.gradle');

      // Let any process start. Assert after.
      when(mockProcessManager.run(
        any,
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenAnswer((_) async => ProcessResult(1, 0, '', ''));

      when(mockProcessManager.start(any,
          workingDirectory: anyNamed('workingDirectory'),
          environment: anyNamed('environment')))
          .thenAnswer((_) {
        return Future<Process>.value(
            createMockProcess(
              exitCode: 1,
            )
        );
      });

      await expectLater(() async {
        await buildGradleApp(
          project: FlutterProject.current(),
          androidBuildInfo: const AndroidBuildInfo(
            BuildInfo(
              BuildMode.release,
              null,
              treeShakeIcons: false,
            ),
          ),
          target: 'lib/main.dart',
          isBuildingBundle: false,
          localGradleErrors: const <GradleHandledError>[],
        );
      }, throwsToolExit());

      final List<String> actualGradlewCall = verify(
        mockProcessManager.start(
            captureAny,
            environment: anyNamed('environment'),
            workingDirectory: anyNamed('workingDirectory')
        ),
      ).captured.last as List<String>;

      expect(actualGradlewCall, contains('/android/gradlew'));
      expect(actualGradlewCall, contains('-Plocal-engine-out=out/android_arm64'));
      expect(actualGradlewCall, contains('-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0'));
      expect(actualGradlewCall, contains('-Plocal-engine-build-mode=release'));

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      AndroidStudio: () => mockAndroidStudio,
      Artifacts: () => mockArtifacts,
      Cache: () => cache,
      Platform: () => android,
      FileSystem: () => fileSystem,
      ProcessManager: () => mockProcessManager,
    });

    testUsingContext(
        'build apk uses selected local engine,the engine abi is x86', () async {
      when(mockArtifacts.getArtifactPath(Artifact.flutterFramework,
          platform: anyNamed('platform'), mode: anyNamed('mode'))).thenReturn('engine');
      when(mockArtifacts.engineOutPath).thenReturn(fileSystem.path.join('out', 'android_x86'));

      fileSystem.file('out/android_x86/flutter_embedding_release.pom')
        ..createSync(recursive: true)
        ..writeAsStringSync('''
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version>
  <dependencies>
  </dependencies>
</project>
''');
      fileSystem.file('out/android_x86/x86_release.pom').createSync(recursive: true);
      fileSystem.file('out/android_x86/x86_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_x86/flutter_embedding_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_x86/flutter_embedding_release.pom').createSync(recursive: true);

      fileSystem.file('android/gradlew').createSync(recursive: true);

      fileSystem.directory('android')
          .childFile('gradle.properties')
          .createSync(recursive: true);

      fileSystem.file('android/build.gradle')
          .createSync(recursive: true);

      fileSystem.directory('android')
          .childDirectory('app')
          .childFile('build.gradle')
        ..createSync(recursive: true)
        ..writeAsStringSync('apply from: irrelevant/flutter.gradle');

      // Let any process start. Assert after.
      when(mockProcessManager.run(
        any,
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenAnswer((_) async => ProcessResult(1, 0, '', ''));

      when(mockProcessManager.start(any,
          workingDirectory: anyNamed('workingDirectory'),
          environment: anyNamed('environment')))
          .thenAnswer((_) {
        return Future<Process>.value(
            createMockProcess(
              exitCode: 1,
            )
        );
      });

      await expectLater(() async {
        await buildGradleApp(
          project: FlutterProject.current(),
          androidBuildInfo: const AndroidBuildInfo(
            BuildInfo(
              BuildMode.release,
              null,
              treeShakeIcons: false,
            ),
          ),
          target: 'lib/main.dart',
          isBuildingBundle: false,
          localGradleErrors: const <GradleHandledError>[],
        );
      }, throwsToolExit());

      final List<String> actualGradlewCall = verify(
        mockProcessManager.start(
            captureAny,
            environment: anyNamed('environment'),
            workingDirectory: anyNamed('workingDirectory')
        ),
      ).captured.last as List<String>;

      expect(actualGradlewCall, contains('/android/gradlew'));
      expect(actualGradlewCall, contains('-Plocal-engine-out=out/android_x86'));
      expect(actualGradlewCall, contains('-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0'));
      expect(actualGradlewCall, contains('-Plocal-engine-build-mode=release'));

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      AndroidStudio: () => mockAndroidStudio,
      Artifacts: () => mockArtifacts,
      Cache: () => cache,
      Platform: () => android,
      FileSystem: () => fileSystem,
      ProcessManager: () => mockProcessManager,
    });

    testUsingContext(
        'build apk uses selected local engine,the engine abi is x64', () async {
      when(mockArtifacts.getArtifactPath(Artifact.flutterFramework,
          platform: anyNamed('platform'), mode: anyNamed('mode'))).thenReturn('engine');
      when(mockArtifacts.engineOutPath).thenReturn(fileSystem.path.join('out', 'android_x64'));

      fileSystem.file('out/android_x64/flutter_embedding_release.pom')
        ..createSync(recursive: true)
        ..writeAsStringSync('''
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version>
  <dependencies>
  </dependencies>
</project>
''');
      fileSystem.file('out/android_x64/x86_64_release.pom').createSync(recursive: true);
      fileSystem.file('out/android_x64/x86_64_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_x64/flutter_embedding_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_x64/flutter_embedding_release.pom').createSync(recursive: true);

      fileSystem.file('android/gradlew').createSync(recursive: true);

      fileSystem.directory('android')
          .childFile('gradle.properties')
          .createSync(recursive: true);

      fileSystem.file('android/build.gradle')
          .createSync(recursive: true);

      fileSystem.directory('android')
          .childDirectory('app')
          .childFile('build.gradle')
        ..createSync(recursive: true)
        ..writeAsStringSync('apply from: irrelevant/flutter.gradle');

      // Let any process start. Assert after.
      when(mockProcessManager.run(
        any,
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenAnswer((_) async => ProcessResult(1, 0, '', ''));

      when(mockProcessManager.start(any,
          workingDirectory: anyNamed('workingDirectory'),
          environment: anyNamed('environment')))
          .thenAnswer((_) {
        return Future<Process>.value(
            createMockProcess(
              exitCode: 1,
            )
        );
      });

      await expectLater(() async {
        await buildGradleApp(
          project: FlutterProject.current(),
          androidBuildInfo: const AndroidBuildInfo(
            BuildInfo(
              BuildMode.release,
              null,
              treeShakeIcons: false,
            ),
          ),
          target: 'lib/main.dart',
          isBuildingBundle: false,
          localGradleErrors: const <GradleHandledError>[],
        );
      }, throwsToolExit());

      final List<String> actualGradlewCall = verify(
        mockProcessManager.start(
            captureAny,
            environment: anyNamed('environment'),
            workingDirectory: anyNamed('workingDirectory')
        ),
      ).captured.last as List<String>;

      expect(actualGradlewCall, contains('/android/gradlew'));
      expect(actualGradlewCall, contains('-Plocal-engine-out=out/android_x64'));
      expect(actualGradlewCall, contains('-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0'));
      expect(actualGradlewCall, contains('-Plocal-engine-build-mode=release'));

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      AndroidStudio: () => mockAndroidStudio,
      Artifacts: () => mockArtifacts,
      Cache: () => cache,
      Platform: () => android,
      FileSystem: () => fileSystem,
      ProcessManager: () => mockProcessManager,
    });

    testUsingContext('build aar uses selected local engine,the engine abi is arm', () async {
1994 1995
      when(mockArtifacts.getArtifactPath(Artifact.flutterFramework,
          platform: TargetPlatform.android_arm, mode: anyNamed('mode'))).thenReturn('engine');
1996
      when(mockArtifacts.engineOutPath).thenReturn(fileSystem.path.join('out', 'android_arm'));
1997

1998
      fileSystem.file('out/android_arm/flutter_embedding_release.pom')
1999
        ..createSync(recursive: true)
2000 2001
        ..writeAsStringSync('''
<?xml version="1.0" encoding="UTF-8"?>
2002 2003 2004 2005 2006 2007
<project>
  <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version>
  <dependencies>
  </dependencies>
</project>
''');
2008 2009 2010 2011
      fileSystem.file('out/android_arm/armeabi_v7a_release.pom').createSync(recursive: true);
      fileSystem.file('out/android_arm/armeabi_v7a_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_arm/flutter_embedding_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_arm/flutter_embedding_release.pom').createSync(recursive: true);
2012

2013
      final File manifestFile = fileSystem.file('pubspec.yaml');
2014 2015 2016 2017 2018 2019 2020 2021
      manifestFile.createSync(recursive: true);
      manifestFile.writeAsStringSync('''
        flutter:
          module:
            androidPackage: com.example.test
        '''
      );

2022 2023 2024 2025 2026 2027
      fileSystem.directory('.android/gradle')
        .createSync(recursive: true);

      fileSystem.directory('.android/gradle/wrapper')
        .createSync(recursive: true);

2028
      fileSystem.file('.android/gradlew').createSync(recursive: true);
2029

2030
      fileSystem.file('.android/gradle.properties')
Emmanuel Garcia's avatar
Emmanuel Garcia committed
2031 2032
        .writeAsStringSync('irrelevant');

2033
      fileSystem.file('.android/build.gradle')
2034 2035
        .createSync(recursive: true);

2036
      // Let any process start. Assert after.
2037
      when(mockProcessManager.run(
2038 2039
        any,
        environment: anyNamed('environment'),
2040
        workingDirectory: anyNamed('workingDirectory'),
2041 2042
      )).thenAnswer((_) async => ProcessResult(1, 0, '', ''));

2043
      fileSystem.directory('build/outputs/repo').createSync(recursive: true);
2044

2045 2046
      when(fileSystemUtils.copyDirectorySync(any, any)).thenReturn(null);

2047
      await buildGradleAar(
2048
        androidBuildInfo: const AndroidBuildInfo(BuildInfo(BuildMode.release, null, treeShakeIcons: false)),
2049
        project: FlutterProject.current(),
2050
        outputDirectory: fileSystem.directory('build/'),
2051
        target: '',
2052
        buildNumber: '2.0',
2053 2054
      );

2055 2056 2057 2058 2059 2060
      final List<String> actualGradlewCall = verify(
        mockProcessManager.run(
          captureAny,
          environment: anyNamed('environment'),
          workingDirectory: anyNamed('workingDirectory'),
        ),
2061
      ).captured.last as List<String>;
2062

2063
      expect(actualGradlewCall, contains('/.android/gradlew'));
2064 2065 2066
      expect(actualGradlewCall, contains('-Plocal-engine-out=out/android_arm'));
      expect(actualGradlewCall, contains('-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0'));
      expect(actualGradlewCall, contains('-Plocal-engine-build-mode=release'));
2067
      expect(actualGradlewCall, contains('-PbuildNumber=2.0'));
2068

2069 2070 2071 2072 2073 2074 2075 2076
      // Verify the local engine repo is copied into the generated Maven repo.
      final List<dynamic> copyDirectoryArguments = verify(
        fileSystemUtils.copyDirectorySync(captureAny, captureAny)
      ).captured;

      expect(copyDirectoryArguments.length, 2);
      expect((copyDirectoryArguments.first as Directory).path, '/.tmp_rand0/flutter_tool_local_engine_repo.rand0');
      expect((copyDirectoryArguments.last as Directory).path, 'build/outputs/repo');
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      AndroidStudio: () => mockAndroidStudio,
      Artifacts: () => mockArtifacts,
      Cache: () => cache,
      Platform: () => android,
      FileSystem: () => fileSystem,
      FileSystemUtils: () => fileSystemUtils,
      ProcessManager: () => mockProcessManager,
    });

    testUsingContext(
        'build aar uses selected local engine,the engine abi is arm64', () async {
      when(mockArtifacts.getArtifactPath(Artifact.flutterFramework,
          platform: anyNamed('platform'), mode: anyNamed('mode'))).thenReturn('engine');
      when(mockArtifacts.engineOutPath).thenReturn(fileSystem.path.join('out', 'android_arm64'));

      fileSystem.file('out/android_arm64/flutter_embedding_release.pom')
        ..createSync(recursive: true)
        ..writeAsStringSync('''
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version>
  <dependencies>
  </dependencies>
</project>
''');
      fileSystem.file('out/android_arm64/arm64_v8a_release.pom').createSync(recursive: true);
      fileSystem.file('out/android_arm64/arm64_v8a_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_arm64/flutter_embedding_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_arm64/flutter_embedding_release.pom').createSync(recursive: true);

      final File manifestFile = fileSystem.file('pubspec.yaml');
      manifestFile.createSync(recursive: true);
      manifestFile.writeAsStringSync('''
        flutter:
          module:
            androidPackage: com.example.test
        '''
      );

      fileSystem.directory('.android/gradle')
          .createSync(recursive: true);

      fileSystem.directory('.android/gradle/wrapper')
          .createSync(recursive: true);

      fileSystem.file('.android/gradlew').createSync(recursive: true);

      fileSystem.file('.android/gradle.properties')
          .writeAsStringSync('irrelevant');

      fileSystem.file('.android/build.gradle')
          .createSync(recursive: true);

      // Let any process start. Assert after.
      when(mockProcessManager.run(
        any,
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenAnswer((_) async => ProcessResult(1, 0, '', ''));

      fileSystem.directory('build/outputs/repo').createSync(recursive: true);

      when(fileSystemUtils.copyDirectorySync(any, any)).thenReturn(null);

      await buildGradleAar(
        androidBuildInfo: const AndroidBuildInfo(
            BuildInfo(BuildMode.release, null, treeShakeIcons: false)),
        project: FlutterProject.current(),
        outputDirectory: fileSystem.directory('build/'),
        target: '',
        buildNumber: '2.0',
      );

      final List<String> actualGradlewCall = verify(
        mockProcessManager.run(
          captureAny,
          environment: anyNamed('environment'),
          workingDirectory: anyNamed('workingDirectory'),
        ),
      ).captured.last as List<String>;

      expect(actualGradlewCall, contains('/.android/gradlew'));
      expect(actualGradlewCall, contains('-Plocal-engine-out=out/android_arm64'));
      expect(actualGradlewCall, contains('-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0'));
      expect(actualGradlewCall, contains('-Plocal-engine-build-mode=release'));
      expect(actualGradlewCall, contains('-PbuildNumber=2.0'));

      // Verify the local engine repo is copied into the generated Maven repo.
      final List<dynamic> copyDirectoryArguments = verify(
          fileSystemUtils.copyDirectorySync(captureAny, captureAny)
      ).captured;

      expect(copyDirectoryArguments.length, 2);
      expect((copyDirectoryArguments.first as Directory).path, '/.tmp_rand0/flutter_tool_local_engine_repo.rand0');
      expect((copyDirectoryArguments.last as Directory).path, 'build/outputs/repo');

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      AndroidStudio: () => mockAndroidStudio,
      Artifacts: () => mockArtifacts,
      Cache: () => cache,
      Platform: () => android,
      FileSystem: () => fileSystem,
      FileSystemUtils: () => fileSystemUtils,
      ProcessManager: () => mockProcessManager,
    });

    testUsingContext(
        'build aar uses selected local engine,the engine abi is x86', () async {
      when(mockArtifacts.getArtifactPath(Artifact.flutterFramework,
          platform: anyNamed('platform'), mode: anyNamed('mode'))).thenReturn('engine');
      when(mockArtifacts.engineOutPath).thenReturn(fileSystem.path.join('out', 'android_x86'));

      fileSystem.file('out/android_x86/flutter_embedding_release.pom')
        ..createSync(recursive: true)
        ..writeAsStringSync('''
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version>
  <dependencies>
  </dependencies>
</project>
''');
      fileSystem.file('out/android_x86/x86_release.pom').createSync(recursive: true);
      fileSystem.file('out/android_x86/x86_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_x86/flutter_embedding_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_x86/flutter_embedding_release.pom').createSync(recursive: true);

      final File manifestFile = fileSystem.file('pubspec.yaml');
      manifestFile.createSync(recursive: true);
      manifestFile.writeAsStringSync('''
        flutter:
          module:
            androidPackage: com.example.test
        '''
      );

      fileSystem.directory('.android/gradle')
          .createSync(recursive: true);

      fileSystem.directory('.android/gradle/wrapper')
          .createSync(recursive: true);

      fileSystem.file('.android/gradlew').createSync(recursive: true);

      fileSystem.file('.android/gradle.properties')
          .writeAsStringSync('irrelevant');

      fileSystem.file('.android/build.gradle')
          .createSync(recursive: true);

      // Let any process start. Assert after.
      when(mockProcessManager.run(
        any,
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenAnswer((_) async => ProcessResult(1, 0, '', ''));

      fileSystem.directory('build/outputs/repo').createSync(recursive: true);

      when(fileSystemUtils.copyDirectorySync(any, any)).thenReturn(null);

      await buildGradleAar(
        androidBuildInfo: const AndroidBuildInfo(
            BuildInfo(BuildMode.release, null, treeShakeIcons: false)),
        project: FlutterProject.current(),
        outputDirectory: fileSystem.directory('build/'),
        target: '',
        buildNumber: '2.0',
      );

      final List<String> actualGradlewCall = verify(
        mockProcessManager.run(
          captureAny,
          environment: anyNamed('environment'),
          workingDirectory: anyNamed('workingDirectory'),
        ),
      ).captured.last as List<String>;

      expect(actualGradlewCall, contains('/.android/gradlew'));
      expect(actualGradlewCall, contains('-Plocal-engine-out=out/android_x86'));
      expect(actualGradlewCall, contains('-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0'));
      expect(actualGradlewCall, contains('-Plocal-engine-build-mode=release'));
      expect(actualGradlewCall, contains('-PbuildNumber=2.0'));

      // Verify the local engine repo is copied into the generated Maven repo.
      final List<dynamic> copyDirectoryArguments = verify(
          fileSystemUtils.copyDirectorySync(captureAny, captureAny)
      ).captured;

      expect(copyDirectoryArguments.length, 2);
      expect((copyDirectoryArguments.first as Directory).path, '/.tmp_rand0/flutter_tool_local_engine_repo.rand0');
      expect((copyDirectoryArguments.last as Directory).path, 'build/outputs/repo');

    }, overrides: <Type, Generator>{
      AndroidSdk: () => mockAndroidSdk,
      AndroidStudio: () => mockAndroidStudio,
      Artifacts: () => mockArtifacts,
      Cache: () => cache,
      Platform: () => android,
      FileSystem: () => fileSystem,
      FileSystemUtils: () => fileSystemUtils,
      ProcessManager: () => mockProcessManager,
    });

    testUsingContext(
        'build aar uses selected local engine,the engine abi is x64', () async {
      when(mockArtifacts.getArtifactPath(Artifact.flutterFramework,
          platform: anyNamed('platform'), mode: anyNamed('mode'))).thenReturn('engine');
      when(mockArtifacts.engineOutPath).thenReturn(fileSystem.path.join('out', 'android_x64'));

      fileSystem.file('out/android_x64/flutter_embedding_release.pom')
        ..createSync(recursive: true)
        ..writeAsStringSync('''
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version>
  <dependencies>
  </dependencies>
</project>
''');
      fileSystem.file('out/android_x64/x86_64_release.pom').createSync(recursive: true);
      fileSystem.file('out/android_x64/x86_64_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_x64/flutter_embedding_release.jar').createSync(recursive: true);
      fileSystem.file('out/android_x64/flutter_embedding_release.pom').createSync(recursive: true);

      final File manifestFile = fileSystem.file('pubspec.yaml');
      manifestFile.createSync(recursive: true);
      manifestFile.writeAsStringSync('''
        flutter:
          module:
            androidPackage: com.example.test
        '''
      );

      fileSystem.directory('.android/gradle')
          .createSync(recursive: true);

      fileSystem.directory('.android/gradle/wrapper')
          .createSync(recursive: true);

      fileSystem.file('.android/gradlew').createSync(recursive: true);

      fileSystem.file('.android/gradle.properties')
          .writeAsStringSync('irrelevant');

      fileSystem.file('.android/build.gradle')
          .createSync(recursive: true);

      // Let any process start. Assert after.
      when(mockProcessManager.run(
        any,
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenAnswer((_) async => ProcessResult(1, 0, '', ''));

      fileSystem.directory('build/outputs/repo').createSync(recursive: true);

      when(fileSystemUtils.copyDirectorySync(any, any)).thenReturn(null);

      await buildGradleAar(
        androidBuildInfo: const AndroidBuildInfo(
            BuildInfo(BuildMode.release, null, treeShakeIcons: false)),
        project: FlutterProject.current(),
        outputDirectory: fileSystem.directory('build/'),
        target: '',
        buildNumber: '2.0',
      );

      final List<String> actualGradlewCall = verify(
        mockProcessManager.run(
          captureAny,
          environment: anyNamed('environment'),
          workingDirectory: anyNamed('workingDirectory'),
        ),
      ).captured.last as List<String>;

      expect(actualGradlewCall, contains('/.android/gradlew'));
      expect(actualGradlewCall, contains('-Plocal-engine-out=out/android_x64'));
      expect(actualGradlewCall, contains('-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0'));
      expect(actualGradlewCall, contains('-Plocal-engine-build-mode=release'));
      expect(actualGradlewCall, contains('-PbuildNumber=2.0'));

      // Verify the local engine repo is copied into the generated Maven repo.
      final List<dynamic> copyDirectoryArguments = verify(
          fileSystemUtils.copyDirectorySync(captureAny, captureAny)
      ).captured;

      expect(copyDirectoryArguments.length, 2);
      expect((copyDirectoryArguments.first as Directory).path, '/.tmp_rand0/flutter_tool_local_engine_repo.rand0');
      expect((copyDirectoryArguments.last as Directory).path, 'build/outputs/repo');
2371

2372
    }, overrides: <Type, Generator>{
2373 2374 2375 2376 2377
      AndroidSdk: () => mockAndroidSdk,
      AndroidStudio: () => mockAndroidStudio,
      Artifacts: () => mockArtifacts,
      Cache: () => cache,
      Platform: () => android,
2378
      FileSystem: () => fileSystem,
2379
      FileSystemUtils: () => fileSystemUtils,
2380
      ProcessManager: () => mockProcessManager,
2381
    });
2382
  });
2383 2384

  group('printHowToConsumeAar', () {
2385 2386 2387 2388 2389 2390 2391 2392 2393
    BufferLogger logger;
    FileSystem fileSystem;

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

    testWithoutContext('stdout contains release, debug and profile', () async {
2394 2395 2396
      printHowToConsumeAar(
        buildModes: const <String>{'release', 'debug', 'profile'},
        androidPackage: 'com.mycompany',
2397
        repoDirectory: fileSystem.directory('build/'),
2398
        buildNumber: '2.2',
2399 2400
        logger: logger,
        fileSystem: fileSystem,
2401 2402 2403
      );

      expect(
2404
        logger.statusText,
2405 2406 2407 2408 2409 2410
        contains(
          '\n'
          'Consuming the Module\n'
          '  1. Open <host>/app/build.gradle\n'
          '  2. Ensure you have the repositories configured, otherwise add them:\n'
          '\n'
2411
          '      String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"\n'
2412 2413
          '      repositories {\n'
          '        maven {\n'
2414
          "            url 'build/'\n"
2415 2416
          '        }\n'
          '        maven {\n'
2417
          "            url '\$storageUrl/download.flutter.io'\n"
2418 2419 2420 2421 2422 2423
          '        }\n'
          '      }\n'
          '\n'
          '  3. Make the host app depend on the Flutter module:\n'
          '\n'
          '    dependencies {\n'
2424 2425 2426
          "      releaseImplementation 'com.mycompany:flutter_release:2.2'\n"
          "      debugImplementation 'com.mycompany:flutter_debug:2.2'\n"
          "      profileImplementation 'com.mycompany:flutter_profile:2.2'\n"
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444
          '    }\n'
          '\n'
          '\n'
          '  4. Add the `profile` build type:\n'
          '\n'
          '    android {\n'
          '      buildTypes {\n'
          '        profile {\n'
          '          initWith debug\n'
          '        }\n'
          '      }\n'
          '    }\n'
          '\n'
          'To learn more, visit https://flutter.dev/go/build-aar\n'
        )
      );
    });

2445
    testWithoutContext('stdout contains release', () async {
2446 2447 2448
      printHowToConsumeAar(
        buildModes: const <String>{'release'},
        androidPackage: 'com.mycompany',
2449 2450 2451
        repoDirectory: fileSystem.directory('build/'),
        logger: logger,
        fileSystem: fileSystem,
2452 2453 2454
      );

      expect(
2455
        logger.statusText,
2456 2457 2458 2459 2460 2461
        contains(
          '\n'
          'Consuming the Module\n'
          '  1. Open <host>/app/build.gradle\n'
          '  2. Ensure you have the repositories configured, otherwise add them:\n'
          '\n'
2462
          '      String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"\n'
2463 2464
          '      repositories {\n'
          '        maven {\n'
2465
          "            url 'build/'\n"
2466 2467
          '        }\n'
          '        maven {\n'
2468
          "            url '\$storageUrl/download.flutter.io'\n"
2469 2470 2471 2472 2473 2474
          '        }\n'
          '      }\n'
          '\n'
          '  3. Make the host app depend on the Flutter module:\n'
          '\n'
          '    dependencies {\n'
2475
          "      releaseImplementation 'com.mycompany:flutter_release:1.0'\n"
2476 2477 2478 2479 2480 2481 2482
          '    }\n'
          '\n'
          'To learn more, visit https://flutter.dev/go/build-aar\n'
        )
      );
    });

2483
    testWithoutContext('stdout contains debug', () async {
2484 2485 2486
      printHowToConsumeAar(
        buildModes: const <String>{'debug'},
        androidPackage: 'com.mycompany',
2487 2488 2489
        repoDirectory: fileSystem.directory('build/'),
        logger: logger,
        fileSystem: fileSystem,
2490 2491 2492
      );

      expect(
2493
        logger.statusText,
2494 2495 2496 2497 2498 2499
        contains(
          '\n'
          'Consuming the Module\n'
          '  1. Open <host>/app/build.gradle\n'
          '  2. Ensure you have the repositories configured, otherwise add them:\n'
          '\n'
2500
          '      String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"\n'
2501 2502
          '      repositories {\n'
          '        maven {\n'
2503
          "            url 'build/'\n"
2504 2505
          '        }\n'
          '        maven {\n'
2506
          "            url '\$storageUrl/download.flutter.io'\n"
2507 2508 2509 2510 2511 2512
          '        }\n'
          '      }\n'
          '\n'
          '  3. Make the host app depend on the Flutter module:\n'
          '\n'
          '    dependencies {\n'
2513
          "      debugImplementation 'com.mycompany:flutter_debug:1.0'\n"
2514 2515 2516 2517 2518 2519 2520
          '    }\n'
          '\n'
          'To learn more, visit https://flutter.dev/go/build-aar\n'
        )
      );
    });

2521
    testWithoutContext('stdout contains profile', () async {
2522 2523 2524
      printHowToConsumeAar(
        buildModes: const <String>{'profile'},
        androidPackage: 'com.mycompany',
2525
        repoDirectory: fileSystem.directory('build/'),
2526
        buildNumber: '1.0',
2527 2528
        logger: logger,
        fileSystem: fileSystem,
2529 2530 2531
      );

      expect(
2532
        logger.statusText,
2533 2534 2535 2536 2537 2538
        contains(
          '\n'
          'Consuming the Module\n'
          '  1. Open <host>/app/build.gradle\n'
          '  2. Ensure you have the repositories configured, otherwise add them:\n'
          '\n'
2539
          '      String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"\n'
2540 2541
          '      repositories {\n'
          '        maven {\n'
2542
          "            url 'build/'\n"
2543 2544
          '        }\n'
          '        maven {\n'
2545
          "            url '\$storageUrl/download.flutter.io'\n"
2546 2547 2548 2549 2550 2551
          '        }\n'
          '      }\n'
          '\n'
          '  3. Make the host app depend on the Flutter module:\n'
          '\n'
          '    dependencies {\n'
2552
          "      profileImplementation 'com.mycompany:flutter_profile:1.0'\n"
2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
          '    }\n'
          '\n'
          '\n'
          '  4. Add the `profile` build type:\n'
          '\n'
          '    android {\n'
          '      buildTypes {\n'
          '        profile {\n'
          '          initWith debug\n'
          '        }\n'
          '      }\n'
          '    }\n'
          '\n'
          'To learn more, visit https://flutter.dev/go/build-aar\n'
        )
      );
    });
  });
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582

  test('Current settings.gradle is in our legacy settings.gradle file set', () {
    // If this test fails, you probably edited templates/app/android.tmpl.
    // That's fine, but you now need to add a copy of that file to gradle/settings.gradle.legacy_versions, separated
    // from the previous versions by a line that just says ";EOF".
    final File templateSettingsDotGradle = globals.fs.file(globals.fs.path.join(Cache.flutterRoot, 'packages', 'flutter_tools', 'templates', 'app', 'android.tmpl', 'settings.gradle'));
    final File legacySettingsDotGradleFiles = globals.fs.file(globals.fs.path.join(Cache.flutterRoot, 'packages','flutter_tools', 'gradle', 'settings.gradle.legacy_versions'));
    expect(
      legacySettingsDotGradleFiles.readAsStringSync().split(';EOF').map<String>((String body) => body.trim()),
      contains(templateSettingsDotGradle.readAsStringSync().trim()),
    );
  });
2583
}
2584

2585
/// Generates a fake app bundle at the location [directoryName]/[fileName].
2586
FlutterProject generateFakeAppBundle(String directoryName, String fileName, FileSystem fileSystem) {
2587 2588 2589 2590 2591
  final FlutterProject project = MockFlutterProject();
  final AndroidProject androidProject = MockAndroidProject();

  when(project.isModule).thenReturn(false);
  when(project.android).thenReturn(androidProject);
2592
  when(androidProject.buildDirectory).thenReturn(fileSystem.directory('irrelevant'));
2593 2594 2595 2596

  final Directory bundleDirectory = getBundleDirectory(project);
  bundleDirectory
    .childDirectory(directoryName)
2597
    .createSync(recursive: true);
2598 2599 2600 2601 2602 2603

  bundleDirectory
    .childDirectory(directoryName)
    .childFile(fileName)
    .createSync();
  return project;
2604 2605
}

2606
FakePlatform fakePlatform(String name) {
2607 2608 2609 2610 2611
  return FakePlatform(
    environment: <String, String>{'HOME': '/path/to/home'},
    operatingSystem: name,
    stdoutSupportsAnsi: false,
  );
2612 2613
}

2614 2615
class FakeGradleUtils extends GradleUtils {
  @override
2616
  String getExecutable(FlutterProject project) {
2617 2618 2619 2620 2621
    return 'gradlew';
  }
}

class MockAndroidSdk extends Mock implements AndroidSdk {}
2622
class MockAndroidProject extends Mock implements AndroidProject {}
Emmanuel Garcia's avatar
Emmanuel Garcia committed
2623 2624 2625
class MockAndroidStudio extends Mock implements AndroidStudio {}
class MockDirectory extends Mock implements Directory {}
class MockFile extends Mock implements File {}
2626
class MockFileSystemUtils extends Mock implements FileSystemUtils {}
2627
class MockFlutterProject extends Mock implements FlutterProject {}
2628 2629 2630
class MockLocalEngineArtifacts extends Mock implements LocalEngineArtifacts {}
class MockProcessManager extends Mock implements ProcessManager {}
class MockXcodeProjectInterpreter extends Mock implements XcodeProjectInterpreter {}
2631
class MockUsage extends Mock implements Usage {}