test.dart 6.14 KB
Newer Older
1 2 3 4 5 6
// 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';

7
import '../base/common.dart';
8
import '../base/file_system.dart';
9
import '../cache.dart';
10
import '../runner/flutter_command.dart';
11
import '../test/coverage_collector.dart';
12 13 14
import '../test/event_printer.dart';
import '../test/runner.dart';
import '../test/watcher.dart';
15 16

class TestCommand extends FlutterCommand {
17
  TestCommand({ bool verboseHelp = false }) {
18
    requiresPubspecYaml();
19
    usesPubOption();
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
    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'
              'Instructions for connecting with a debugger and printed to the\n'
              'console once the test has started.',
      )
      ..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.',
      )
65 66 67 68 69
      ..addFlag('preview-dart-2',
        defaultsTo: true,
        hide: !verboseHelp,
        help: 'Preview Dart 2.0 functionality.',
      )
70 71 72 73 74
      ..addFlag('track-widget-creation',
        negatable: false,
        hide: !verboseHelp,
        help: 'Track widget creation locations.\n'
              'This enables testing of features such as the widget inspector.',
75 76 77 78 79
      )
      ..addFlag('update-goldens',
        negatable: false,
        help: 'Whether matchesGoldenFile() calls within your test methods should\n'
              'update the golden files rather than test for an existing match.',
80
      );
Ian Hickson's avatar
Ian Hickson committed
81 82
  }

83
  @override
Ian Hickson's avatar
Ian Hickson committed
84
  String get name => 'test';
85 86

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

89 90 91 92 93 94 95 96 97 98 99 100
  @override
  Future<Null> validateCommand() async {
    await super.validateCommand();
    if (!fs.isFileSync('pubspec.yaml')) {
      throwToolExit(
          'Error: No pubspec.yaml file found in the current working directory.\n'
              'Run this command from the root of your project. Test files must be\n'
              'called *_test.dart and must reside in the package\'s \'test\'\n'
              'directory (or one of its subdirectories).');
    }
  }

101
  @override
102
  Future<FlutterCommandResult> runCommand() async {
103 104
    final List<String> names = argResults['name'];
    final List<String> plainNames = argResults['plain-name'];
105

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

108 109 110 111 112
    final bool startPaused = argResults['start-paused'];
    if (startPaused && files.length != 1) {
      throwToolExit(
          'When using --start-paused, you must specify a single test file to run.',
          exitCode: 1);
113 114
    }

115 116
    Directory workDir;
    if (files.isEmpty) {
117 118 119
      // 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');
120 121
      if (!workDir.existsSync())
        throwToolExit('Test directory "${workDir.path}" not found.');
122
      files = _findTests(workDir).toList();
123 124
      if (files.isEmpty) {
        throwToolExit(
125 126
            'Test directory "${workDir.path}" does not appear to contain any test files.\n'
                'Test files must be in that directory and end with the pattern "_test.dart".'
127 128
        );
      }
129
    }
130 131 132 133 134 135

    CoverageCollector collector;
    if (argResults['coverage'] || argResults['merge-coverage']) {
      collector = new CoverageCollector();
    }

136 137
    final bool machine = argResults['machine'];
    if (collector != null && machine) {
138 139 140 141 142 143 144
      throwToolExit(
          "The test command doesn't support --machine and coverage together");
    }

    TestWatcher watcher;
    if (collector != null) {
      watcher = collector;
145
    } else if (machine) {
146 147
      watcher = new EventPrinter();
    }
148 149 150

    Cache.releaseLockEarly();

151 152 153 154 155 156 157 158 159 160
    final int result = await runTests(
      files,
      workDir: workDir,
      names: names,
      plainNames: plainNames,
      watcher: watcher,
      enableObservatory: collector != null || startPaused,
      startPaused: startPaused,
      ipv6: argResults['ipv6'],
      machine: machine,
161
      previewDart2: argResults['preview-dart-2'],
162
      trackWidgetCreation: argResults['track-widget-creation'],
163
      updateGoldens: argResults['update-goldens'],
164
    );
165

166
    if (collector != null) {
167 168
      if (!await collector.collectCoverageData(
          argResults['coverage-path'], mergeCoverageData: argResults['merge-coverage']))
169
        throwToolExit(null);
170 171
    }

172 173
    if (result != 0)
      throwToolExit(null);
174
    return const FlutterCommandResult(ExitStatus.success);
175
  }
176
}
177 178 179 180 181 182 183

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));
}