build_aar_test.dart 10.4 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:io' show Process, ProcessResult;

7
import 'package:args/command_runner.dart';
8
import 'package:flutter_tools/src/android/android_builder.dart';
9
import 'package:flutter_tools/src/android/android_sdk.dart';
10
import 'package:flutter_tools/src/base/file_system.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/project.dart';
15
import 'package:flutter_tools/src/reporting/reporting.dart';
16
import 'package:flutter_tools/src/globals.dart' as globals;
17 18
import 'package:mockito/mockito.dart';
import 'package:process/process.dart';
19

20
import '../../src/android_common.dart';
21 22
import '../../src/common.dart';
import '../../src/context.dart';
23
import '../../src/mocks.dart';
24 25 26 27

void main() {
  Cache.disableLocking();

28
  Future<BuildAarCommand> runCommandIn(String target, { List<String> arguments }) async {
29
    final BuildAarCommand command = BuildAarCommand(verboseHelp: false);
30 31 32 33 34 35 36 37 38 39
    final CommandRunner<void> runner = createTestCommandRunner(command);
    await runner.run(<String>[
      'aar',
      '--no-pub',
      ...?arguments,
      target,
    ]);
    return command;
  }

40
  group('Usage', () {
41
    Directory tempDir;
42
    Usage mockUsage;
43 44

    setUp(() {
45
      mockUsage = MockUsage();
46
      tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.');
47 48 49 50 51 52 53 54 55 56 57 58
    });

    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);
      expect(await command.usageValues,
59
          containsPair(CustomDimensions.commandBuildAarProjectType, 'module'));
60 61

    }, overrides: <Type, Generator>{
62
      AndroidBuilder: () => FakeAndroidBuilder(),
63
    });
64 65 66 67 68 69 70

    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);
      expect(await command.usageValues,
71
          containsPair(CustomDimensions.commandBuildAarProjectType, 'plugin'));
72 73

    }, overrides: <Type, Generator>{
74
      AndroidBuilder: () => FakeAndroidBuilder(),
75
    });
76 77 78 79 80 81 82 83

    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']);
      expect(await command.usageValues,
84
          containsPair(CustomDimensions.commandBuildAarTargetPlatform, 'android-arm'));
85 86

    }, overrides: <Type, Generator>{
87
      AndroidBuilder: () => FakeAndroidBuilder(),
88
    });
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

    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']);

      verify(mockUsage.sendEvent(
        'tool-command-result',
        'aar',
        label: 'success',
        value: anyNamed('value'),
        parameters: anyNamed('parameters'),
      )).called(1);
    },
    overrides: <Type, Generator>{
      AndroidBuilder: () => FakeAndroidBuilder(),
      Usage: () => mockUsage,
    });
109
  });
110

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
  group('flag parsing', () {
    Directory tempDir;
    MockAndroidBuilder mockAndroidBuilder;

    setUp(() {
      mockAndroidBuilder = MockAndroidBuilder();
      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);

      final Set<AndroidBuildInfo> androidBuildInfos = verify(mockAndroidBuilder.buildAar(
        project: anyNamed('project'),
        target: anyNamed('target'),
        androidBuildInfo: captureAnyNamed('androidBuildInfo'),
        outputDirectoryPath: anyNamed('outputDirectoryPath'),
        buildNumber: '1.0',
      )).captured[0] as Set<AndroidBuildInfo>;

      expect(androidBuildInfos.length, 3);

      final List<BuildMode> buildModes = <BuildMode>[];
      for (final AndroidBuildInfo androidBuildInfo in androidBuildInfos) {
        final BuildInfo buildInfo = androidBuildInfo.buildInfo;
        buildModes.add(buildInfo.mode);
143 144
        if (buildInfo.mode.isPrecompiled) {
          expect(buildInfo.treeShakeIcons, isTrue);
145
          expect(buildInfo.trackWidgetCreation, isTrue);
146 147
        } else {
          expect(buildInfo.treeShakeIcons, isFalse);
148
          expect(buildInfo.trackWidgetCreation, isTrue);
149
        }
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
        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>{
      AndroidBuilder: () => mockAndroidBuilder,
    });

    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',
        ],
      );

      final Set<AndroidBuildInfo> androidBuildInfos = verify(mockAndroidBuilder.buildAar(
        project: anyNamed('project'),
        target: anyNamed('target'),
        androidBuildInfo: captureAnyNamed('androidBuildInfo'),
        outputDirectoryPath: anyNamed('outputDirectoryPath'),
        buildNumber: '200',
      )).captured[0] as Set<AndroidBuildInfo>;

      final AndroidBuildInfo androidBuildInfo = androidBuildInfos.single;
      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);
    }, overrides: <Type, Generator>{
      AndroidBuilder: () => mockAndroidBuilder,
    });
  });

