plugin_tests.dart 16.1 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
import '../framework/framework.dart';
10
import '../framework/ios.dart';
11 12 13
import '../framework/task_result.dart';
import '../framework/utils.dart';

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

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

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

  Future<TaskResult> call() async {
49 50
    final Directory tempDir =
        Directory.systemTemp.createTempSync('flutter_devicelab_plugin_test.');
Daco Harkes's avatar
Daco Harkes committed
51 52 53 54
    // 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';
55
    try {
56 57
      section('Create plugin');
      final _FlutterProject plugin = await _FlutterProject.create(
58
          tempDir, options, buildTarget,
Daco Harkes's avatar
Daco Harkes committed
59
          name: 'plugintest', template: template, environment: pluginCreateEnvironment);
60 61 62
      if (dartOnlyPlugin) {
        await plugin.convertDefaultPluginToDartPlugin();
      }
63 64 65
      if (sharedDarwinSource) {
        await plugin.convertDefaultPluginToSharedDarwinPlugin();
      }
66
      section('Test plugin');
Daco Harkes's avatar
Daco Harkes committed
67
      if (runFlutterTest) {
68 69 70 71
        await plugin.runFlutterTest();
        if (!dartOnlyPlugin) {
          await plugin.example.runNativeTests(buildTarget);
        }
Daco Harkes's avatar
Daco Harkes committed
72
      }
73
      section('Create Flutter app');
74
      final _FlutterProject app = await _FlutterProject.create(tempDir, options, buildTarget,
75
          name: 'plugintestapp', template: 'app', environment: appCreateEnvironment);
76
      try {
77 78 79 80 81
        section('Add plugins');
        await app.addPlugin('plugintest',
            pluginPath: path.join('..', 'plugintest'));
        await app.addPlugin('path_provider');
        section('Build app');
82
        await app.build(buildTarget, validateNativeBuildProject: !dartOnlyPlugin);
Daco Harkes's avatar
Daco Harkes committed
83 84
        if (runFlutterTest) {
          section('Test app');
85
          await app.runFlutterTest();
Daco Harkes's avatar
Daco Harkes committed
86
        }
87
      } finally {
88 89
        await plugin.delete();
        await app.delete();
90
      }
91
      return TaskResult.success(null);
92
    } catch (e) {
93
      return TaskResult.failure(e.toString());
94
    } finally {
95
      rmTree(tempDir);
96 97 98 99
    }
  }
}

100 101
class _FlutterProject {
  _FlutterProject(this.parent, this.name);
102 103 104 105 106 107

  final Directory parent;
  final String name;

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

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

110 111 112 113
  _FlutterProject get example {
    return _FlutterProject(Directory(path.join(rootPath)), 'example');
  }

114
  Future<void> addPlugin(String plugin, {String? pluginPath}) async {
115
    final File pubspec = pubspecFile;
116
    String content = await pubspec.readAsString();
117 118
    final String dependency =
        pluginPath != null ? '$plugin:\n    path: $pluginPath' : '$plugin:';
119 120
    content = content.replaceFirst(
      '\ndependencies:\n',
121
      '\ndependencies:\n  $dependency\n',
122 123 124 125
    );
    await pubspec.writeAsString(content, flush: true);
  }

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 154 155 156 157 158 159 160 161 162 163 164 165 166
  /// 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);
      }
    }
  }

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
  /// Converts an iOS/macOS plugin created from the standard template to a shared
  /// darwin directory plugin.
  Future<void> convertDefaultPluginToSharedDarwinPlugin() async {
    // Convert the metadata.
    final File pubspec = pubspecFile;
    String pubspecContent = await pubspec.readAsString();
    const String originalIOSKey = '\n      ios:\n';
    const String originalMacOSKey = '\n      macos:\n';
    if (!pubspecContent.contains(originalIOSKey) || !pubspecContent.contains(originalMacOSKey)) {
      print(pubspecContent);
      throw TaskResult.failure('Missing expected darwin platform plugin keys');
    }
    pubspecContent = pubspecContent.replaceAll(
        originalIOSKey,
        '$originalIOSKey        sharedDarwinSource: true\n'
    );
    pubspecContent = pubspecContent.replaceAll(
        originalMacOSKey,
        '$originalMacOSKey        sharedDarwinSource: true\n'
    );
    await pubspec.writeAsString(pubspecContent, flush: true);

    // Copy ios to darwin, and delete macos.
    final Directory iosDir = Directory(path.join(rootPath, 'ios'));
    final Directory darwinDir = Directory(path.join(rootPath, 'darwin'));
    recursiveCopy(iosDir, darwinDir);

    await iosDir.delete(recursive: true);
    await Directory(path.join(rootPath, 'macos')).delete(recursive: true);

    final File podspec = File(path.join(darwinDir.path, '$name.podspec'));
    String podspecContent = await podspec.readAsString();
    if (!podspecContent.contains('s.platform =')) {
      print(podspecContent);
      throw TaskResult.failure('Missing expected podspec platform');
    }

    // Remove "s.platform = :ios" to work on all platforms, including macOS.
    podspecContent = podspecContent.replaceFirst(RegExp(r'.*s\.platform.*'), '');
    podspecContent = podspecContent.replaceFirst("s.dependency 'Flutter'", "s.ios.dependency 'Flutter'\ns.osx.dependency 'FlutterMacOS'");

    await podspec.writeAsString(podspecContent, flush: true);

    // Make PlugintestPlugin.swift compile on iOS and macOS with target conditionals.
    final String pluginClass = '${name[0].toUpperCase()}${name.substring(1)}Plugin';
    print('pluginClass: $pluginClass');
    final File pluginRegister = File(path.join(darwinDir.path, 'Classes', '$pluginClass.swift'));
    final String pluginRegisterContent = '''
#if os(macOS)
import FlutterMacOS
#elseif os(iOS)
import Flutter
#endif

public class $pluginClass: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
#if os(macOS)
    let channel = FlutterMethodChannel(name: "$name", binaryMessenger: registrar.messenger)
#elseif os(iOS)
    let channel = FlutterMethodChannel(name: "$name", binaryMessenger: registrar.messenger())
#endif
    let instance = $pluginClass()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
#if os(macOS)
    result("macOS " + ProcessInfo.processInfo.operatingSystemVersionString)
#elseif os(iOS)
    result("iOS " + UIDevice.current.systemVersion)
#endif
  }
}
''';
    await pluginRegister.writeAsString(pluginRegisterContent, flush: true);
  }

