test.dart 21.4 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

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_time_recorder.dart';
25
import '../test/test_wrapper.dart';
26
import '../test/watcher.dart';
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
/// 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 {
64 65 66
  TestCommand({
    bool verboseHelp = false,
    this.testWrapper = const TestWrapper(),
67
    this.testRunner = const FlutterTestRunner(),
68
    this.verbose = false,
69
  }) : assert(testWrapper != null) {
70
    requiresPubspecYaml();
71
    usesPubOption();
72
    addNullSafetyModeOptions(hide: !verboseHelp);
73 74
    usesTrackWidgetCreation(verboseHelp: verboseHelp);
    addEnableExperimentation(hide: !verboseHelp);
75
    usesDartDefineOption();
76
    usesWebRendererOption();
77
    usesDeviceUserOption();
78
    usesFlavorOption();
79

80 81 82 83 84 85 86 87 88 89 90
    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,
      )
91 92
      ..addOption('tags',
        abbr: 't',
93
        help: 'Run only tests associated with the specified tags. See: https://pub.dev/packages/test#tagging-tests',
94 95 96
      )
      ..addOption('exclude-tags',
        abbr: 'x',
97
        help: 'Run only tests that do not have the specified tags. See: https://pub.dev/packages/test#tagging-tests',
98
      )
99 100 101 102
      ..addFlag('start-paused',
        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
103
              'Instructions for connecting with a debugger are printed to the '
104 105
              'console once the test has started.',
      )
106 107 108
      ..addFlag('run-skipped',
        help: 'Run skipped tests instead of skipping them.',
      )
109 110
      ..addFlag('disable-service-auth-codes',
        negatable: false,
111 112 113
        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!)'
114
      )
115 116 117 118 119 120 121
      ..addFlag('coverage',
        negatable: false,
        help: 'Whether to collect coverage information.',
      )
      ..addFlag('merge-coverage',
        negatable: false,
        help: 'Whether to merge coverage data with "coverage/lcov.base.info".\n'
122
              'Implies collecting coverage data. (Requires lcov.)',
123 124 125
      )
      ..addFlag('ipv6',
        negatable: false,
126
        hide: !verboseHelp,
127 128 129 130 131 132 133 134 135
        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,
136
        help: 'Handle machine structured JSON command input '
137 138
              'and provide output and progress in machine friendly format.',
      )
139 140
      ..addFlag('update-goldens',
        negatable: false,
141
        help: 'Whether "matchesGoldenFile()" calls within your test methods should ' // flutter_ignore: golden_tag (see analyze.dart)
142
              'update the golden files rather than test for an existing match.',
143 144 145
      )
      ..addOption('concurrency',
        abbr: 'j',
146
        defaultsTo: math.max<int>(1, globals.platform.numberOfProcessors - 2).toString(),
147 148
        help: 'The number of concurrent test processes to run. This will be ignored '
              'when running integration tests.',
149
        valueHelp: 'jobs',
150 151 152
      )
      ..addFlag('test-assets',
        defaultsTo: true,
153 154 155
        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.',
156
      )
157 158 159 160
      // --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.
161 162
      ..addOption('platform',
        allowed: const <String>['tester', 'chrome'],
163
        hide: !verboseHelp,
164
        defaultsTo: 'tester',
165 166
        help: 'Selects the test backend.',
        allowedHelp: <String, String>{
167
          'tester': 'Run tests using the VM-based test environment.',
168 169 170 171
          '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.',
        },
172 173
      )
      ..addOption('test-randomize-ordering-seed',
174 175 176 177
        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.',
178
      )
179 180 181 182 183 184 185 186 187 188
      ..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.'
      )
189 190
      ..addFlag('enable-vmservice',
        hide: !verboseHelp,
191 192 193 194 195
        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.'
196 197 198 199
      )
      ..addOption('reporter',
        abbr: 'r',
        defaultsTo: 'compact',
200 201 202 203 204 205 206 207
        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',
        },
      )
208
      ..addOption('timeout',
209 210 211 212
        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.',
213
        defaultsTo: '30s',
214
      );
215 216
    addDdsOptions(verboseHelp: verboseHelp);
    usesFatalWarningsOption(verboseHelp: verboseHelp);
Ian Hickson's avatar
Ian Hickson committed
217 218
  }

219 220 221
  /// The interface for starting and configuring the tester.
  final TestWrapper testWrapper;

222 223 224
  /// Interface for running the tester process.
  final FlutterTestRunner testRunner;

225 226
  final bool verbose;

227 228 229 230 231 232
  @visibleForTesting
  bool get isIntegrationTest => _isIntegrationTest;
  bool _isIntegrationTest = false;

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

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

245
  @override
Ian Hickson's avatar
Ian Hickson committed
246
  String get name => 'test';
247 248

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

251 252 253
  @override
  String get category => FlutterCommandCategory.project;

254
  @override
