test.dart 20.8 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
// @dart = 2.8

7
import 'dart:math' as math;
8

9 10
import 'package:meta/meta.dart';

11
import '../asset.dart';
12
import '../base/common.dart';
13
import '../base/file_system.dart';
14
import '../build_info.dart';
15
import '../bundle_builder.dart';
16
import '../devfs.dart';
17
import '../device.dart';
18
import '../globals.dart' as globals;
19
import '../project.dart';
20
import '../runner/flutter_command.dart';
21
import '../test/coverage_collector.dart';
22 23
import '../test/event_printer.dart';
import '../test/runner.dart';
24
import '../test/test_wrapper.dart';
25
import '../test/watcher.dart';
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
/// The name of the directory where Integration Tests are placed.
///
/// When there are test files specified for the test command that are part of
/// this directory, *relative to the package root*, the files will be executed
/// as Integration Tests.
const String _kIntegrationTestDirectory = 'integration_test';

/// A command to run tests.
///
/// This command has two modes of execution:
///
/// ## Unit / Widget Tests
///
/// These tests run in the Flutter Tester, which is a desktop-based Flutter
/// embedder. In this mode, tests are quick to compile and run.
///
/// By default, if no flags are passed to the `flutter test` command, the Tool
/// will recursively find all files within the `test/` directory that end with
/// the `*_test.dart` suffix, and run them in a single invocation.
///
/// See:
/// - https://flutter.dev/docs/cookbook/testing/unit/introduction
/// - https://flutter.dev/docs/cookbook/testing/widget/introduction
///
/// ## Integration Tests
///
/// These tests run in a connected Flutter Device, similar to `flutter run`. As
/// a result, iteration is slower because device-based artifacts have to be
/// built.
///
/// Integration tests should be placed in the `integration_test/` directory of
/// your package. To run these tests, use `flutter test integration_test`.
///
/// See:
/// - https://flutter.dev/docs/testing/integration-tests
class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
63 64 65
  TestCommand({
    bool verboseHelp = false,
    this.testWrapper = const TestWrapper(),
66
    this.testRunner = const FlutterTestRunner(),
67
  }) : assert(testWrapper != null) {
68
    requiresPubspecYaml();
69
    usesPubOption();
70
    addNullSafetyModeOptions(hide: !verboseHelp);
71 72
    usesTrackWidgetCreation(verboseHelp: verboseHelp);
    addEnableExperimentation(hide: !verboseHelp);
73
    usesDartDefineOption();
74
    usesWebRendererOption();
75
    usesDeviceUserOption();
76
    usesFlavorOption();
77

78 79 80 81 82 83 84 85 86 87 88
    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,
      )
89 90
      ..addOption('tags',
        abbr: 't',
91
        help: 'Run only tests associated with the specified tags. See: https://pub.dev/packages/test#tagging-tests',
92 93 94
      )
      ..addOption('exclude-tags',
        abbr: 'x',
95
        help: 'Run only tests that do not have the specified tags. See: https://pub.dev/packages/test#tagging-tests',
96
      )
97 98 99 100 101
      ..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
102
              'Instructions for connecting with a debugger are printed to the '
103 104
              'console once the test has started.',
      )
105 106 107 108
      ..addFlag('run-skipped',
        defaultsTo: false,
        help: 'Run skipped tests instead of skipping them.',
      )
109 110 111
      ..addFlag('disable-service-auth-codes',
        defaultsTo: false,
        negatable: false,
112 113 114
        hide: !verboseHelp,
        help: '(deprecated) Allow connections to the VM service without using authentication codes. '
              '(Not recommended! This can open your device to remote code execution attacks!)'
115
      )
116 117 118 119 120 121 122 123 124
      ..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'
125
              'Implies collecting coverage data. (Requires lcov.)',
126 127 128
      )
      ..addFlag('ipv6',
        negatable: false,
129
        hide: !verboseHelp,
130 131 132 133 134 135 136 137 138
        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,
139
        help: 'Handle machine structured JSON command input '
140 141
              'and provide output and progress in machine friendly format.',
      )