204 205 206 207 208 209 210 211 212 213
  group('Gradle', () {
    ProcessManager mockProcessManager;
    Directory tempDir;
    AndroidSdk mockAndroidSdk;
    Usage mockUsage;

    setUp(() {
      mockUsage = MockUsage();
      when(mockUsage.isFirstRun).thenReturn(true);

214
      tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.');
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232

      mockProcessManager = MockProcessManager();
      when(mockProcessManager.run(any,
          workingDirectory: anyNamed('workingDirectory'),
          environment: anyNamed('environment')))
        .thenAnswer((_) => Future<ProcessResult>.value(ProcessResult(0, 0, 'assembleRelease', '')));
      // Fallback with error.
      final Process process = createMockProcess(exitCode: 1);
      when(mockProcessManager.start(any,
          workingDirectory: anyNamed('workingDirectory'),
          environment: anyNamed('environment')))
        .thenAnswer((_) => Future<Process>.value(process));
      when(mockProcessManager.canRun(any)).thenReturn(false);

      mockAndroidSdk = MockAndroidSdk();
      when(mockAndroidSdk.directory).thenReturn('irrelevant');
    });

233 234 235 236
    tearDown(() {
      tryToDelete(tempDir);
    });

237 238
    group('AndroidSdk', () {
      testUsingContext('validateSdkWellFormed() not called, sdk reinitialized', () async {
239 240 241 242 243 244 245 246 247 248
        final String projectPath = await createProject(tempDir,
            arguments: <String>['--no-pub', '--template=module']);

        await expectLater(
          runBuildAarCommand(
            projectPath,
            arguments: <String>['--no-pub'],
          ),
          throwsToolExit(),
        );
249 250 251 252 253 254

        verifyNever(mockAndroidSdk.validateSdkWellFormed());
        verify(mockAndroidSdk.reinitialize()).called(1);
      },
      overrides: <Type, Generator>{
        AndroidSdk: () => mockAndroidSdk,
255 256 257 258 259 260 261 262 263 264 265 266 267 268
        FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir),
        ProcessManager: () => mockProcessManager,
      });

      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,
            arguments: <String>['--no-pub'],
          );
        }, throwsToolExit(
269
          message: 'No Android SDK found. Try setting the ANDROID_SDK_ROOT environment variable',
270 271 272 273 274
        ));
      },
      overrides: <Type, Generator>{
        AndroidSdk: () => null,
        FlutterProjectFactory: () => FakeFlutterProjectFactory(tempDir),
275 276 277 278
        ProcessManager: () => mockProcessManager,
      });
    });
  });
279
}
280 281 282 283 284

Future<BuildAarCommand> runBuildAarCommand(
  String target, {
  List<String> arguments,
}) async {
285
  final BuildAarCommand command = BuildAarCommand(verboseHelp: false);
286 287 288 289 290
  final CommandRunner<void> runner = createTestCommandRunner(command);
  await runner.run(<String>[
    'aar',
    '--no-pub',
    ...?arguments,
291
    globals.fs.path.join(target, 'lib', 'main.dart'),
292 293 294 295
  ]);
  return command;
}

296
class MockAndroidBuilder extends Mock implements AndroidBuilder {}
297 298 299 300
class MockAndroidSdk extends Mock implements AndroidSdk {}
class MockProcessManager extends Mock implements ProcessManager {}
class MockProcess extends Mock implements Process {}
class MockUsage extends Mock implements Usage {}