test.dart 11.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:async';
6
import 'dart:math' as math;
7

8
import '../asset.dart';
9
import '../base/common.dart';
10
import '../base/file_system.dart';
11
import '../build_info.dart';
12
import '../bundle.dart';
13
import '../cache.dart';
14
import '../codegen.dart';
15
import '../dart/pub.dart';
16
import '../devfs.dart';
17
import '../globals.dart' as globals;
18
import '../project.dart';
19
import '../runner/flutter_command.dart';
20
import '../test/coverage_collector.dart';
21 22
import '../test/event_printer.dart';
import '../test/runner.dart';
23
import '../test/test_wrapper.dart';
24
import '../test/watcher.dart';
25

26
class TestCommand extends FlutterCommand {
27 28 29
  TestCommand({
    bool verboseHelp = false,
    this.testWrapper = const TestWrapper(),
30
    this.testRunner = const FlutterTestRunner(),
31
  }) : assert(testWrapper != null) {
32
    requiresPubspecYaml();
33
    usesPubOption();
34 35 36 37 38 39 40 41 42 43 44
    argParser
      ..addMultiOption('name',
        help: 'A regular expression matching substrings of the names of tests to run.',
        valueHelp: 'regexp',
        splitCommas: false,
      )
      ..addMultiOption('plain-name',
        help: 'A plain-text substring of the names of tests to run.',
        valueHelp: 'substring',
        splitCommas: false,
      )
45 46 47 48 49 50 51 52
      ..addOption('tags',
        abbr: 't',
        help: 'Run only tests associated with tags',
      )
      ..addOption('exclude-tags',
        abbr: 'x',
        help: 'Run only tests WITHOUT given tags',
      )
53 54 55 56 57
      ..addFlag('start-paused',
        defaultsTo: false,
        negatable: false,
        help: 'Start in a paused mode and wait for a debugger to connect.\n'
              'You must specify a single test file to run, explicitly.\n'
Devon Carew's avatar
Devon Carew committed
58
              'Instructions for connecting with a debugger are printed to the '
59 60
              'console once the test has started.',
      )
61 62 63 64 65
      ..addFlag('disable-service-auth-codes',
        hide: !verboseHelp,
        defaultsTo: false,
        negatable: false,
        help: 'No longer require an authentication code to connect to the VM '
66
              'service (not recommended).',
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
      ..addFlag('coverage',
        defaultsTo: false,
        negatable: false,
        help: 'Whether to collect coverage information.',
      )
      ..addFlag('merge-coverage',
        defaultsTo: false,
        negatable: false,
        help: 'Whether to merge coverage data with "coverage/lcov.base.info".\n'
              'Implies collecting coverage data. (Requires lcov)',
      )
      ..addFlag('ipv6',
        negatable: false,
        hide: true,
        help: 'Whether to use IPv6 for the test harness server socket.',
      )
      ..addOption('coverage-path',
        defaultsTo: 'coverage/lcov.info',
        help: 'Where to store coverage information (if coverage is enabled).',
      )
      ..addFlag('machine',
        hide: !verboseHelp,
        negatable: false,
        help: 'Handle machine structured JSON command input\n'
              'and provide output and progress in machine friendly format.',
      )
94 95
      ..addFlag('update-goldens',
        negatable: false,
96
        help: 'Whether matchesGoldenFile() calls within your test methods should '
97
              'update the golden files rather than test for an existing match.',
98 99 100
      )
      ..addOption('concurrency',
        abbr: 'j',
101
        defaultsTo: math.max<int>(1, globals.platform.numberOfProcessors - 2).toString(),
102
        help: 'The number of concurrent test processes to run.',
103
        valueHelp: 'jobs',
104 105 106 107 108 109
      )
      ..addFlag('test-assets',
        defaultsTo: true,
        negatable: true,
        help: 'Whether to build the assets bundle for testing.\n'
              'Consider using --no-test-assets if assets are not required.',
110 111 112 113
      )
      ..addOption('platform',
        allowed: const <String>['tester', 'chrome'],
        defaultsTo: 'tester',
114
        help: 'The platform to run the unit tests on. Defaults to "tester".',
115 116
      )
      ..addOption('test-randomize-ordering-seed',
117 118
        help: 'The seed to randomize the execution order of test cases.\n'
              'Must be a 32bit unsigned integer or "random".\n'
119
              'If "random", pick a random seed to use.\n'
120
              'If not passed, do not randomize test case execution order.',
121 122 123 124 125 126 127 128 129
      )
      ..addFlag('enable-vmservice',
        defaultsTo: false,
        hide: !verboseHelp,
        help: 'Enables the vmservice without --start-paused. This flag is '
              'intended for use with tests that will use dart:developer to '
              'interact with the vmservice at runtime.\n'
              'This flag is ignored if --start-paused or coverage are requested. '
              'The vmservice will be enabled no matter what in those cases.'
130
      );
131
    usesTrackWidgetCreation(verboseHelp: verboseHelp);
132
    addEnableExperimentation(hide: !verboseHelp);
Ian Hickson's avatar
Ian Hickson committed
133 134
  }

135 136 137
  /// The interface for starting and configuring the tester.
  final TestWrapper testWrapper;

138 139 140
  /// Interface for running the tester process.
  final FlutterTestRunner testRunner;

141
  @override
142
  Future<Set<DevelopmentArtifact>> get requiredArtifacts async {
143
    final Set<DevelopmentArtifact> results = <DevelopmentArtifact>{};
144
    if (stringArg('platform') == 'chrome') {
145 146 147 148
      results.add(DevelopmentArtifact.web);
    }
    return results;
  }
149

150
  @override
Ian Hickson's avatar
Ian Hickson committed
151
  String get name => 'test';
152 153

  @override
154
  String get description => 'Run Flutter unit tests for the current project.';
155

156
  @override
157
  Future<FlutterCommandResult> runCommand() async {
158 159
    await globals.cache.updateAll(await requiredArtifacts);
    if (!globals.fs.isFileSync('pubspec.yaml')) {
160
      throwToolExit(
161
        'Error: No pubspec.yaml file found in the current working directory.\n'
162
        'Run this command from the root of your project. Test files must be '
163
        "called *_test.dart and must reside in the package's 'test' "
164
        'directory (or one of its subdirectories).');
165
    }
166
    if (shouldRunPub) {
167
      await pub.get(context: PubContext.getVerifyContext(name), skipPubspecYamlCheck: true);
168
    }
169 170 171
    final bool buildTestAssets = boolArg('test-assets');
    final List<String> names = stringsArg('name');
    final List<String> plainNames = stringsArg('plain-name');
172 173
    final String tags = stringArg('tags');
    final String excludeTags = stringArg('exclude-tags');
174
    final FlutterProject flutterProject = FlutterProject.current();
175
    final List<String> dartExperiments = stringsArg(FlutterOptions.kEnableExperiment);
176

177 178 179 180
    if (buildTestAssets && flutterProject.manifest.assets.isNotEmpty) {
      await _buildTestAsset();
    }

181
    List<String> files = argResults.rest.map<String>((String testPath) => globals.fs.path.absolute(testPath)).toList();
182

183
    final bool startPaused = boolArg('start-paused');
184 185
    if (startPaused && files.length != 1) {
      throwToolExit(
186 187 188 189 190
        'When using --start-paused, you must specify a single test file to run.',
        exitCode: 1,
      );
    }

191
    final int jobs = int.tryParse(stringArg('concurrency'));
192 193 194 195
    if (jobs == null || jobs <= 0 || !jobs.isFinite) {
      throwToolExit(
        'Could not parse -j/--concurrency argument. It must be an integer greater than zero.'
      );
196 197
    }

198 199
    Directory workDir;
    if (files.isEmpty) {
200 201
      // We don't scan the entire package, only the test/ subdirectory, so that
      // files with names like like "hit_test.dart" don't get run.
202
      workDir = globals.fs.directory('test');
203
      if (!workDir.existsSync()) {
204
        throwToolExit('Test directory "${workDir.path}" not found.');
205
      }
206
      files = _findTests(workDir).toList();
207 208
      if (files.isEmpty) {
        throwToolExit(
209
            'Test directory "${workDir.path}" does not appear to contain any test files.\n'
210
            'Test files must be in that directory and end with the pattern "_test.dart".'
211 212
        );
      }
213
    } else {
214
      files = <String>[
215
        for (String path in files)
216 217
          if (globals.fs.isDirectorySync(path))
            ..._findTests(globals.fs.directory(path))
218
          else
219
            path,
220
      ];
221
    }
222

223
    final bool machine = boolArg('machine');
224
    CoverageCollector collector;
225
    if (boolArg('coverage') || boolArg('merge-coverage')) {
226
      final String projectName = FlutterProject.current().manifest.appName;
227
      collector = CoverageCollector(
228
        verbose: !machine,
229
        libraryPredicate: (String libraryName) => libraryName.contains(projectName),
230
      );
231 232 233
    }

    TestWatcher watcher;
234 235 236
    if (machine) {
      watcher = EventPrinter(parent: collector);
    } else if (collector != null) {
237 238
      watcher = collector;
    }
239 240 241

    Cache.releaseLockEarly();

242
    // Run builders once before all tests.
243
    if (flutterProject.hasBuilders) {
244 245
      final CodegenDaemon codegenDaemon = await codeGenerator.daemon(flutterProject);
      codegenDaemon.startBuild();
246
      await for (final CodegenStatus status in codegenDaemon.buildResults) {
247 248 249 250 251 252 253 254 255
        if (status == CodegenStatus.Succeeded) {
          break;
        }
        if (status == CodegenStatus.Failed) {
          throwToolExit('Code generation failed.');
        }
      }
    }

256
    final bool disableServiceAuthCodes =
257
      boolArg('disable-service-auth-codes');
258

259
    final int result = await testRunner.runTests(
260
      testWrapper,
261 262 263 264
      files,
      workDir: workDir,
      names: names,
      plainNames: plainNames,
265 266
      tags: tags,
      excludeTags: excludeTags,
267
      watcher: watcher,
268
      enableObservatory: collector != null || startPaused || boolArg('enable-vmservice'),
269
      startPaused: startPaused,
270
      disableServiceAuthCodes: disableServiceAuthCodes,
271
      ipv6: boolArg('ipv6'),
272
      machine: machine,
273
      buildMode: BuildMode.debug,
274 275
      trackWidgetCreation: boolArg('track-widget-creation'),
      updateGoldens: boolArg('update-goldens'),
276
      concurrency: jobs,
277
      buildTestAssets: buildTestAssets,
278
      flutterProject: flutterProject,
279
      web: stringArg('platform') == 'chrome',
280
      randomSeed: stringArg('test-randomize-ordering-seed'),
281
      dartExperiments: dartExperiments,
282
    );
283

284
    if (collector != null) {
285
      final bool collectionResult = await collector.collectCoverageData(
286 287
        stringArg('coverage-path'),
        mergeCoverageData: boolArg('merge-coverage'),
288 289
      );
      if (!collectionResult) {
290
        throwToolExit(null);
291
      }
292 293
    }

294
    if (result != 0) {
295
      throwToolExit(null);
296
    }
297
    return FlutterCommandResult.success();
298
  }
299 300 301 302 303 304 305

  Future<void> _buildTestAsset() async {
    final AssetBundle assetBundle = AssetBundleFactory.instance.createBundle();
    final int build = await assetBundle.build();
    if (build != 0) {
      throwToolExit('Error: Failed to build asset bundle');
    }
306
    if (_needRebuild(assetBundle.entries)) {
307
      await writeBundle(globals.fs.directory(globals.fs.path.join('build', 'unit_test_assets')),
308 309 310
          assetBundle.entries);
    }
  }
311

312
  bool _needRebuild(Map<String, DevFSContent> entries) {
313
    final File manifest = globals.fs.file(globals.fs.path.join('build', 'unit_test_assets', 'AssetManifest.json'));
314 315 316 317
    if (!manifest.existsSync()) {
      return true;
    }
    final DateTime lastModified = manifest.lastModifiedSync();
318
    final File pub = globals.fs.file('pubspec.yaml');
319 320 321 322
    if (pub.lastModifiedSync().isAfter(lastModified)) {
      return true;
    }

323
    for (final DevFSFileContent entry in entries.values.whereType<DevFSFileContent>()) {
324 325 326 327 328 329 330
      // Calling isModified to access file stats first in order for isModifiedAfter
      // to work.
      if (entry.isModified && entry.isModifiedAfter(lastModified)) {
        return true;
      }
    }
    return false;
331
  }
332
}
333 334 335 336

Iterable<String> _findTests(Directory directory) {
  return directory.listSync(recursive: true, followLinks: false)
      .where((FileSystemEntity entity) => entity.path.endsWith('_test.dart') &&
337 338
      globals.fs.isFileSync(entity.path))
      .map((FileSystemEntity entity) => globals.fs.path.absolute(entity.path));
339
}