142 143
      ..addFlag('update-goldens',
        negatable: false,
144
        help: 'Whether "matchesGoldenFile()" calls within your test methods should ' // flutter_ignore: golden_tag (see analyze.dart)
145
              'update the golden files rather than test for an existing match.',
146 147 148
      )
      ..addOption('concurrency',
        abbr: 'j',
149
        defaultsTo: math.max<int>(1, globals.platform.numberOfProcessors - 2).toString(),
150 151
        help: 'The number of concurrent test processes to run. This will be ignored '
              'when running integration tests.',
152
        valueHelp: 'jobs',
153 154 155 156
      )
      ..addFlag('test-assets',
        defaultsTo: true,
        negatable: true,
157 158 159
        help: 'Whether to build the assets bundle for testing. '
              'This takes additional time before running the tests. '
              'Consider using "--no-test-assets" if assets are not required.',
160
      )
161 162 163 164
      // --platform is not supported to be used by Flutter developers. It only
      // exists to test the Flutter framework itself and may be removed entirely
      // in the future. Developers should either use plain `flutter test`, or
      // `package:integration_test` instead.
165 166
      ..addOption('platform',
        allowed: const <String>['tester', 'chrome'],
167
        hide: !verboseHelp,
168
        defaultsTo: 'tester',
169 170
        help: 'Selects the test backend.',
        allowedHelp: <String, String>{
171
          'tester': 'Run tests using the VM-based test environment.',
172 173 174 175
          'chrome': '(deprecated) Run tests using the Google Chrome web browser. '
                    'This value is intended for testing the Flutter framework '
                    'itself and may be removed at any time.',
        },
176 177
      )
      ..addOption('test-randomize-ordering-seed',
178 179 180 181
        help: 'The seed to randomize the execution order of test cases within test files. '
              'Must be a 32bit unsigned integer or the string "random", '
              'which indicates that a seed should be selected randomly. '
              'By default, tests run in the order they are declared.',
182
      )
183 184 185 186 187 188 189 190 191 192
      ..addOption('total-shards',
        help: 'Tests can be sharded with the "--total-shards" and "--shard-index" '
              'arguments, allowing you to split up your test suites and run '
              'them separately.'
      )
      ..addOption('shard-index',
          help: 'Tests can be sharded with the "--total-shards" and "--shard-index" '
              'arguments, allowing you to split up your test suites and run '
              'them separately.'
      )
193 194 195
      ..addFlag('enable-vmservice',
        defaultsTo: false,
        hide: !verboseHelp,
196 197 198 199 200
        help: 'Enables the VM service without "--start-paused". This flag is '
              'intended for use with tests that will use "dart:developer" to '
              'interact with the VM service at runtime.\n'
              'This flag is ignored if "--start-paused" or coverage are requested, as '
              'the VM service will be enabled in those cases regardless.'
201 202 203 204
      )
      ..addOption('reporter',
        abbr: 'r',
        defaultsTo: 'compact',
205 206 207 208 209 210 211 212
        help: 'Set how to print test results.',
        allowed: <String>['compact', 'expanded', 'json'],
        allowedHelp: <String, String>{
          'compact':  'A single line that updates dynamically.',
          'expanded': 'A separate line for each update. May be preferred when logging to a file or in continuous integration.',
          'json':     'A machine-readable format. See: https://dart.dev/go/test-docs/json_reporter.md',
        },
      )
213
      ..addOption('timeout',
214 215 216 217
        help: 'The default test timeout, specified either '
              'in seconds (e.g. "60s"), '
              'as a multiplier of the default timeout (e.g. "2x"), '
              'or as the string "none" to disable the timeout entirely.',
218
        defaultsTo: '30s',
219
      );
220 221
    addDdsOptions(verboseHelp: verboseHelp);
    usesFatalWarningsOption(verboseHelp: verboseHelp);
Ian Hickson's avatar
Ian Hickson committed
222 223
  }

224 225 226
  /// The interface for starting and configuring the tester.
  final TestWrapper testWrapper;

227 228 229
  /// Interface for running the tester process.
  final FlutterTestRunner testRunner;

230 231 232 233 234 235
  @visibleForTesting
  bool get isIntegrationTest => _isIntegrationTest;
  bool _isIntegrationTest = false;

  List<String> _testFiles = <String>[];

236
  @override