255 256
  Future<FlutterCommandResult> verifyThenRunCommand(String? commandPath) {
    _testFiles = argResults!.rest.map<String>(globals.fs.path.absolute).toList();
257 258
    if (_testFiles.isEmpty) {
      // We don't scan the entire package, only the test/ subdirectory, so that
nt4f04uNd's avatar
nt4f04uNd committed
259
      // files with names like "hit_test.dart" don't get run.
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
      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
277
            globals.fs.path.normalize(globals.fs.path.absolute(path)),
278 279 280 281 282 283 284
      ];
    }

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

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

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

309 310 311 312 313
    TestTimeRecorder? testTimeRecorder;
    if (verbose) {
      testTimeRecorder = TestTimeRecorder(globals.logger);
    }

314
    if (buildInfo.packageConfig['test_api'] == null) {
315
      throwToolExit(
316 317 318 319 320 321 322 323 324
        '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',
      );
    }

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

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

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

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

364
    final int? totalShards = int.tryParse(stringArgDeprecated('total-shards') ?? '');
365 366 367 368 369 370 371 372 373 374 375 376 377 378
    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.');
    }

379
    final bool machine = boolArgDeprecated('machine');
380
    CoverageCollector? collector;
381
    if (boolArgDeprecated('coverage') || boolArgDeprecated('merge-coverage')) {
382
      final String projectName = flutterProject.manifest.appName;
383
      collector = CoverageCollector(
384
        verbose: !machine,
385
        libraryNames: <String>{projectName},
386
        packagesPath: buildInfo.packagesPath,
387 388
        resolver: await CoverageCollector.getResolver(buildInfo.packagesPath),
        testTimeRecorder: testTimeRecorder,
389
      );
390 391
    }

392
    TestWatcher? watcher;
393
    if (machine) {
394
      watcher = EventPrinter(parent: collector, out: globals.stdio.stdout);
395
    } else if (collector != null) {
396 397
      watcher = collector;
    }
398

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

409
    Device? integrationTestDevice;
410 411 412
    if (_isIntegrationTest) {
      integrationTestDevice = await findTargetDevice();

413 414 415 416
      // 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');

417 418 419 420 421 422 423
      if (integrationTestDevice == null) {
        throwToolExit(
          'No devices are connected. '
          'Ensure that `flutter doctor` shows at least one connected device',
        );
      }
      if (integrationTestDevice.platformType == PlatformType.web) {
424
        // TODO(jiahaog): Support web. https://github.com/flutter/flutter/issues/66264
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
        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',
        );
      }
    }

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

470
    if (collector != null) {
471
      final Stopwatch? collectTimeRecorderStopwatch = testTimeRecorder?.start(TestTimePhases.CoverageDataCollect);
472
      final bool collectionResult = await collector.collectCoverageData(
473
        stringArgDeprecated('coverage-path'),
474
        mergeCoverageData: boolArgDeprecated('merge-coverage'),
475
      );
476
      testTimeRecorder?.stop(TestTimePhases.CoverageDataCollect, collectTimeRecorderStopwatch!);
477
      if (!collectionResult) {
478
        testTimeRecorder?.print();
479
        throwToolExit(null);
480
      }
481 482
    }

483 484
    testTimeRecorder?.print();

485
    if (result != 0) {
486
      throwToolExit(null);
487
    }
488
    return FlutterCommandResult.success();
489
  }
490 491 492

  Future<void> _buildTestAsset() async {
    final AssetBundle assetBundle = AssetBundleFactory.instance.createBundle();
493
    final int build = await assetBundle.build(packagesPath: '.packages');
494 495 496
    if (build != 0) {
      throwToolExit('Error: Failed to build asset bundle');
    }
497
    if (_needRebuild(assetBundle.entries)) {
498
      await writeBundle(globals.fs.directory(globals.fs.path.join('build', 'unit_test_assets')),
499
          assetBundle.entries, assetBundle.entryKinds);
500 501
    }
  }
502

503
  bool _needRebuild(Map<String, DevFSContent> entries) {
504
    final File manifest = globals.fs.file(globals.fs.path.join('build', 'unit_test_assets', 'AssetManifest.json'));
505 506 507 508
    if (!manifest.existsSync()) {
      return true;
    }
    final DateTime lastModified = manifest.lastModifiedSync();
509
    final File pub = globals.fs.file('pubspec.yaml');
510 511 512 513
    if (pub.lastModifiedSync().isAfter(lastModified)) {
      return true;
    }

514
    for (final DevFSFileContent entry in entries.values.whereType<DevFSFileContent>()) {
515 516 517 518 519 520 521
      // Calling isModified to access file stats first in order for isModifiedAfter
      // to work.
      if (entry.isModified && entry.isModifiedAfter(lastModified)) {
        return true;
      }
    }
    return false;
522
  }
523
}
524

525 526
/// Searches [directory] and returns files that end with `_test.dart` as
/// absolute paths.
527 528 529
Iterable<String> _findTests(Directory directory) {
  return directory.listSync(recursive: true, followLinks: false)
      .where((FileSystemEntity entity) => entity.path.endsWith('_test.dart') &&
530 531
      globals.fs.isFileSync(entity.path))
      .map((FileSystemEntity entity) => globals.fs.path.absolute(entity.path));
532
}
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557

/// 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.'
  );
}