test.dart 10.1 KB
Newer Older
1 2 3 4 5
// Copyright 2015 The Chromium Authors. All rights reserved.
// 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 '../base/platform.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';
18
import '../project.dart';
19
import '../runner/flutter_command.dart';
20
import '../test/coverage_collector.dart';
21 22 23
import '../test/event_printer.dart';
import '../test/runner.dart';
import '../test/watcher.dart';
24

25
class TestCommand extends FastFlutterCommand {
26
  TestCommand({ bool verboseHelp = false }) {
27
    requiresPubspecYaml();
28
    usesPubOption();
29 30 31 32 33 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,
      )
      ..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
45
              'Instructions for connecting with a debugger are printed to the '
46 47
              'console once the test has started.',
      )
48 49 50 51 52 53 54
      ..addFlag('disable-service-auth-codes',
        hide: !verboseHelp,
        defaultsTo: false,
        negatable: false,
        help: 'No longer require an authentication code to connect to the VM '
              'service (not recommended).'
      )
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
      ..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.',
      )
      ..addFlag('track-widget-creation',
        negatable: false,
        hide: !verboseHelp,
        help: 'Track widget creation locations.\n'
              'This enables testing of features such as the widget inspector.',
86 87 88
      )
      ..addFlag('update-goldens',
        negatable: false,
89
        help: 'Whether matchesGoldenFile() calls within your test methods should '
90
              'update the golden files rather than test for an existing match.',
91 92 93 94 95
      )
      ..addOption('concurrency',
        abbr: 'j',
        defaultsTo: math.max<int>(1, platform.numberOfProcessors - 2).toString(),
        help: 'The number of concurrent test processes to run.',
96 97 98 99 100 101 102
        valueHelp: 'jobs'
      )
      ..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.',
103 104 105 106 107
      )
      ..addOption('platform',
        allowed: const <String>['tester', 'chrome'],
        defaultsTo: 'tester',
        help: 'The platform to run the unit tests on. Defaults to "tester".'
108
      );
Ian Hickson's avatar
Ian Hickson committed
109 110
  }

111
  @override
112 113 114 115 116 117 118 119 120
  Future<Set<DevelopmentArtifact>> get requiredArtifacts async {
    final Set<DevelopmentArtifact> results = <DevelopmentArtifact>{
      DevelopmentArtifact.universal,
    };
    if (argResults['platform'] == 'chrome') {
      results.add(DevelopmentArtifact.web);
    }
    return results;
  }
121

122
  @override
Ian Hickson's avatar
Ian Hickson committed
123
  String get name => 'test';
124 125

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

128
  @override