237
  Future<Set<DevelopmentArtifact>> get requiredArtifacts async {
238 239 240 241
    final Set<DevelopmentArtifact> results = _isIntegrationTest
        // Use [DeviceBasedDevelopmentArtifacts].
        ? await super.requiredArtifacts
        : <DevelopmentArtifact>{};
242
    if (stringArgDeprecated('platform') == 'chrome') {
243 244 245 246
      results.add(DevelopmentArtifact.web);
    }
    return results;
  }
247

248
  @override
Ian Hickson's avatar
Ian Hickson committed
249
  String get name => 'test';
250 251

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

254 255 256
  @override
  String get category => FlutterCommandCategory.project;

257 258 259 260 261
  @override
  Future<FlutterCommandResult> verifyThenRunCommand(String commandPath) {
    _testFiles = argResults.rest.map<String>(globals.fs.path.absolute).toList();
    if (_testFiles.isEmpty) {
      // We don't scan the entire package, only the test/ subdirectory, so that
nt4f04uNd's avatar
nt4f04uNd committed
262
      // files with names like "hit_test.dart" don't get run.
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
      final Directory testDir = globals.fs.directory('test');
      if (!testDir.existsSync()) {
        throwToolExit('Test directory "${testDir.path}" not found.');
      }
      _testFiles = _findTests(testDir).toList();
      if (_testFiles.isEmpty) {
        throwToolExit(
          'Test directory "${testDir.path}" does not appear to contain any test files.\n'
          'Test files must be in that directory and end with the pattern "_test.dart".'
        );
      }
    } else {
      _testFiles = <String>[
        for (String path in _testFiles)
          if (globals.fs.isDirectorySync(path))
            ..._findTests(globals.fs.directory(path))
          else
280
            globals.fs.path.normalize(globals.fs.path.absolute(path)),
281 282 283 284 285 286 287
      ];
    }

    // This needs to be set before [super.verifyThenRunCommand] so that the
    // correct [requiredArtifacts] can be identified before [run] takes place.
    _isIntegrationTest = _shouldRunAsIntegrationTests(globals.fs.currentDirectory.absolute.path, _testFiles);

288
    globals.printTrace(
289 290 291 292 293 294
      'Found ${_testFiles.length} files which will be executed as '
      '${_isIntegrationTest ? 'Integration' : 'Widget'} Tests.',
    );
    return super.verifyThenRunCommand(commandPath);
  }

295
  @override
