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

import 'dart:io';

7
import 'package:path/path.dart' as path;
8

9 10 11 12
import '../framework/framework.dart';
import '../framework/task_result.dart';
import '../framework/utils.dart';

13 14 15
/// Combines several TaskFunctions with trivial success value into one.
TaskFunction combine(List<TaskFunction> tasks) {
  return () async {
16
    for (final TaskFunction task in tasks) {
17 18 19 20 21
      final TaskResult result = await task();
      if (result.failed) {
        return result;
      }
    }
22
    return TaskResult.success(null);
23 24 25
  };
}

26 27
/// Defines task that creates new Flutter project, adds a local and remote
/// plugin, and then builds the specified [buildTarget].
28
class PluginTest {
29 30 31 32 33 34
  PluginTest(
    this.buildTarget,
    this.options, {
    this.pluginCreateEnvironment,
    this.appCreateEnvironment,
    this.dartOnlyPlugin = false,
Daco Harkes's avatar
Daco Harkes committed
35
    this.template = 'plugin',
36
  });
37

38
  final String buildTarget;
39
  final List<String> options;
40 41
  final Map<String, String>? pluginCreateEnvironment;
  final Map<String, String>? appCreateEnvironment;
42
  final bool dartOnlyPlugin;
Daco Harkes's avatar
Daco Harkes committed
43
  final String template;
44 45

  Future<TaskResult> call() async {
46 47
    final Directory tempDir =
        Directory.systemTemp.createTempSync('flutter_devicelab_plugin_test.');
Daco Harkes's avatar
Daco Harkes committed
48 49 50 51
    // FFI plugins do not have support for `flutter test`.
    // `flutter test` does not do a native build.
    // Supporting `flutter test` would require invoking a native build.
    final bool runFlutterTest = template != 'plugin_ffi';
52
    try {
53 54
      section('Create plugin');
      final _FlutterProject plugin = await _FlutterProject.create(
55
          tempDir, options, buildTarget,
Daco Harkes's avatar
Daco Harkes committed
56
          name: 'plugintest', template: template, environment: pluginCreateEnvironment);
57 58 59
      if (dartOnlyPlugin) {
        await plugin.convertDefaultPluginToDartPlugin();
      }
60
      section('Test plugin');
Daco Harkes's avatar
Daco Harkes committed
61 62 63
      if (runFlutterTest) {
        await plugin.test();
      }
64
      section('Create Flutter app');
65
      final _FlutterProject app = await _FlutterProject.create(tempDir, options, buildTarget,
66
          name: 'plugintestapp', template: 'app', environment: appCreateEnvironment);
67
      try {
68 69 70 71 72
        section('Add plugins');
        await app.addPlugin('plugintest',
            pluginPath: path.join('..', 'plugintest'));
        await app.addPlugin('path_provider');
        section('Build app');
73
        await app.build(buildTarget, validateNativeBuildProject: !dartOnlyPlugin);
Daco Harkes's avatar
Daco Harkes committed
74 75 76 77
        if (runFlutterTest) {
          section('Test app');
          await app.test();
        }
78
      } finally {
79 80
        await plugin.delete();
        await app.delete();
81
      }
82
      return TaskResult.success(null);
83
    } catch (e) {
84
      return TaskResult.failure(e.toString());
85
    } finally {
86
      rmTree(tempDir);
87 88 89 90
    }
  }
}

91 92
class _FlutterProject {
  _FlutterProject(this.parent, this.name);
93 94 95 96 97 98

  final Directory parent;
  final String name;

  String get rootPath => path.join(parent.path, name);

99 100
  File get pubspecFile => File(path.join(rootPath, 'pubspec.yaml'));

101
  Future<void> addPlugin(String plugin, {String? pluginPath}) async {
102
    final File pubspec = pubspecFile;
103
    String content = await pubspec.readAsString();
104 105
    final String dependency =
        pluginPath != null ? '$plugin:\n    path: $pluginPath' : '$plugin:';
106 107
    content = content.replaceFirst(
      '\ndependencies:\n',
108
      '\ndependencies:\n  $dependency\n',
109 110 111 112
    );
    await pubspec.writeAsString(content, flush: true);
  }

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 143 144 145 146 147 148 149 150 151 152 153
  /// Converts a plugin created from the standard template to a Dart-only
  /// plugin.
  Future<void> convertDefaultPluginToDartPlugin() async {
    final String dartPluginClass = 'DartClassFor$name';
    // Convert the metadata.
    final File pubspec = pubspecFile;
    String content = await pubspec.readAsString();
    content = content.replaceAll(
      RegExp(r' pluginClass: .*?\n'),
      ' dartPluginClass: $dartPluginClass\n',
    );
    await pubspec.writeAsString(content, flush: true);

    // Add the Dart registration hook that the build will generate a call to.
    final File dartCode = File(path.join(rootPath, 'lib', '$name.dart'));
    content = await dartCode.readAsString();
    content = '''
$content

class $dartPluginClass {
  static void registerWith() {}
}
''';
    await dartCode.writeAsString(content, flush: true);

    // Remove any native plugin code.
    const List<String> platforms = <String>[
      'android',
      'ios',
      'linux',
      'macos',
      'windows',
    ];
    for (final String platform in platforms) {
      final Directory platformDir = Directory(path.join(rootPath, platform));
      if (platformDir.existsSync()) {
        await platformDir.delete(recursive: true);
      }
    }
  }

154 155 156 157 158 159 160
  Future<void> test() async {
    await inDirectory(Directory(rootPath), () async {
      await flutter('test');
    });
  }

