test.dart 6.36 KB
Newer Older
1 2 3 4 5 6 7 8
// 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';
import 'dart:io';

import 'package:path/path.dart' as path;
Ian Hickson's avatar
Ian Hickson committed
9
import 'package:test/src/executable.dart' as executable; // ignore: implementation_imports
10

11
import '../base/logger.dart';
12
import '../base/os.dart';
13
import '../cache.dart';
14
import '../dart/package_map.dart';
15
import '../globals.dart';
16
import '../runner/flutter_command.dart';
17
import '../test/coverage_collector.dart';
18
import '../test/flutter_platform.dart' as loader;
19
import '../toolchain.dart';
20 21

class TestCommand extends FlutterCommand {
Ian Hickson's avatar
Ian Hickson committed
22
  TestCommand() {
23
    usesPubOption();
24 25
    argParser.addFlag('coverage',
      defaultsTo: false,
26
      negatable: false,
27 28
      help: 'Whether to collect coverage information.'
    );
29 30 31 32
    argParser.addFlag('merge-coverage',
      defaultsTo: false,
      negatable: false,
      help: 'Whether to merge converage data with "coverage/lcov.base.info". '
33
            'Implies collecting coverage data. (Requires lcov)'
34
    );
35 36 37 38
    argParser.addOption('coverage-path',
      defaultsTo: 'coverage/lcov.info',
      help: 'Where to store coverage information (if coverage is enabled).'
    );
Ian Hickson's avatar
Ian Hickson committed
39 40
  }

41
  @override
Ian Hickson's avatar
Ian Hickson committed
42
  String get name => 'test';
43 44

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

47
  @override
48
  Validator commandValidator = () {
49
    if (!FileSystemEntity.isFileSync('pubspec.yaml')) {
50 51 52 53 54
      printError(
        '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).');
55 56 57 58
      return false;
    }
    return true;
  };
59 60 61

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

67 68 69 70
  Directory get _currentPackageTestDir {
    // 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.
    return new Directory('test');
71 72 73 74 75
  }

  Future<int> _runTests(List<String> testArgs, Directory testDirectory) async {
    Directory currentDirectory = Directory.current;
    try {
Ian Hickson's avatar
Ian Hickson committed
76 77
      if (testDirectory != null) {
        printTrace('switching to directory $testDirectory to run tests');
78
        PackageMap.globalPackagesPath = path.normalize(path.absolute(PackageMap.globalPackagesPath));
Ian Hickson's avatar
Ian Hickson committed
79 80 81 82 83
        Directory.current = testDirectory;
      }
      printTrace('running test package with arguments: $testArgs');
      await executable.main(testArgs);
      printTrace('test package returned with exit code $exitCode');
84

Ian Hickson's avatar
Ian Hickson committed
85
      return exitCode;
86 87 88 89 90
    } finally {
      Directory.current = currentDirectory;
    }
  }

91 92 93 94
  Future<bool> _collectCoverageData(CoverageCollector collector, { bool mergeCoverageData: false }) async {
    Status status = logger.startProgress('Collecting coverage information...');
    String coverageData = await collector.finalizeCoverage();
    status.stop(showElapsedTime: true);
95 96
    if (coverageData == null)
      return false;
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

    String coveragePath = argResults['coverage-path'];
    File coverageFile = new File(coveragePath)
      ..createSync(recursive: true)
      ..writeAsStringSync(coverageData, flush: true);
    printTrace('wrote coverage data to $coveragePath (size=${coverageData.length})');

    String baseCoverageData = 'coverage/lcov.base.info';
    if (mergeCoverageData) {
      if (!os.isLinux) {
        printError(
          'Merging coverage data is supported only on Linux because it '
          'requires the "lcov" tool.'
        );
        return false;
      }

      if (!FileSystemEntity.isFileSync(baseCoverageData)) {
        printError('Missing "$baseCoverageData". Unable to merge coverage data.');
        return false;
      }

      if (os.which('lcov') == null) {
120 121 122 123 124 125
        String installMessage = 'Please install lcov.';
        if (os.isLinux)
          installMessage = 'Consider running "sudo apt-get install lcov".';
        else if (os.isMacOS)
          installMessage = 'Consider running "brew install lcov".';
        printError('Missing "lcov" tool. Unable to merge coverage data.\n$installMessage');
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
        return false;
      }

      Directory tempDir = Directory.systemTemp.createTempSync('flutter_tools');
      try {
        File sourceFile = coverageFile.copySync(path.join(tempDir.path, 'lcov.source.info'));
        ProcessResult result = Process.runSync('lcov', <String>[
          '--add-tracefile', baseCoverageData,
          '--add-tracefile', sourceFile.path,
          '--output-file', coverageFile.path,
        ]);
        if (result.exitCode != 0)
          return false;
      } finally {
        tempDir.deleteSync(recursive: true);
      }
    }
    return true;
  }

146
  @override
147
  Future<int> runCommand() async {
148 149
    List<String> testArgs = argResults.rest.map((String testPath) => path.absolute(testPath)).toList();

150
    if (!commandValidator())
151 152
      return 1;

Ian Hickson's avatar
Ian Hickson committed
153
    Directory testDir;
154

155
    if (testArgs.isEmpty) {
Ian Hickson's avatar
Ian Hickson committed
156
      testDir = _currentPackageTestDir;
157 158 159 160 161
      if (!testDir.existsSync()) {
        printError("Test directory '${testDir.path}' not found.");
        return 1;
      }

162
      testArgs.addAll(_findTests(testDir));
163
    }
164

Ian Hickson's avatar
Ian Hickson committed
165
    testArgs.insert(0, '--');
166
    if (!terminal.supportsColor)
167
      testArgs.insertAll(0, <String>['--no-color', '-rexpanded']);
168

169 170 171
    if (argResults['coverage'])
      testArgs.insert(0, '--concurrency=1');

172
    loader.installHook();
173 174 175
    loader.shellPath = tools.getHostToolPath(HostTool.SkyShell);
    if (!FileSystemEntity.isFileSync(loader.shellPath)) {
        printError('Cannot find Flutter shell at ${loader.shellPath}');
Ian Hickson's avatar
Ian Hickson committed
176 177
      return 1;
    }
178 179 180

    Cache.releaseLockEarly();

181
    CoverageCollector collector = CoverageCollector.instance;
182
    collector.enabled = argResults['coverage'] || argResults['merge-coverage'];
183 184 185 186

    int result = await _runTests(testArgs, testDir);

    if (collector.enabled) {
187 188
      if (!await _collectCoverageData(collector, mergeCoverageData: argResults['merge-coverage']))
        return 1;
189 190 191
    }

    return result;
192
  }
193
}