296
  Future<FlutterCommandResult> runCommand() async {
297
    if (!globals.fs.isFileSync('pubspec.yaml')) {
298
      throwToolExit(
299
        'Error: No pubspec.yaml file found in the current working directory.\n'
300
        'Run this command from the root of your project. Test files must be '
301
        "called *_test.dart and must reside in the package's 'test' "
302
        'directory (or one of its subdirectories).');
303
    }
304
    final FlutterProject flutterProject = FlutterProject.current();
305
    final bool buildTestAssets = boolArgDeprecated('test-assets');
306 307
    final List<String> names = stringsArg('name');
    final List<String> plainNames = stringsArg('plain-name');
308 309
    final String tags = stringArgDeprecated('tags');
    final String excludeTags = stringArgDeprecated('exclude-tags');
310
    final BuildInfo buildInfo = await getBuildInfo(forcedBuildMode: BuildMode.debug);
311

312
    if (buildInfo.packageConfig['test_api'] == null) {
313
      throwToolExit(
314 315 316 317 318 319 320 321 322
        'Error: cannot run without a dependency on either "package:flutter_test" or "package:test". '
        'Ensure the following lines are present in your pubspec.yaml:'
        '\n\n'
        'dev_dependencies:\n'
        '  flutter_test:\n'
        '    sdk: flutter\n',
      );
    }

323
    String testAssetDirectory;
324
    if (buildTestAssets) {
325
      await _buildTestAsset();
326 327
      testAssetDirectory = globals.fs.path.
        join(flutterProject?.directory?.path ?? '', 'build', 'unit_test_assets');
328 329
    }

330
    final bool startPaused = boolArgDeprecated('start-paused');
331
    if (startPaused && _testFiles.length != 1) {
332
      throwToolExit(
333 334 335 336 337
        'When using --start-paused, you must specify a single test file to run.',
        exitCode: 1,
      );
    }

338
    int jobs = int.tryParse(stringArgDeprecated('concurrency'));
339 340 341 342
    if (jobs == null || jobs <= 0 || !jobs.isFinite) {
      throwToolExit(
        'Could not parse -j/--concurrency argument. It must be an integer greater than zero.'
      );
343
    }
344 345
    if (_isIntegrationTest) {
      if (argResults.wasParsed('concurrency')) {
346
        globals.printStatus(
347 348
          '-j/--concurrency was parsed but will be ignored, this option is not '
          'supported when running Integration Tests.',
349 350
        );
      }
351 352 353
      // Running with concurrency will result in deploying multiple test apps
      // on the connected device concurrently, which is not supported.
      jobs = 1;
354
    }
355

356
    final int shardIndex = int.tryParse(stringArgDeprecated('shard-index') ?? '');
357 358 359 360 361
    if (shardIndex != null && (shardIndex < 0 || !shardIndex.isFinite)) {
      throwToolExit(
          'Could not parse --shard-index=$shardIndex argument. It must be an integer greater than -1.');
    }

362
    final int totalShards = int.tryParse(stringArgDeprecated('total-shards') ?? '');
363 364 365 366 367 368 369 370 371 372 373 374 375 376
    if (totalShards != null && (totalShards <= 0 || !totalShards.isFinite)) {
      throwToolExit(
          'Could not parse --total-shards=$totalShards argument. It must be an integer greater than zero.');
    }

    if (totalShards != null && shardIndex == null) {
      throwToolExit(
          'If you set --total-shards you need to also set --shard-index.');
    }
    if (shardIndex != null && totalShards == null) {
      throwToolExit(
          'If you set --shard-index you need to also set --total-shards.');
    }

377
    final bool machine = boolArgDeprecated('machine');
378
    CoverageCollector collector;
379
    if (boolArgDeprecated('coverage') || boolArgDeprecated('merge-coverage')) {
380
      final String projectName = flutterProject.manifest.appName;
381
      collector = CoverageCollector(
382
        verbose: !machine,
383
        libraryPredicate: (String libraryName) => libraryName.contains(projectName),
384
        packagesPath: buildInfo.packagesPath
385
      );
386 387 388
    }

    TestWatcher watcher;
389
    if (machine) {
390
      watcher = EventPrinter(parent: collector, out: globals.stdio.stdout);
391
    } else if (collector != null) {
392 393
      watcher = collector;
    }
394

395 396 397
    final DebuggingOptions debuggingOptions = DebuggingOptions.enabled(
      buildInfo,
      startPaused: startPaused,
398
      disableServiceAuthCodes: boolArgDeprecated('disable-service-auth-codes'),
399 400
      // On iOS >=14, keeping this enabled will leave a prompt on the screen.
      disablePortPublication: true,
401
      enableDds: enableDds,
402
      nullAssertions: boolArgDeprecated(FlutterOptions.kNullAssertions),
403
    );
404

405 406 407 408
    Device integrationTestDevice;
    if (_isIntegrationTest) {
      integrationTestDevice = await findTargetDevice();

409 410 411 412
      // Disable reporting of test results to native test frameworks. This isn't
      // needed as the Flutter Tool will be responsible for reporting results.
      buildInfo.dartDefines.add('INTEGRATION_TEST_SHOULD_REPORT_RESULTS_TO_NATIVE=false');

413 414 415 416 417 418 419
      if (integrationTestDevice == null) {
        throwToolExit(
          'No devices are connected. '
          'Ensure that `flutter doctor` shows at least one connected device',
        );
      }
      if (integrationTestDevice.platformType == PlatformType.web) {
420
        // TODO(jiahaog): Support web. https://github.com/flutter/flutter/issues/66264
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
        throwToolExit('Web devices are not supported for integration tests yet.');
      }

      if (buildInfo.packageConfig['integration_test'] == null) {
        throwToolExit(
          'Error: cannot run without a dependency on "package:integration_test". '
          'Ensure the following lines are present in your pubspec.yaml:'
          '\n\n'
          'dev_dependencies:\n'
          '  integration_test:\n'
          '    sdk: flutter\n',
        );
      }
    }

436
    final int result = await testRunner.runTests(
437
      testWrapper,
438
      _testFiles,
439
      debuggingOptions: debuggingOptions,
440 441
      names: names,
      plainNames: plainNames,
442 443
      tags: tags,
      excludeTags: excludeTags,
444
      watcher: watcher,
445 446
      enableObservatory: collector != null || startPaused || boolArgDeprecated('enable-vmservice'),
      ipv6: boolArgDeprecated('ipv6'),
447
      machine: machine,
448
      updateGoldens: boolArgDeprecated('update-goldens'),
449
      concurrency: jobs,
450
      testAssetDirectory: testAssetDirectory,
451
      flutterProject: flutterProject,
452 453 454 455
      web: stringArgDeprecated('platform') == 'chrome',
      randomSeed: stringArgDeprecated('test-randomize-ordering-seed'),
      reporter: stringArgDeprecated('reporter'),
      timeout: stringArgDeprecated('timeout'),
456
      runSkipped: boolArgDeprecated('run-skipped'),
457 458
      shardIndex: shardIndex,
      totalShards: totalShards,
459
      integrationTestDevice: integrationTestDevice,
460
      integrationTestUserIdentifier: stringArgDeprecated(FlutterOptions.kDeviceUser),
461
    );
462

463
    if (collector != null) {
464
      final bool collectionResult = collector.collectCoverageData(
465
        stringArgDeprecated('coverage-path'),
466
        mergeCoverageData: boolArgDeprecated('merge-coverage'),
467 468
      );
      if (!collectionResult) {
469
        throwToolExit(null);
470
      }
471 472
    }

473
    if (result != 0) {
474
      throwToolExit(null);
475
    }
476
    return FlutterCommandResult.success();
477
  }