129
  Future<FlutterCommandResult> runCommand() async {
130
    await cache.updateAll(await requiredArtifacts);
131 132
    if (!fs.isFileSync('pubspec.yaml')) {
      throwToolExit(
133
        'Error: No pubspec.yaml file found in the current working directory.\n'
134 135
        'Run this command from the root of your project. Test files must be '
        'called *_test.dart and must reside in the package\'s \'test\' '
136
        'directory (or one of its subdirectories).');
137
    }
138 139 140
    if (shouldRunPub) {
      await pubGet(context: PubContext.getVerifyContext(name), skipPubspecYamlCheck: true);
    }
141
    final bool buildTestAssets = argResults['test-assets'];
142 143
    final List<String> names = argResults['name'];
    final List<String> plainNames = argResults['plain-name'];
144
    final FlutterProject flutterProject = FlutterProject.current();
145

146 147 148 149
    if (buildTestAssets && flutterProject.manifest.assets.isNotEmpty) {
      await _buildTestAsset();
    }

150
    Iterable<String> files = argResults.rest.map<String>((String testPath) => fs.path.absolute(testPath)).toList();
151

152 153 154
    final bool startPaused = argResults['start-paused'];
    if (startPaused && files.length != 1) {
      throwToolExit(
155 156 157 158 159 160 161 162 163 164
        'When using --start-paused, you must specify a single test file to run.',
        exitCode: 1,
      );
    }

    final int jobs = int.tryParse(argResults['concurrency']);
    if (jobs == null || jobs <= 0 || !jobs.isFinite) {
      throwToolExit(
        'Could not parse -j/--concurrency argument. It must be an integer greater than zero.'
      );
165 166
    }

167 168
    Directory workDir;
    if (files.isEmpty) {
169 170 171
      // 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.
      workDir = fs.directory('test');
172 173
      if (!workDir.existsSync())
        throwToolExit('Test directory "${workDir.path}" not found.');
174
      files = _findTests(workDir).toList();
175 176
      if (files.isEmpty) {
        throwToolExit(
177
            'Test directory "${workDir.path}" does not appear to contain any test files.\n'
178
            'Test files must be in that directory and end with the pattern "_test.dart".'
179 180
        );
      }
181 182 183 184 185 186 187 188 189 190
    } else {
      final List<String> fileCopy = <String>[];
      for (String file in files) {
        if (file.endsWith(platform.pathSeparator)) {
          fileCopy.addAll(_findTests(fs.directory(file)));
        } else {
          fileCopy.add(file);
        }
      }
      files = fileCopy;
191
    }
192 193 194

    CoverageCollector collector;
    if (argResults['coverage'] || argResults['merge-coverage']) {
195
      collector = CoverageCollector(
196
        flutterProject: FlutterProject.current(),
197
      );
198 199
    }

200 201
    final bool machine = argResults['machine'];
    if (collector != null && machine) {
202
      throwToolExit("The test command doesn't support --machine and coverage together");
203 204 205 206 207
    }

    TestWatcher watcher;
    if (collector != null) {
      watcher = collector;
208
    } else if (machine) {
209
      watcher = EventPrinter();
210
    }
211 212 213

    Cache.releaseLockEarly();

214
    // Run builders once before all tests.
215
    if (flutterProject.hasBuilders) {
216 217 218 219 220 221 222 223 224 225 226 227
      final CodegenDaemon codegenDaemon = await codeGenerator.daemon(flutterProject);
      codegenDaemon.startBuild();
      await for (CodegenStatus status in codegenDaemon.buildResults) {
        if (status == CodegenStatus.Succeeded) {
          break;
        }
        if (status == CodegenStatus.Failed) {
          throwToolExit('Code generation failed.');
        }
      }
    }

228 229 230
    final bool disableServiceAuthCodes =
      argResults['disable-service-auth-codes'];

231 232 233 234 235 236 237 238
    final int result = await runTests(
      files,
      workDir: workDir,
      names: names,
      plainNames: plainNames,
      watcher: watcher,
      enableObservatory: collector != null || startPaused,
      startPaused: startPaused,
239
      disableServiceAuthCodes: disableServiceAuthCodes,
240 241 242
      ipv6: argResults['ipv6'],
      machine: machine,
      trackWidgetCreation: argResults['track-widget-creation'],
243
      updateGoldens: argResults['update-goldens'],
244
      concurrency: jobs,
245
      buildTestAssets: buildTestAssets,
246
      flutterProject: flutterProject,
247
      web: argResults['platform'] == 'chrome',
248
    );
249

250
    if (collector != null) {
251 252
      if (!await collector.collectCoverageData(
          argResults['coverage-path'], mergeCoverageData: argResults['merge-coverage']))
253
        throwToolExit(null);
254 255
    }

256 257
    if (result != 0)
      throwToolExit(null);
258
    return const FlutterCommandResult(ExitStatus.success);
259
  }
260 261 262 263 264 265 266

  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');
    }
267
    if (_needRebuild(assetBundle.entries)) {
268
      await writeBundle(fs.directory(fs.path.join('build', 'unit_test_assets')),
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
          assetBundle.entries);
    }
  }
  bool _needRebuild(Map<String, DevFSContent> entries) {
    final File manifest = fs.file(fs.path.join('build', 'unit_test_assets', 'AssetManifest.json'));
    if (!manifest.existsSync()) {
      return true;
    }
    final DateTime lastModified = manifest.lastModifiedSync();
    final File pub = fs.file('pubspec.yaml');
    if (pub.lastModifiedSync().isAfter(lastModified)) {
      return true;
    }

    for (DevFSFileContent entry in entries.values.whereType<DevFSFileContent>()) {
      // Calling isModified to access file stats first in order for isModifiedAfter
      // to work.
      if (entry.isModified && entry.isModifiedAfter(lastModified)) {
        return true;
      }
    }
    return false;
291
  }
292
}
293 294 295 296 297 298 299

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