module_test.dart 13.9 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 18
final String gradlewExecutable =
    Platform.isWindows ? '.\\$gradlew' : './$gradlew';
19
final String fileReadWriteMode = Platform.isWindows ? 'rw-rw-rw-' : 'rw-r--r--';
20 21 22 23 24 25 26 27 28 29 30 31 32 33
final String platformLineSep = Platform.isWindows ? '\r\n' : '\n';

/// Combines several TaskFunctions with trivial success value into one.
TaskFunction combine(List<TaskFunction> tasks) {
  return () async {
    for (final TaskFunction task in tasks) {
      final TaskResult result = await task();
      if (result.failed) {
        return result;
      }
    }
    return TaskResult.success(null);
  };
}
34

35
/// Tests that the Flutter module project template works and supports
36
/// adding Flutter to an existing Android app.
37 38 39 40 41 42 43 44
class ModuleTest {
  ModuleTest(
    this.buildTarget, {
    this.gradleVersion = '7.6.3',
  });

  final String buildTarget;
  final String gradleVersion;
45

46 47
  Future<TaskResult> call() async {
    section('Running: $buildTarget');
48 49
    section('Find Java');

50
    final String? javaHome = await findJavaHome();
51
    if (javaHome == null) {
52
      return TaskResult.failure('Could not find Java');
53
    }
54 55
    print('\nUsing JAVA_HOME=$javaHome');

56
    section('Create Flutter module project');
57

58
    final Directory tempDir = Directory.systemTemp.createTempSync('flutter_module_test.');
59
    final Directory projectDir = Directory(path.join(tempDir.path, 'hello'));
60
    try {
61
      await inDirectory(tempDir, () async {
62 63
        await flutter(
          'create',
64
          options: <String>['--org', 'io.flutter.devicelab', '--template=module', 'hello'],
65 66 67
        );
      });

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
      section('Create package with native assets');

      await flutter(
        'config',
        options: <String>['--enable-native-assets'],
      );

      const String ffiPackageName = 'ffi_package';
      await createFfiPackage(ffiPackageName, tempDir);

      section('Add FFI package');

      final File pubspec = File(path.join(projectDir.path, 'pubspec.yaml'));
      String content = await pubspec.readAsString();
      content = content.replaceFirst(
        'dependencies:$platformLineSep',
        'dependencies:$platformLineSep  $ffiPackageName:$platformLineSep    path: ..${Platform.pathSeparator}$ffiPackageName$platformLineSep',
      );
      await pubspec.writeAsString(content, flush: true);
      await inDirectory(projectDir, () async {
        await flutter(
          'packages',
          options: <String>['get'],
        );
      });

94 95 96 97
      section('Add read-only asset');

      final File readonlyTxtAssetFile = await File(path.join(
        projectDir.path,
98 99
        'assets',
        'read-only.txt'
100 101 102 103 104 105 106 107 108 109
      ))
      .create(recursive: true);

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

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

114
      content = content.replaceFirst(
115 116
        '$platformLineSep  # assets:$platformLineSep',
        '$platformLineSep  assets:$platformLineSep    - assets/read-only.txt$platformLineSep',
117 118 119 120 121
      );
      await pubspec.writeAsString(content, flush: true);

      section('Add plugins');

122
      content = content.replaceFirst(
123
        '${platformLineSep}dependencies:$platformLineSep',
124
        '${platformLineSep}dependencies:$platformLineSep  device_info: 2.0.3$platformLineSep  package_info: 2.0.2$platformLineSep',
125 126
      );
      await pubspec.writeAsString(content, flush: true);
127
      await inDirectory(projectDir, () async {
128 129 130 131 132
        await flutter(
          'packages',
          options: <String>['get'],
        );
      });
133

134 135
      // TODO(dacoharkes): Implement Add2app. https://github.com/flutter/flutter/issues/129757

136
      section('Build Flutter module library archive');
137

138
      await inDirectory(Directory(path.join(projectDir.path, '.android')), () async {
139
        await exec(
140
          gradlewExecutable,
141 142 143
          <String>['flutter:assembleDebug'],
          environment: <String, String>{ 'JAVA_HOME': javaHome },
        );
144 145
      });

146
      final bool aarBuilt = exists(File(path.join(
147
        projectDir.path,
148 149
        '.android',
        'Flutter',
150 151 152 153 154 155 156
        'build',
        'outputs',
        'aar',
        'flutter-debug.aar',
      )));

      if (!aarBuilt) {
157
        return TaskResult.failure('Failed to build .aar');
158 159
      }

160 161
      section('Build ephemeral host app');

162
      await inDirectory(projectDir, () async {
163 164 165 166 167 168
        await flutter(
          'build',
          options: <String>['apk'],
        );
      });

169
      final bool ephemeralHostApkBuilt = exists(File(path.join(
170
        projectDir.path,
171 172 173 174 175 176 177 178
        'build',
        'host',
        'outputs',
        'apk',
        'release',
        'app-release.apk',
      )));

179
      if (!ephemeralHostApkBuilt) {
180
        return TaskResult.failure('Failed to build ephemeral host .apk');
181 182
      }

183 184
      section('Clean build');

185
      await inDirectory(projectDir, () async {
186 187 188
        await flutter('clean');
      });

189
      section('Make Android host app editable');
190

191
      await inDirectory(projectDir, () async {
192
        await flutter(
193
          'make-host-app-editable',
194 195 196 197
          options: <String>['android'],
        );
      });

198
      section('Build editable host app');
199

200
      await inDirectory(projectDir, () async {
201 202 203 204 205 206
        await flutter(
          'build',
          options: <String>['apk'],
        );
      });

207 208
      final bool editableHostApkBuilt = exists(File(path.join(
        projectDir.path,
209 210 211 212 213 214 215 216
        'build',
        'host',
        'outputs',
        'apk',
        'release',
        'app-release.apk',
      )));

217 218
      if (!editableHostApkBuilt) {
        return TaskResult.failure('Failed to build editable host .apk');
219 220
      }

221
      section('Add to existing Android app');
222

223
      final Directory hostApp = Directory(path.join(tempDir.path, 'hello_host_app'));
224 225
      mkdir(hostApp);
      recursiveCopy(
226 227 228 229 230
        Directory(
          path.join(
            flutterDirectory.path,
            'dev',
            'integration_tests',
231
            'android_host_app_v2_embedding',
232 233
          ),
        ),
234 235 236
        hostApp,
      );
      copy(
237
        File(path.join(projectDir.path, '.android', gradlew)),
238 239 240
        hostApp,
      );
      copy(
241 242
        File(path.join(projectDir.path, '.android', 'gradle', 'wrapper',
            'gradle-wrapper.jar')),
243
        Directory(path.join(hostApp.path, 'gradle', 'wrapper')),
244 245
      );

246 247 248 249 250 251 252 253 254 255 256 257 258 259
      // Modify gradle version to passed in version.
      // This is somehow the wrong file.
      final File gradleWrapperProperties = File(path.join(
          hostApp.path, 'gradle', 'wrapper', 'gradle-wrapper.properties'));
      String propertyContent = await gradleWrapperProperties.readAsString();
      propertyContent = propertyContent.replaceFirst(
        'REPLACEME',
        gradleVersion,
      );
      section(propertyContent);
      await gradleWrapperProperties.writeAsString(propertyContent, flush: true);

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

261 262
      section('Build debug host APK');

263
      await inDirectory(hostApp, () async {
264 265 266 267
        if (!Platform.isWindows) {
          await exec('chmod', <String>['+x', 'gradlew']);
        }
        await exec(gradlewExecutable,
268
          <String>['app:assembleDebug'],
269 270 271 272
          environment: <String, String>{
            'JAVA_HOME': javaHome,
            'FLUTTER_ANALYTICS_LOG_FILE': analyticsOutputFile.path,
          },
273
        );
274 275
      });

276 277 278
      section('Check debug APK exists');

      final String debugHostApk = path.join(
279 280 281 282 283 284 285
        hostApp.path,
        'app',
        'build',
        'outputs',
        'apk',
        'debug',
        'app-debug.apk',
286 287 288 289 290 291 292
      );
      if (!exists(File(debugHostApk))) {
        return TaskResult.failure('Failed to build debug host APK');
      }

      section('Check files in debug APK');

293
      checkCollectionContains<String>(<String>[
294
        ...flutterAssets,
295 296
        ...debugAssets,
        ...baseApkFiles,
297 298
        'lib/arm64-v8a/lib$ffiPackageName.so',
        'lib/armeabi-v7a/lib$ffiPackageName.so',
299 300 301 302 303 304 305 306 307 308
      ], 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" />''')
      ) {
309
        return TaskResult.failure("Debug host APK doesn't contain metadata: flutterProjectType = module ");
310
      }
311 312

      final String analyticsOutput = analyticsOutputFile.readAsStringSync();
313
      if (!analyticsOutput.contains('cd24: android')
314
          || !analyticsOutput.contains('cd25: true')
315
          || !analyticsOutput.contains('viewName: assemble')) {
316
        return TaskResult.failure(
317
          'Building outer app produced the following analytics: "$analyticsOutput" '
318
          'but not the expected strings: "cd24: android", "cd25: true" and '
319
          '"viewName: assemble"'
320 321 322
        );
      }

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

325
      final String readonlyDebugAssetFilePath = path.joinAll(<String>[
326 327 328 329
        hostApp.path,
        'app',
        'build',
        'intermediates',
330
        'assets',
331
        'debug',
332 333 334 335
        'flutter_assets',
        'assets',
        'read-only.txt',
      ]);
336 337 338 339 340 341 342
      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');
343
      if (modes.compareTo(fileReadWriteMode) != 0) {
344 345 346
        return TaskResult.failure('Failed to make assets user-readable and writable');
      }

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
      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');

374
      checkCollectionContains<String>(<String>[
375
        ...flutterAssets,
376
        ...baseApkFiles,
377
        'lib/arm64-v8a/lib$ffiPackageName.so',
378 379
        'lib/arm64-v8a/libapp.so',
        'lib/arm64-v8a/libflutter.so',
380
        'lib/armeabi-v7a/lib$ffiPackageName.so',
381 382 383 384
        'lib/armeabi-v7a/libapp.so',
        'lib/armeabi-v7a/libflutter.so',
      ], await getFilesInApk(releaseHostApk));

385 386 387 388 389 390
      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.
391
        final ArchiveFile? noticesFile = apk.findFile('assets/flutter_assets/NOTICES.Z');
392

393
        final Uint8List? licenseData = noticesFile?.content as Uint8List?;
394 395 396 397 398 399 400 401 402
        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.');
        }
      });

403 404 405 406 407 408 409 410
      section('Check release AndroidManifest.xml');

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

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

416
      final String readonlyReleaseAssetFilePath = path.joinAll(<String>[
417 418 419 420
        hostApp.path,
        'app',
        'build',
        'intermediates',
421
        'assets',
422
        'release',
423 424 425 426
        'flutter_assets',
        'assets',
        'read-only.txt',
      ]);
427 428 429 430 431 432 433
      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');
434
      if (modes.compareTo(fileReadWriteMode) != 0) {
435 436 437
        return TaskResult.failure('Failed to make assets user-readable and writable');
      }

438
      return TaskResult.success(null);
439 440
    } on TaskResult catch (taskResult) {
      return taskResult;
441
    } catch (e) {
442
      return TaskResult.failure(e.toString());
443
    } finally {
444
      rmTree(tempDir);
445
    }
446 447 448 449 450 451 452
  }
}

Future<void> main() async {
  await task(combine(<TaskFunction>[
    // ignore: avoid_redundant_argument_values
    ModuleTest('module-gradle-7.6', gradleVersion: '7.6.3').call,
453
    ModuleTest('module-gradle-7.6', gradleVersion: '7.6-rc-2').call,
454
  ]));
455
}