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

import 'package:args/command_runner.dart';
6
import 'package:flutter_tools/src/android/android_builder.dart';
7
import 'package:flutter_tools/src/android/android_sdk.dart';
8
import 'package:flutter_tools/src/android/android_studio.dart';
9
import 'package:flutter_tools/src/base/file_system.dart';
10
import 'package:flutter_tools/src/base/logger.dart';
11
import 'package:flutter_tools/src/build_info.dart';
12 13
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/build_aar.dart';
14
import 'package:flutter_tools/src/features.dart';
15
import 'package:flutter_tools/src/globals.dart' as globals;
16
import 'package:flutter_tools/src/project.dart';
17
import 'package:flutter_tools/src/reporting/reporting.dart';
18
import 'package:test/fake.dart';
19

20
import '../../src/android_common.dart';
21 22
import '../../src/common.dart';
import '../../src/context.dart';
23
import '../../src/fake_process_manager.dart';
24
import '../../src/fakes.dart' hide FakeFlutterProjectFactory;
25
import '../../src/test_flutter_command_runner.dart';
26 27 28 29

void main() {
  Cache.disableLocking();

30
  Future<BuildAarCommand> runCommandIn(String target, { List<String>? arguments }) async {
31 32 33 34 35 36
    final BuildAarCommand command = BuildAarCommand(
      androidSdk: FakeAndroidSdk(),
      fileSystem: globals.fs,
      logger: BufferLogger.test(),
      verboseHelp: false,
    );
37 38 39 40 41 42 43 44 45 46
    final CommandRunner<void> runner = createTestCommandRunner(command);
    await runner.run(<String>[
      'aar',
      '--no-pub',
      ...?arguments,
      target,
    ]);
    return command;
  }

47
  group('Usage', () {
48 49
    late Directory tempDir;
    late TestUsage testUsage;
50 51

    setUp(() {
52
      testUsage = TestUsage();
53
      tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.');
54 55 56 57 58 59 60 61 62 63 64
    });

    tearDown(() {
      tryToDelete(tempDir);
    });

    testUsingContext('indicate that project is a module', () async {
      final String projectPath = await createProject(tempDir,
          arguments: <String>['--no-pub', '--template=module']);

      final BuildAarCommand command = await runCommandIn(projectPath);
65
      expect((await command.usageValues).commandBuildAarProjectType, 'module');
66 67

    }, overrides: <Type, Generator>{
68
      AndroidBuilder: () => FakeAndroidBuilder(),
69
    });
70 71 72 73 74 75

    testUsingContext('indicate that project is a plugin', () async {
      final String projectPath = await createProject(tempDir,
          arguments: <String>['--no-pub', '--template=plugin', '--project-name=aar_test']);

      final BuildAarCommand command = await runCommandIn(projectPath);
76
      expect((await command.usageValues).commandBuildAarProjectType, 'plugin');
77 78

    }, overrides: <Type, Generator>{
79
      AndroidBuilder: () => FakeAndroidBuilder(),
80
    });
81 82 83 84 85 86 87

    testUsingContext('indicate the target platform', () async {
      final String projectPath = await createProject(tempDir,
          arguments: <String>['--no-pub', '--template=module']);

      final BuildAarCommand command = await runCommandIn(projectPath,
          arguments: <String>['--target-platform=android-arm']);
88
      expect((await command.usageValues).commandBuildAarTargetPlatform, 'android-arm');
89 90

    }, overrides: <Type, Generator>{
91
      AndroidBuilder: () => FakeAndroidBuilder(),
92
    });
93 94 95 96 97 98 99 100

    testUsingContext('logs success', () async {
      final String projectPath = await createProject(tempDir,
          arguments: <String>['--no-pub', '--template=module']);

      await runCommandIn(projectPath,
          arguments: <String>['--target-platform=android-arm']);

101 102 103 104 105 106 107
      expect(testUsage.events, contains(
        const TestUsageEvent(
          'tool-command-result',
          'aar',
          label: 'success',
        ),
      ));
108 109 110
    },
    overrides: <Type, Generator>{
      AndroidBuilder: () => FakeAndroidBuilder(),
111
      Usage: () => testUsage,
112
    });
113
  });
114

115
  group('flag parsing', () {
116 117
    late Directory tempDir;
    late FakeAndroidBuilder fakeAndroidBuilder;
118 119

    setUp(() {
120
      fakeAndroidBuilder = FakeAndroidBuilder();
121 122 123 124 125 126 127 128 129 130 131 132
      tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_build_aar_test.');
    });

    tearDown(() {
      tryToDelete(tempDir);
    });

    testUsingContext('defaults', () async {
      final String projectPath = await createProject(tempDir,
        arguments: <String>['--no-pub']);
      await runCommandIn(projectPath);

133 134
      expect(fakeAndroidBuilder.buildNumber, '1.0');
      expect(fakeAndroidBuilder.androidBuildInfo.length, 3);
135 136

      final List<BuildMode> buildModes = <BuildMode>[];
137
      for (final AndroidBuildInfo androidBuildInfo in fakeAndroidBuilder.androidBuildInfo) {
138 139
        final BuildInfo buildInfo = androidBuildInfo.buildInfo;
        buildModes.add(buildInfo.mode);
140 141
        if (buildInfo.mode.isPrecompiled) {
          expect(buildInfo.treeShakeIcons, isTrue);
142
          expect(buildInfo.trackWidgetCreation, isTrue);
143 144
        } else {
          expect(buildInfo.treeShakeIcons, isFalse);
145
          expect(buildInfo.trackWidgetCreation, isTrue);
146
        }
147 148 149 150 151 152 153 154
        expect(buildInfo.flavor, isNull);
        expect(buildInfo.splitDebugInfoPath, isNull);
        expect(buildInfo.dartObfuscation, isFalse);
        expect(androidBuildInfo.targetArchs, <AndroidArch>[AndroidArch.armeabi_v7a, AndroidArch.arm64_v8a, AndroidArch.x86_64]);
      }
      expect(buildModes.length, 3);
      expect(buildModes, containsAll(<BuildMode>[BuildMode.debug, BuildMode.profile, BuildMode.release]));
    }, overrides: <Type, Generator>{
155
      AndroidBuilder: () => fakeAndroidBuilder,
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    });

    testUsingContext('parses flags', () async {
      final String projectPath = await createProject(tempDir,
        arguments: <String>['--no-pub']);
      await runCommandIn(
        projectPath,
        arguments: <String>[
          '--no-debug',
          '--no-profile',
          '--target-platform',
          'android-x86',
          '--tree-shake-icons',
          '--flavor',
          'free',
          '--build-number',
          '200',
          '--split-debug-info',
          '/project-name/v1.2.3/',
          '--obfuscate',
176
          '--dart-define=foo=bar',
177 178 179
        ],
      );

180
      expect(fakeAndroidBuilder.buildNumber, '200');
181

182
      final AndroidBuildInfo androidBuildInfo = fakeAndroidBuilder.androidBuildInfo.single;
183 184 185 186 187 188 189 190
      expect(androidBuildInfo.targetArchs, <AndroidArch>[AndroidArch.x86]);

      final BuildInfo buildInfo = androidBuildInfo.buildInfo;
      expect(buildInfo.mode, BuildMode.release);
      expect(buildInfo.treeShakeIcons, isTrue);
      expect(buildInfo.flavor, 'free');
      expect(buildInfo.splitDebugInfoPath, '/project-name/v1.2.3/');
      expect(buildInfo.dartObfuscation, isTrue);
191
      expect(buildInfo.dartDefines.contains('foo=bar'), isTrue);
192
      expect(buildInfo.nullSafetyMode, NullSafetyMode.sound);
193
    }, overrides: <Type, Generator>{
194
      AndroidBuilder: () => fakeAndroidBuilder,
195 196 197
    });
  });

198
  group('Gradle', () {
199 200 201 202 203
    late Directory tempDir;
    late AndroidSdk mockAndroidSdk;
    late String gradlew;
    late FakeProcessManager processManager;
    late String flutterRoot;
204 205

    setUp(() {
206
      tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.');
207 208 209 210 211
      mockAndroidSdk = FakeAndroidSdk();
      gradlew = globals.fs.path.join(tempDir.path, 'flutter_project', '.android',
          globals.platform.isWindows ? 'gradlew.bat' : 'gradlew');
      processManager = FakeProcessManager.empty();
      flutterRoot = getFlutterRoot();
212 213
    });

214 215 216 217
    tearDown(() {
      tryToDelete(tempDir);
    });

218
    group('AndroidSdk', () {
219 220 221 222 223 224 225
      testUsingContext('throws throwsToolExit if AndroidSdk is null', () async {
        final String projectPath = await createProject(tempDir,
            arguments: <String>['--no-pub', '--template=module']);

        await expectLater(() async {
          await runBuildAarCommand(
            projectPath,
226
            null,
227 228 229
            arguments: <String>['--no-pub'],
          );
        }, throwsToolExit(
230
          message: 'No Android SDK found. Try setting the ANDROID_SDK_ROOT environment variable',
231 232 233 234
        ));
      },
      overrides: <Type, Generator>{
        FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir),
235
        ProcessManager: () => FakeProcessManager.any(),
236 237
      });
    });
238

239 240 241 242 243
    group('throws ToolExit', () {
      testUsingContext('main.dart not found', () async {
        await expectLater(() async {
          await runBuildAarCommand(
            'missing_project',
244
            mockAndroidSdk,
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
            arguments: <String>['--no-pub'],
          );
        }, throwsToolExit(
          message: 'main.dart does not exist',
        ));
      });

      testUsingContext('flutter project not valid', () async {
        await expectLater(() async {
          await runCommandIn(
            tempDir.path,
            arguments: <String>['--no-pub'],
          );
        }, throwsToolExit(
          message: 'is not a valid flutter project',
        ));
      });
    });

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    testUsingContext('support ExtraDartFlagOptions', () async {
      final String projectPath = await createProject(tempDir,
          arguments: <String>['--no-pub', '--template=module']);

      processManager.addCommand(FakeCommand(
        command: <String>[
          gradlew,
          '-I=${globals.fs.path.join(flutterRoot, 'packages', 'flutter_tools', 'gradle','aar_init_script.gradle')}',
          '-Pflutter-root=$flutterRoot',
          '-Poutput-dir=${globals.fs.path.join(tempDir.path, 'flutter_project', 'build', 'host')}',
          '-Pis-plugin=false',
          '-PbuildNumber=1.0',
          '-q',
          '-Ptarget=${globals.fs.path.join('lib', 'main.dart')}',
          '-Pdart-obfuscation=false',
          '-Pextra-front-end-options=foo,bar',
          '-Ptrack-widget-creation=true',
          '-Ptree-shake-icons=true',
          '-Ptarget-platform=android-arm,android-arm64,android-x64',
          'assembleAarRelease',
        ],
        exitCode: 1,
      ));

288
      await expectLater(() => runBuildAarCommand(projectPath, mockAndroidSdk, arguments: <String>[
289 290 291 292 293 294 295 296 297 298 299 300 301
        '--no-debug',
        '--no-profile',
        '--extra-front-end-options=foo',
        '--extra-front-end-options=bar',
      ]), throwsToolExit(message: 'Gradle task assembleAarRelease failed with exit code 1'));
      expect(processManager, hasNoRemainingExpectations);
    },
    overrides: <Type, Generator>{
      FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir),
      ProcessManager: () => processManager,
      FeatureFlags: () => TestFeatureFlags(isIOSEnabled: false),
      AndroidStudio: () => FakeAndroidStudio(),
    });
302
  });