478 479 480

  Future<void> _buildTestAsset() async {
    final AssetBundle assetBundle = AssetBundleFactory.instance.createBundle();
481
    final int build = await assetBundle.build(packagesPath: '.packages');
482 483 484
    if (build != 0) {
      throwToolExit('Error: Failed to build asset bundle');
    }
485
    if (_needRebuild(assetBundle.entries)) {
486
      await writeBundle(globals.fs.directory(globals.fs.path.join('build', 'unit_test_assets')),
487 488 489
          assetBundle.entries);
    }
  }
490

491
  bool _needRebuild(Map<String, DevFSContent> entries) {
492
    final File manifest = globals.fs.file(globals.fs.path.join('build', 'unit_test_assets', 'AssetManifest.json'));
493 494 495 496
    if (!manifest.existsSync()) {
      return true;
    }
    final DateTime lastModified = manifest.lastModifiedSync();
497
    final File pub = globals.fs.file('pubspec.yaml');
498 499 500 501
    if (pub.lastModifiedSync().isAfter(lastModified)) {
      return true;
    }

502
    for (final DevFSFileContent entry in entries.values.whereType<DevFSFileContent>()) {
503 504 505 506 507 508 509
      // Calling isModified to access file stats first in order for isModifiedAfter
      // to work.
      if (entry.isModified && entry.isModifiedAfter(lastModified)) {
        return true;
      }
    }
    return false;
510
  }
511
}
512

513 514
/// Searches [directory] and returns files that end with `_test.dart` as
/// absolute paths.
515 516 517
Iterable<String> _findTests(Directory directory) {
  return directory.listSync(recursive: true, followLinks: false)
      .where((FileSystemEntity entity) => entity.path.endsWith('_test.dart') &&
518 519
      globals.fs.isFileSync(entity.path))
      .map((FileSystemEntity entity) => globals.fs.path.absolute(entity.path));
520
}
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545

/// Returns true if there are files that are Integration Tests.
///
/// The [currentDirectory] and [testFiles] parameters here must be provided as
/// absolute paths.
///
/// Throws an exception if there are both Integration Tests and Widget Tests
/// found in [testFiles].
bool _shouldRunAsIntegrationTests(String currentDirectory, List<String> testFiles) {
  final String integrationTestDirectory = globals.fs.path.join(currentDirectory, _kIntegrationTestDirectory);

  if (testFiles.every((String absolutePath) => !absolutePath.startsWith(integrationTestDirectory))) {
    return false;
  }

  if (testFiles.every((String absolutePath) => absolutePath.startsWith(integrationTestDirectory))) {
    return true;
  }

  throwToolExit(
    'Integration tests and unit tests cannot be run in a single invocation.'
    ' Use separate invocations of `flutter test` to run integration tests'
    ' and unit tests.'
  );
}