244
  Future<void> runFlutterTest() async {
245 246 247 248 249
    await inDirectory(Directory(rootPath), () async {
      await flutter('test');
    });
  }

250 251 252 253 254
  Future<void> runNativeTests(String buildTarget) async {
    // Native unit tests rely on building the app first to generate necessary
    // build files.
    await build(buildTarget, validateNativeBuildProject: false);

255
    switch (buildTarget) {
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
      case 'apk':
        if (await exec(
          path.join('.', 'gradlew'),
          <String>['testDebugUnitTest'],
          workingDirectory: path.join(rootPath, 'android'),
          canFail: true,
        ) != 0) {
          throw TaskResult.failure('Platform unit tests failed');
        }
      case 'ios':
        await testWithNewIOSSimulator('TestNativeUnitTests', (String deviceId) async {
          if (!await runXcodeTests(
            platformDirectory: path.join(rootPath, 'ios'),
            destination: 'id=$deviceId',
            configuration: 'Debug',
            testName: 'native_plugin_unit_tests_ios',
            skipCodesign: true,
          )) {
            throw TaskResult.failure('Platform unit tests failed');
          }
        });
277 278
      case 'linux':
        if (await exec(
279
          path.join(rootPath, 'build', 'linux', 'x64', 'release', 'plugins', 'plugintest', 'plugintest_test'),
280 281 282 283 284
          <String>[],
          canFail: true,
        ) != 0) {
          throw TaskResult.failure('Platform unit tests failed');
        }
285
      case 'macos':
286
        if (!await runXcodeTests(
287 288
          platformDirectory: path.join(rootPath, 'macos'),
          destination: 'platform=macOS',
289
          configuration: 'Debug',
290
          testName: 'native_plugin_unit_tests_macos',
291 292 293 294
          skipCodesign: true,
        )) {
          throw TaskResult.failure('Platform unit tests failed');
        }
295 296
      case 'windows':
        if (await exec(
297
          path.join(rootPath, 'build', 'windows', 'x64', 'plugins', 'plugintest', 'Release', 'plugintest_test.exe'),
298 299 300 301 302
          <String>[],
          canFail: true,
        ) != 0) {
          throw TaskResult.failure('Platform unit tests failed');
        }
303 304 305
    }
  }

306
  static Future<_FlutterProject> create(
307 308
      Directory directory,
      List<String> options,
309
      String target,
310
      {
311 312 313
        required String name,
        required String template,
        Map<String, String>? environment,
314
      }) async {
315 316 317 318 319 320 321 322
    await inDirectory(directory, () async {
      await flutter(
        'create',
        options: <String>[
          '--template=$template',
          '--org',
          'io.flutter.devicelab',
          ...options,
323
          name,
324
        ],
325
        environment: environment,
326 327
      );
    });
328 329

    final _FlutterProject project = _FlutterProject(directory, name);
330 331
    if (template == 'plugin' && (target == 'ios' || target == 'macos')) {
      project._reduceDarwinPluginMinimumVersion(name, target);
332 333 334 335 336 337
    }
    return project;
  }

  // Make the platform version artificially low to test that the "deployment
  // version too low" warning is never emitted.
