test.dart 7.88 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 '../base/io.dart';
10
import '../base/logger.dart';
11
import '../base/os.dart';
12 13
import '../base/platform.dart';
import '../base/process_manager.dart';
14
import '../cache.dart';
15
import '../globals.dart';
16
import '../runner/flutter_command.dart';
17
import '../test/coverage_collector.dart';
18 19 20
import '../test/event_printer.dart';
import '../test/runner.dart';
import '../test/watcher.dart';
21 22

class TestCommand extends FlutterCommand {
23
  TestCommand({ bool verboseHelp: false }) {
24
    requiresPubspecYaml();
25
    usesPubOption();
26 27 28 29 30 31 32 33 34 35 36 37
    argParser.addOption('name',
      help: 'A regular expression matching substrings of the names of tests to run.',
      valueHelp: 'regexp',
      allowMultiple: true,
      splitCommas: false,
    );
    argParser.addOption('plain-name',
      help: 'A plain-text substring of the names of tests to run.',
      valueHelp: 'substring',
      allowMultiple: true,
      splitCommas: false,
    );
38 39 40 41 42 43 44 45
    argParser.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.'
    );
46 47
    argParser.addFlag('coverage',
      defaultsTo: false,
48
      negatable: false,
49 50
      help: 'Whether to collect coverage information.'
    );
51 52 53
    argParser.addFlag('merge-coverage',
      defaultsTo: false,
      negatable: false,
Josh Soref's avatar
Josh Soref committed
54
      help: 'Whether to merge coverage data with "coverage/lcov.base.info".\n'
55
            'Implies collecting coverage data. (Requires lcov)'
56
    );
57 58 59 60 61
    argParser.addFlag('ipv6',
        negatable: false,
        hide: true,
        help: 'Whether to use IPv6 for the test harness server socket.'
    );
62 63 64 65
    argParser.addOption('coverage-path',
      defaultsTo: 'coverage/lcov.info',
      help: 'Where to store coverage information (if coverage is enabled).'
    );
66 67 68 69 70
    argParser.addFlag('machine',
        hide: !verboseHelp,
        negatable: false,
        help: 'Handle machine structured JSON command input\n'
            'and provide output and progress in machine friendly format.');
71 72 73
    argParser.addFlag('preview-dart-2',
        hide: !verboseHelp,
        help: 'Preview Dart 2.0 functionality.');
Ian Hickson's avatar
Ian Hickson committed
74 75
  }

76
  @override
Ian Hickson's avatar
Ian Hickson committed
77
  String get name => 'test';
78 79

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

82
  Future<bool> _collectCoverageData(CoverageCollector collector, { bool mergeCoverageData: false }) async {
83 84
    final Status status = logger.startProgress('Collecting coverage information...');
    final String coverageData = await collector.finalizeCoverage(
85
      timeout: const Duration(seconds: 30),
86
    );
Devon Carew's avatar
Devon Carew committed
87
    status.stop();
88
    printTrace('coverage information collection complete');
89 90
    if (coverageData == null)
      return false;
91

92 93
    final String coveragePath = argResults['coverage-path'];
    final File coverageFile = fs.file(coveragePath)
94 95 96 97
      ..createSync(recursive: true)
      ..writeAsStringSync(coverageData, flush: true);
    printTrace('wrote coverage data to $coveragePath (size=${coverageData.length})');

98
    const String baseCoverageData = 'coverage/lcov.base.info';
99
    if (mergeCoverageData) {
100
      if (!platform.isLinux) {
101 102 103 104 105 106 107
        printError(
          'Merging coverage data is supported only on Linux because it '
          'requires the "lcov" tool.'
        );
        return false;
      }

108
      if (!fs.isFileSync(baseCoverageData)) {
109 110 111 112 113
        printError('Missing "$baseCoverageData". Unable to merge coverage data.');
        return false;
      }

      if (os.which('lcov') == null) {
114
        String installMessage = 'Please install lcov.';
115
        if (platform.isLinux)
116
          installMessage = 'Consider running "sudo apt-get install lcov".';
117
        else if (platform.isMacOS)
118 119
          installMessage = 'Consider running "brew install lcov".';
        printError('Missing "lcov" tool. Unable to merge coverage data.\n$installMessage');
120 121 122
        return false;
      }

123
      final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools');
124
      try {
125 126
        final File sourceFile = coverageFile.copySync(fs.path.join(tempDir.path, 'lcov.source.info'));
        final ProcessResult result = processManager.runSync(<String>[
127
          'lcov',
128 129 130 131 132 133 134 135 136 137 138 139 140
          '--add-tracefile', baseCoverageData,
          '--add-tracefile', sourceFile.path,
          '--output-file', coverageFile.path,
        ]);
        if (result.exitCode != 0)
          return false;
      } finally {
        tempDir.deleteSync(recursive: true);
      }
    }
    return true;
  }

141 142 143 144 145 146 147 148 149 150 151 152
  @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).');
    }
  }

153
  @override
154
  Future<FlutterCommandResult> runCommand() async {
155 156
    final List<String> names = argResults['name'];
    final List<String> plainNames = argResults['plain-name'];
157

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

160 161 162 163 164
    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);
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 178
            '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".'
179 180
        );
      }
181
    }
182 183 184 185 186 187

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

188 189
    final bool machine = argResults['machine'];
    if (collector != null && machine) {
190 191 192 193 194 195 196
      throwToolExit(
          "The test command doesn't support --machine and coverage together");
    }

    TestWatcher watcher;
    if (collector != null) {
      watcher = collector;
197
    } else if (machine) {
198 199
      watcher = new EventPrinter();
    }
200 201 202

    Cache.releaseLockEarly();

203 204
    final int result = await runTests(files,
        workDir: workDir,
205 206
        names: names,
        plainNames: plainNames,
207 208 209
        watcher: watcher,
        enableObservatory: collector != null || startPaused,
        startPaused: startPaused,
210
        ipv6: argResults['ipv6'],
211
        machine: machine,
212
        previewDart2: argResults['preview-dart-2'],
213
        );
214

215
    if (collector != null) {
216
      if (!await _collectCoverageData(collector, mergeCoverageData: argResults['merge-coverage']))
217
        throwToolExit(null);
218 219
    }

220 221
    if (result != 0)
      throwToolExit(null);
222
    return const FlutterCommandResult(ExitStatus.success);
223
  }
224
}
225 226 227 228 229 230 231

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