303
}
304 305

Future<BuildAarCommand> runBuildAarCommand(
306
  String target, AndroidSdk? androidSdk, {
307
  List<String>? arguments,
308
}) async {
309 310 311 312 313 314
  final BuildAarCommand command = BuildAarCommand(
    androidSdk: androidSdk,
    fileSystem: globals.fs,
    logger: BufferLogger.test(),
    verboseHelp: false,
  );
315 316 317 318 319
  final CommandRunner<void> runner = createTestCommandRunner(command);
  await runner.run(<String>[
    'aar',
    '--no-pub',
    ...?arguments,
320
    globals.fs.path.join(target, 'lib', 'main.dart'),
321 322 323 324
  ]);
  return command;
}

325
class FakeAndroidBuilder extends Fake implements AndroidBuilder {
326 327 328 329 330
  late FlutterProject project;
  late Set<AndroidBuildInfo> androidBuildInfo;
  late String target;
  String? outputDirectoryPath;
  late String buildNumber;
331 332 333

  @override
  Future<void> buildAar({
334 335 336 337 338
    required FlutterProject project,
    required Set<AndroidBuildInfo> androidBuildInfo,
    required String target,
    String? outputDirectoryPath,
    required String buildNumber,
339 340 341 342 343 344 345 346
  }) async {
    this.project = project;
    this.androidBuildInfo = androidBuildInfo;
    this.target = target;
    this.outputDirectoryPath = outputDirectoryPath;
    this.buildNumber = buildNumber;
  }
}
347 348 349 350 351 352 353 354

class FakeAndroidSdk extends Fake implements AndroidSdk {
}

class FakeAndroidStudio extends Fake implements AndroidStudio {
  @override
  String get javaPath => 'java';
}