  static Future<_FlutterProject> create(
161 162
      Directory directory,
      List<String> options,
163
      String target,
164
      {
165 166 167
        required String name,
        required String template,
        Map<String, String>? environment,
168
      }) async {
169 170 171 172 173 174 175 176
    await inDirectory(directory, () async {
      await flutter(
        'create',
        options: <String>[
          '--template=$template',
          '--org',
          'io.flutter.devicelab',
          ...options,
177
          name,
178
        ],
179
        environment: environment,
180 181
      );
    });
182 183

    final _FlutterProject project = _FlutterProject(directory, name);
184 185
    if (template == 'plugin' && (target == 'ios' || target == 'macos')) {
      project._reduceDarwinPluginMinimumVersion(name, target);
186 187 188 189 190 191
    }
    return project;
  }

  // Make the platform version artificially low to test that the "deployment
  // version too low" warning is never emitted.
192 193
  void _reduceDarwinPluginMinimumVersion(String plugin, String target) {
    final File podspec = File(path.join(rootPath, target, '$plugin.podspec'));
194 195 196
    if (!podspec.existsSync()) {
      throw TaskResult.failure('podspec file missing at ${podspec.path}');
    }
197
    final String versionString = target == 'ios'
198
        ? "s.platform = :ios, '9.0'"
199
        : "s.platform = :osx, '10.11'";
200 201
    String podspecContent = podspec.readAsStringSync();
    if (!podspecContent.contains(versionString)) {
202
      throw TaskResult.failure('Update this test to match plugin minimum $target deployment version');
203 204 205
    }
    podspecContent = podspecContent.replaceFirst(
      versionString,
206 207 208
      target == 'ios'
          ? "s.platform = :ios, '7.0'"
          : "s.platform = :osx, '10.8'"
209 210
    );
    podspec.writeAsStringSync(podspecContent, flush: true);
211 212
  }

213
  Future<void> build(String target, {bool validateNativeBuildProject = true}) async {
214
    await inDirectory(Directory(rootPath), () async {
215 216 217 218 219 220
      final String buildOutput =  await evalFlutter('build', options: <String>[
        target,
        '-v',
        if (target == 'ios')
          '--no-codesign',
      ]);
221

222
      if (target == 'ios' || target == 'macos') {
223 224 225 226
        // This warning is confusing and shouldn't be emitted. Plugins often support lower versions than the
        // Flutter app, but as long as they support the minimum it will work.
        // warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0,
        // but the range of supported deployment target versions is 9.0 to 14.0.99.
227 228
        //
        // (or "The macOS deployment target 'MACOSX_DEPLOYMENT_TARGET'"...)
229 230 231
        if (buildOutput.contains('the range of supported deployment target versions')) {
          throw TaskResult.failure('Minimum plugin version warning present');
        }
232

233 234 235 236
        if (validateNativeBuildProject) {
          final File podsProject = File(path.join(rootPath, target, 'Pods', 'Pods.xcodeproj', 'project.pbxproj'));
          if (!podsProject.existsSync()) {
            throw TaskResult.failure('Xcode Pods project file missing at ${podsProject.path}');
237
          }
238 239 240 241 242 243 244 245 246 247 248 249

          final String podsProjectContent = podsProject.readAsStringSync();
          if (target == 'ios') {
            // Plugins with versions lower than the app version should not have IPHONEOS_DEPLOYMENT_TARGET set.
            // The plugintest plugin target should not have IPHONEOS_DEPLOYMENT_TARGET set since it has been lowered
            // in _reduceDarwinPluginMinimumVersion to 7, which is below the target version of 9.
            if (podsProjectContent.contains('IPHONEOS_DEPLOYMENT_TARGET = 7')) {
              throw TaskResult.failure('Plugin build setting IPHONEOS_DEPLOYMENT_TARGET not removed');
            }
            if (!podsProjectContent.contains(r'"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "$(inherited) i386";')) {
              throw TaskResult.failure(r'EXCLUDED_ARCHS is not "$(inherited) i386"');
            }
250
          }
251

252 253 254 255 256
          // Same for macOS deployment target, but 10.8.
          // The plugintest target should not have MACOSX_DEPLOYMENT_TARGET set.
          if (target == 'macos' && podsProjectContent.contains('MACOSX_DEPLOYMENT_TARGET = 10.8')) {
            throw TaskResult.failure('Plugin build setting MACOSX_DEPLOYMENT_TARGET not removed');
          }
257
        }
258
      }
259 260 261
    });
  }

262
  Future<void> delete() async {
263 264 265
    if (Platform.isWindows) {
      // A running Gradle daemon might prevent us from deleting the project
      // folder on Windows.
266 267 268 269 270
      final String wrapperPath =
          path.absolute(path.join(rootPath, 'android', 'gradlew.bat'));
      if (File(wrapperPath).existsSync()) {
        await exec(wrapperPath, <String>['--stop'], canFail: true);
      }
271
      // TODO(ianh): Investigating if flakiness is timing dependent.
272
      await Future<void>.delayed(const Duration(seconds: 10));
273
    }
274
    rmTree(parent);
275 276
  }
}