338 339
  void _reduceDarwinPluginMinimumVersion(String plugin, String target) {
    final File podspec = File(path.join(rootPath, target, '$plugin.podspec'));
340 341 342
    if (!podspec.existsSync()) {
      throw TaskResult.failure('podspec file missing at ${podspec.path}');
    }
343
    final String versionString = target == 'ios'
344
        ? "s.platform = :ios, '11.0'"
345
        : "s.platform = :osx, '10.11'";
346 347
    String podspecContent = podspec.readAsStringSync();
    if (!podspecContent.contains(versionString)) {
348
      throw TaskResult.failure('Update this test to match plugin minimum $target deployment version');
349
    }
350 351 352 353 354 355 356 357 358 359 360 361 362
    // Add transitive dependency on AppAuth 1.6 targeting iOS 8 and macOS 10.9, which no longer builds in Xcode
    // to test the version is forced higher and builds.
    const String iosContent = '''
s.platform = :ios, '10.0'
s.dependency 'AppAuth', '1.6.0'
''';

    const String macosContent = '''
s.platform = :osx, '10.8'
s.dependency 'AppAuth', '1.6.0'
''';

    podspecContent = podspecContent.replaceFirst(versionString, target == 'ios' ? iosContent : macosContent);
363
    podspec.writeAsStringSync(podspecContent, flush: true);
364 365
  }

366
  Future<void> build(String target, {bool validateNativeBuildProject = true}) async {
367
    await inDirectory(Directory(rootPath), () async {
368 369 370 371 372 373
      final String buildOutput =  await evalFlutter('build', options: <String>[
        target,
        '-v',
        if (target == 'ios')
          '--no-codesign',
      ]);
374

375
      if (target == 'ios' || target == 'macos') {
376 377 378 379
        // 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.
380 381
        //
        // (or "The macOS deployment target 'MACOSX_DEPLOYMENT_TARGET'"...)
382 383
        if (buildOutput.contains('is set to 10.0, but the range of supported deployment target versions') ||
            buildOutput.contains('is set to 10.8, but the range of supported deployment target versions')) {
384 385
          throw TaskResult.failure('Minimum plugin version warning present');
        }
386

387 388 389 390
        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}');
391
          }
392 393 394 395 396

          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
397 398
            // in _reduceDarwinPluginMinimumVersion to 10, which is below the target version of 11.
            if (podsProjectContent.contains('IPHONEOS_DEPLOYMENT_TARGET = 10')) {
399 400
              throw TaskResult.failure('Plugin build setting IPHONEOS_DEPLOYMENT_TARGET not removed');
            }
401 402 403 404
            // Transitive dependency AppAuth targeting too-low 8.0 was not fixed.
            if (podsProjectContent.contains('IPHONEOS_DEPLOYMENT_TARGET = 8')) {
              throw TaskResult.failure('Transitive dependency build setting IPHONEOS_DEPLOYMENT_TARGET=8 not removed');
            }
405 406 407
            if (!podsProjectContent.contains(r'"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "$(inherited) i386";')) {
              throw TaskResult.failure(r'EXCLUDED_ARCHS is not "$(inherited) i386"');
            }
408 409 410 411 412 413 414 415 416 417
          } else if (target == 'macos') {
            // Same for macOS deployment target, but 10.8.
            // The plugintest target should not have MACOSX_DEPLOYMENT_TARGET set.
            if (podsProjectContent.contains('MACOSX_DEPLOYMENT_TARGET = 10.8')) {
              throw TaskResult.failure('Plugin build setting MACOSX_DEPLOYMENT_TARGET not removed');
            }
            // Transitive dependency AppAuth targeting too-low 10.9 was not fixed.
            if (podsProjectContent.contains('MACOSX_DEPLOYMENT_TARGET = 10.9')) {
              throw TaskResult.failure('Transitive dependency build setting MACOSX_DEPLOYMENT_TARGET=10.9 not removed');
            }
418
          }
419
        }
420
      }
421 422 423
    });
  }

424
  Future<void> delete() async {
425 426 427
    if (Platform.isWindows) {
      // A running Gradle daemon might prevent us from deleting the project
      // folder on Windows.
428 429 430 431 432
      final String wrapperPath =
          path.absolute(path.join(rootPath, 'android', 'gradlew.bat'));
      if (File(wrapperPath).existsSync()) {
        await exec(wrapperPath, <String>['--stop'], canFail: true);
      }
433
      // TODO(ianh): Investigating if flakiness is timing dependent.
434
      await Future<void>.delayed(const Duration(seconds: 10));
435
    }
436
    rmTree(parent);
437 438
  }
}