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

5
import 'dart:convert';
6
import 'dart:io';
7
import 'dart:typed_data';
8

9
import 'package:archive/archive.dart';
10
import 'package:flutter_devicelab/framework/apk_utils.dart';
11
import 'package:flutter_devicelab/framework/framework.dart';
12
import 'package:flutter_devicelab/framework/task_result.dart';
13 14 15
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:path/path.dart' as path;

16
final String gradlew = Platform.isWindows ? 'gradlew.bat' : 'gradlew';
17
final String gradlewExecutable = Platform.isWindows ? '.\\$gradlew' : './$gradlew';
18
final String fileReadWriteMode = Platform.isWindows ? 'rw-rw-rw-' : 'rw-r--r--';
19
final String platformLineSep = Platform.isWindows ? '\r\n': '\n';
20

21
/// Tests that the Flutter module project template works and supports
22
/// adding Flutter to an existing Android app.
23
Future<void> main() async {
24 25
  await task(() async {

26 27
    section('Find Java');

28
    final String? javaHome = await findJavaHome();
29
    if (javaHome == null)
30
      return TaskResult.failure('Could not find Java');
31 32
    print('\nUsing JAVA_HOME=$javaHome');

33
    section('Create Flutter module project');
34

35
    final Directory tempDir = Directory.systemTemp.createTempSync('flutter_module_test.');
36
    final Directory projectDir = Directory(path.join(tempDir.path, 'hello'));
37
    try {
38
      await inDirectory(tempDir, () async {
39 40
        await flutter(
          'create',
41
          options: <String>['--org', 'io.flutter.devicelab', '--template=module', 'hello'],
42 43 44
        );
      });

45 46 47 48
      section('Add read-only asset');

      final File readonlyTxtAssetFile = await File(path.join(
        projectDir.path,
49 50
        'assets',
        'read-only.txt'
51 52 53 54 55 56 57 58 59 60 61 62 63
      ))
      .create(recursive: true);

      if (!exists(readonlyTxtAssetFile)) {
        return TaskResult.failure('Failed to create read-only asset');
      }

      if (!Platform.isWindows) {
        await exec('chmod', <String>[
          '444',
          readonlyTxtAssetFile.path
        ]);
      }
64

65
      final File pubspec = File(path.join(projectDir.path, 'pubspec.yaml'));
66
      String content = await pubspec.readAsString();
67
      content = content.replaceFirst(
68 69
        '$platformLineSep  # assets:$platformLineSep',
        '$platformLineSep  assets:$platformLineSep    - assets/read-only.txt$platformLineSep',
70 71 72 73 74 75
      );
      await pubspec.writeAsString(content, flush: true);

      section('Add plugins');

      content = await pubspec.readAsString();
76
      content = content.replaceFirst(
77 78
        '${platformLineSep}dependencies:$platformLineSep',
        '${platformLineSep}dependencies:$platformLineSep  device_info: 0.4.1$platformLineSep  package_info: 0.4.0+9$platformLineSep',
79 80
      );
      await pubspec.writeAsString(content, flush: true);
81
      await inDirectory(projectDir, () async {
82 83 84 85 86
        await flutter(
          'packages',
          options: <String>['get'],
        );
      });
87

88
      section('Build Flutter module library archive');
89

90
      await inDirectory(Directory(path.join(projectDir.path, '.android')), () async {
91
        await exec(
92
          gradlewExecutable,
93 94 95
          <String>['flutter:assembleDebug'],
          environment: <String, String>{ 'JAVA_HOME': javaHome },
        );
96 97
      });

98
      final bool aarBuilt = exists(File(path.join(
99
        projectDir.path,
100 101
        '.android',
        'Flutter',
102 103 104 105 106 107 108
        'build',
        'outputs',
        'aar',
        'flutter-debug.aar',
      )));

      if (!aarBuilt) {
109
        return TaskResult.failure('Failed to build .aar');
110 111
      }

112 113
      section('Build ephemeral host app');

114
      await inDirectory(projectDir, () async {
115 116 117 118 119 120
        await flutter(
          'build',
          options: <String>['apk'],
        );
      });

121
      final bool ephemeralHostApkBuilt = exists(File(path.join(
122
        projectDir.path,
123 124 125 126 127 128 129 130
        'build',
        'host',
        'outputs',
        'apk',
        'release',
        'app-release.apk',
      )));

131
      if (!ephemeralHostApkBuilt) {
132
        return TaskResult.failure('Failed to build ephemeral host .apk');
133 134
      }

135 136
      section('Clean build');

137
      await inDirectory(projectDir, () async {
138 139 140
        await flutter('clean');
      });

141
      section('Make Android host app editable');
142

143
      await inDirectory(projectDir, () async {
144
        await flutter(
145
          'make-host-app-editable',
146 147 148 149
          options: <String>['android'],
        );
      });

150
      section('Build editable host app');
151

152
      await inDirectory(projectDir, () async {
153 154 155 156 157 158
        await flutter(
          'build',
          options: <String>['apk'],
        );
      });

159 160
      final bool editableHostApkBuilt = exists(File(path.join(
        projectDir.path,
161 162 163 164 165 166 167 168
        'build',
        'host',
        'outputs',
        'apk',
        'release',
        'app-release.apk',
      )));

169 170
      if (!editableHostApkBuilt) {
        return TaskResult.failure('Failed to build editable host .apk');
171 172
      }

173
      section('Add to existing Android app');
174

175
      final Directory hostApp = Directory(path.join(tempDir.path, 'hello_host_app'));
176 177
      mkdir(hostApp);
      recursiveCopy(
178 179 180 181 182
        Directory(
          path.join(
            flutterDirectory.path,
            'dev',
            'integration_tests',
183
            'android_host_app_v2_embedding',
184 185
          ),
        ),
186 187 188
        hostApp,
      );
      copy(
189
        File(path.join(projectDir.path, '.android', gradlew)),
190 191 192
        hostApp,
      );
      copy(
193
        File(path.join(projectDir.path, '.android', 'gradle', 'wrapper', 'gradle-wrapper.jar')),
194
        Directory(path.join(hostApp.path, 'gradle', 'wrapper')),
195 196
      );

197 198
      final File analyticsOutputFile = File(path.join(tempDir.path, 'analytics.log'));

199 200
      section('Build debug host APK');

201
      await inDirectory(hostApp, () async {
202 203 204 205
        if (!Platform.isWindows) {
          await exec('chmod', <String>['+x', 'gradlew']);
        }
        await exec(gradlewExecutable,
206
          <String>['app:assembleDebug'],
207 208 209 210
          environment: <String, String>{
            'JAVA_HOME': javaHome,
            'FLUTTER_ANALYTICS_LOG_FILE': analyticsOutputFile.path,
          },
211
        );
212 213
      });

214 215 216
      section('Check debug APK exists');

      final String debugHostApk = path.join(
217 218 219 220 221 222 223
        hostApp.path,
        'app',
        'build',
        'outputs',
        'apk',
        'debug',
        'app-debug.apk',
224 225 226 227 228 229 230
      );
      if (!exists(File(debugHostApk))) {
        return TaskResult.failure('Failed to build debug host APK');
      }

      section('Check files in debug APK');

231
      checkCollectionContains<String>(<String>[
232
        ...flutterAssets,
233 234
        ...debugAssets,
        ...baseApkFiles,
235 236 237 238 239 240 241 242 243 244
      ], await getFilesInApk(debugHostApk));

      section('Check debug AndroidManifest.xml');

      final String androidManifestDebug = await getAndroidManifest(debugHostApk);
      if (!androidManifestDebug.contains('''
        <meta-data
            android:name="flutterProjectType"
            android:value="module" />''')
      ) {
245
        return TaskResult.failure("Debug host APK doesn't contain metadata: flutterProjectType = module ");
246
      }
247 248

      final String analyticsOutput = analyticsOutputFile.readAsStringSync();
249
      if (!analyticsOutput.contains('cd24: android')
250
          || !analyticsOutput.contains('cd25: true')
251
          || !analyticsOutput.contains('viewName: assemble')) {
252
        return TaskResult.failure(
253
          'Building outer app produced the following analytics: "$analyticsOutput" '
254
          'but not the expected strings: "cd24: android", "cd25: true" and '
255
          '"viewName: assemble"'
256 257 258
        );
      }

259 260
      section('Check file access modes for read-only asset from Flutter module');

261
      final String readonlyDebugAssetFilePath = path.joinAll(<String>[
262 263 264 265 266 267 268
        hostApp.path,
        'app',
        'build',
        'intermediates',
        'merged_assets',
        'debug',
        'out',
269 270 271 272
        'flutter_assets',
        'assets',
        'read-only.txt',
      ]);
273 274 275 276 277 278 279 280 281 282 283
      final File readonlyDebugAssetFile = File(readonlyDebugAssetFilePath);
      if (!exists(readonlyDebugAssetFile)) {
        return TaskResult.failure('Failed to copy read-only asset file');
      }

      String modes = readonlyDebugAssetFile.statSync().modeString();
      print('\nread-only.txt file access modes = $modes');
      if (modes != null && modes.compareTo(fileReadWriteMode) != 0) {
        return TaskResult.failure('Failed to make assets user-readable and writable');
      }

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
      section('Build release host APK');

      await inDirectory(hostApp, () async {
        await exec(gradlewExecutable,
          <String>['app:assembleRelease'],
          environment: <String, String>{
            'JAVA_HOME': javaHome,
            'FLUTTER_ANALYTICS_LOG_FILE': analyticsOutputFile.path,
          },
        );
      });

      final String releaseHostApk = path.join(
        hostApp.path,
        'app',
        'build',
        'outputs',
        'apk',
        'release',
        'app-release-unsigned.apk',
      );
      if (!exists(File(releaseHostApk))) {
        return TaskResult.failure('Failed to build release host APK');
      }

      section('Check files in release APK');

311
      checkCollectionContains<String>(<String>[
312
        ...flutterAssets,
313
        ...baseApkFiles,
314 315 316 317 318 319
        'lib/arm64-v8a/libapp.so',
        'lib/arm64-v8a/libflutter.so',
        'lib/armeabi-v7a/libapp.so',
        'lib/armeabi-v7a/libflutter.so',
      ], await getFilesInApk(releaseHostApk));

320 321 322 323 324 325
      section('Check the NOTICE file is correct');

      await inDirectory(hostApp, () async {
        final File apkFile = File(releaseHostApk);
        final Archive apk = ZipDecoder().decodeBytes(apkFile.readAsBytesSync());
        // Shouldn't be missing since we already checked it exists above.
326
        final ArchiveFile? noticesFile = apk.findFile('assets/flutter_assets/NOTICES.Z');
327

328
        final Uint8List licenseData = noticesFile?.content as Uint8List;
329 330 331 332 333 334 335 336 337
        if (licenseData == null) {
          return TaskResult.failure('Invalid license file.');
        }
        final String licenseString = utf8.decode(gzip.decode(licenseData));
        if (!licenseString.contains('skia') || !licenseString.contains('Flutter Authors')) {
          return TaskResult.failure('License content missing.');
        }
      });

338 339 340 341 342 343 344 345
      section('Check release AndroidManifest.xml');

      final String androidManifestRelease = await getAndroidManifest(debugHostApk);
      if (!androidManifestRelease.contains('''
        <meta-data
            android:name="flutterProjectType"
            android:value="module" />''')
      ) {
346
        return TaskResult.failure("Release host APK doesn't contain metadata: flutterProjectType = module ");
347
      }
348 349 350

      section('Check file access modes for read-only asset from Flutter module');

351
      final String readonlyReleaseAssetFilePath = path.joinAll(<String>[
352 353 354 355 356 357 358
        hostApp.path,
        'app',
        'build',
        'intermediates',
        'merged_assets',
        'release',
        'out',
359 360 361 362
        'flutter_assets',
        'assets',
        'read-only.txt',
      ]);
363 364 365 366 367 368 369 370 371 372 373
      final File readonlyReleaseAssetFile = File(readonlyReleaseAssetFilePath);
      if (!exists(readonlyReleaseAssetFile)) {
        return TaskResult.failure('Failed to copy read-only asset file');
      }

      modes = readonlyReleaseAssetFile.statSync().modeString();
      print('\nread-only.txt file access modes = $modes');
      if (modes != null && modes.compareTo(fileReadWriteMode) != 0) {
        return TaskResult.failure('Failed to make assets user-readable and writable');
      }

374
      return TaskResult.success(null);
375 376
    } on TaskResult catch (taskResult) {
      return taskResult;
377
    } catch (e) {
378
      return TaskResult.failure(e.toString());
379
    } finally {
380
      rmTree(tempDir);
381 382 383
    }
  });
}