module_test.dart 10.8 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 'dart:io';
6

7
import 'package:flutter_devicelab/framework/apk_utils.dart';
8
import 'package:flutter_devicelab/framework/framework.dart';
9
import 'package:flutter_devicelab/framework/task_result.dart';
10 11 12
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:path/path.dart' as path;

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

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

23 24 25 26
    section('Find Java');

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

30
    section('Create Flutter module project');
31

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

42 43 44 45
      section('Add read-only asset');

      final File readonlyTxtAssetFile = await File(path.join(
        projectDir.path,
46 47
        'assets',
        'read-only.txt'
48 49 50 51 52 53 54 55 56 57 58 59 60
      ))
      .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
        ]);
      }
61

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

      section('Add plugins');

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

85
      section('Build Flutter module library archive');
86

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

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

      if (!aarBuilt) {
106
        return TaskResult.failure('Failed to build .aar');
107 108
      }

109 110
      section('Build ephemeral host app');

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

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

128
      if (!ephemeralHostApkBuilt) {
129
        return TaskResult.failure('Failed to build ephemeral host .apk');
130 131
      }

132 133
      section('Clean build');

134
      await inDirectory(projectDir, () async {
135 136 137
        await flutter('clean');
      });

138
      section('Make Android host app editable');
139

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

147
      section('Build editable host app');
148

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

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

166 167
      if (!editableHostApkBuilt) {
        return TaskResult.failure('Failed to build editable host .apk');
168 169
      }

170
      section('Add to existing Android app');
171

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

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

196 197
      section('Build debug host APK');

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

211 212 213
      section('Check debug APK exists');

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

      section('Check files in debug APK');

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

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

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

258
      final String readonlyDebugAssetFilePath = path.joinAll(<String>[
259 260 261 262 263 264 265
        hostApp.path,
        'app',
        'build',
        'intermediates',
        'merged_assets',
        'debug',
        'out',
266 267 268 269
        'flutter_assets',
        'assets',
        'read-only.txt',
      ]);
270 271 272 273 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');
      if (modes != null && modes.compareTo(fileReadWriteMode) != 0) {
        return TaskResult.failure('Failed to make assets user-readable and writable');
      }

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
      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');

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

      section('Check release AndroidManifest.xml');

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

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

330
      final String readonlyReleaseAssetFilePath = path.joinAll(<String>[
331 332 333 334 335 336 337
        hostApp.path,
        'app',
        'build',
        'intermediates',
        'merged_assets',
        'release',
        'out',
338 339 340 341
        'flutter_assets',
        'assets',
        'read-only.txt',
      ]);
342 343 344 345 346 347 348 349 350 351 352
      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');
      }

353
      return TaskResult.success(null);
354 355
    } on TaskResult catch (taskResult) {
      return taskResult;
356
    } catch (e) {
357
      return TaskResult.failure(e.toString());
358
    } finally {
359
      rmTree(tempDir);
360 361 362
    }
  });
}