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 33
    print('\nUsing JAVA_HOME=$javaHome');

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

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

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

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

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

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

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

      section('Add plugins');

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

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

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

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

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

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

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

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

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

136 137
      section('Clean build');

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      section('Check files in debug APK');

232
      checkCollectionContains<String>(<String>[
233
        ...flutterAssets,
234 235
        ...debugAssets,
        ...baseApkFiles,
236 237 238 239 240 241 242 243 244 245
      ], 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" />''')
      ) {
246
        return TaskResult.failure("Debug host APK doesn't contain metadata: flutterProjectType = module ");
247
      }
248 249

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

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

262
      final String readonlyDebugAssetFilePath = path.joinAll(<String>[
263 264 265 266 267 268 269
        hostApp.path,
        'app',
        'build',
        'intermediates',
        'merged_assets',
        'debug',
        'out',
270 271 272 273
        'flutter_assets',
        'assets',
        'read-only.txt',
      ]);
274 275 276 277 278 279 280
      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');
281
      if (modes.compareTo(fileReadWriteMode) != 0) {
282 283 284
        return TaskResult.failure('Failed to make assets user-readable and writable');
      }

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

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

321 322 323 324 325 326
      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.
327
        final ArchiveFile? noticesFile = apk.findFile('assets/flutter_assets/NOTICES.Z');
328

329
        final Uint8List? licenseData = noticesFile?.content as Uint8List?;
330 331 332 333 334 335 336 337 338
        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.');
        }
      });

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

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

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

352
      final String readonlyReleaseAssetFilePath = path.joinAll(<String>[
353 354 355 356 357 358 359
        hostApp.path,
        'app',
        'build',
        'intermediates',
        'merged_assets',
        'release',
        'out',
360 361 362 363
        'flutter_assets',
        'assets',
        'read-only.txt',
      ]);
364 365 366 367 368 369 370
      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');
371
      if (modes.compareTo(fileReadWriteMode) != 0) {
372 373 374
        return TaskResult.failure('Failed to make assets user-readable and writable');
      }

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