test.dart 23.2 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
import 'package:meta/meta.dart';

7
import '../asset.dart';
8
import '../base/common.dart';
9
import '../base/file_system.dart';
10
import '../build_info.dart';
11
import '../bundle_builder.dart';
12
import '../devfs.dart';
13
import '../device.dart';
14
import '../globals.dart' as globals;
15
import '../project.dart';
16
import '../runner/flutter_command.dart';
17
import '../test/coverage_collector.dart';
18 19
import '../test/event_printer.dart';
import '../test/runner.dart';
20
import '../test/test_time_recorder.dart';
21
import '../test/test_wrapper.dart';
22
import '../test/watcher.dart';
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
/// 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 {
60 61 62
  TestCommand({
    bool verboseHelp = false,
    this.testWrapper = const TestWrapper(),
63
    this.testRunner = const FlutterTestRunner(),
64
    this.verbose = false,
65
  }) {
66
    requiresPubspecYaml();
67
    usesPubOption();
68
    addNullSafetyModeOptions(hide: !verboseHelp);
69 70
    usesTrackWidgetCreation(verboseHelp: verboseHelp);
    addEnableExperimentation(hide: !verboseHelp);
71
    usesDartDefineOption();
72
    usesWebRendererOption();
73
    usesDeviceUserOption();
74
    usesFlavorOption();
75

76 77 78 79 80 81 82 83 84 85 86
    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,
      )
87 88
      ..addOption('tags',
        abbr: 't',
89
        help: 'Run only tests associated with the specified tags. See: https://pub.dev/packages/test#tagging-tests',
90 91 92
      )
      ..addOption('exclude-tags',
        abbr: 'x',
93
        help: 'Run only tests that do not have the specified tags. See: https://pub.dev/packages/test#tagging-tests',
94
      )
95 96 97 98
      ..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
99
              'Instructions for connecting with a debugger are printed to the '
100 101
              'console once the test has started.',
      )
102 103 104
      ..addFlag('run-skipped',
        help: 'Run skipped tests instead of skipping them.',
      )
105 106
      ..addFlag('disable-service-auth-codes',
        negatable: false,
107 108 109
        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!)'
110
      )
111 112 113 114 115 116 117
      ..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'
118
              'Implies collecting coverage data. (Requires lcov.)',
119
      )
120 121 122 123 124
      ..addFlag('branch-coverage',
        negatable: false,
        help: 'Whether to collect branch coverage information. '
              'Implies collecting coverage data.',
      )
125 126
      ..addFlag('ipv6',
        negatable: false,
127
        hide: !verboseHelp,
128 129 130 131 132 133 134 135 136
        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,
137
        help: 'Handle machine structured JSON command input '
138 139
              'and provide output and progress in machine friendly format.',
      )
140 141
      ..addFlag('update-goldens',
        negatable: false,
142
        help: 'Whether "matchesGoldenFile()" calls within your test methods should ' // flutter_ignore: golden_tag (see analyze.dart)
143
              'update the golden files rather than test for an existing match.',
144 145 146
      )
      ..addOption('concurrency',
        abbr: 'j',
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
      )
      ..addOption('reporter',
        abbr: 'r',
199
        help: 'Set how to print test results. If unset, value will default to either compact or expanded.',
200
        allowed: <String>['compact', 'expanded', 'github', 'json'],
201
        allowedHelp: <String, String>{
202
          'compact':  'A single line that updates dynamically (The default reporter).',
203
          'expanded': 'A separate line for each update. May be preferred when logging to a file or in continuous integration.',
204
          'github':   'A custom reporter for GitHub Actions (the default reporter when running on GitHub Actions).',
205 206 207
          'json':     'A machine-readable format. See: https://dart.dev/go/test-docs/json_reporter.md',
        },
      )
208 209 210 211 212
      ..addOption('file-reporter',
        help: 'Enable an additional reporter writing test results to a file.\n'
          'Should be in the form <reporter>:<filepath>, '
          'Example: "json:reports/tests.json".'
      )
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
      );
219
    addDdsOptions(verboseHelp: verboseHelp);
220
    addServeObservatoryOptions(verboseHelp: verboseHelp);
221
    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
  final bool verbose;

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

236
  final Set<Uri> _testFileUris = <Uri>{};
237

238 239
  bool get isWeb => stringArg('platform') == 'chrome';

240
  @override
241
  Future<Set<DevelopmentArtifact>> get requiredArtifacts async {
242 243 244 245
    final Set<DevelopmentArtifact> results = _isIntegrationTest
        // Use [DeviceBasedDevelopmentArtifacts].
        ? await super.requiredArtifacts
        : <DevelopmentArtifact>{};
246
    if (isWeb) {
247 248 249 250
      results.add(DevelopmentArtifact.web);
    }
    return results;
  }
251

252
  @override
Ian Hickson's avatar
Ian Hickson committed
253
  String get name => 'test';
254 255

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

258 259 260
  @override
  String get category => FlutterCommandCategory.project;

261
  @override
262
  Future<FlutterCommandResult> verifyThenRunCommand(String? commandPath) {
263 264
    final List<Uri> testUris = argResults!.rest.map(_parseTestArgument).toList();
    if (testUris.isEmpty) {
265
      // We don't scan the entire package, only the test/ subdirectory, so that
nt4f04uNd's avatar
nt4f04uNd committed
266
      // files with names like "hit_test.dart" don't get run.
267 268 269 270
      final Directory testDir = globals.fs.directory('test');
      if (!testDir.existsSync()) {
        throwToolExit('Test directory "${testDir.path}" not found.');
      }
271 272
      _testFileUris.addAll(_findTests(testDir).map(Uri.file));
      if (_testFileUris.isEmpty) {
273 274 275 276 277 278
        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 {
279 280 281 282 283 284 285 286 287 288 289 290
      for (final Uri uri in testUris) {
        // Test files may have query strings to support name/line/col:
        //     flutter test test/foo.dart?name=a&line=1
        String testPath = uri.replace(query: '').toFilePath();
        testPath = globals.fs.path.absolute(testPath);
        testPath = globals.fs.path.normalize(testPath);
        if (globals.fs.isDirectorySync(testPath)) {
          _testFileUris.addAll(_findTests(globals.fs.directory(testPath)).map(Uri.file));
        } else {
          _testFileUris.add(Uri.file(testPath).replace(query: uri.query));
        }
      }
291 292 293 294
    }

    // This needs to be set before [super.verifyThenRunCommand] so that the
    // correct [requiredArtifacts] can be identified before [run] takes place.
295 296
    final List<String> testFilePaths = _testFileUris.map((Uri uri) => uri.replace(query: '').toFilePath()).toList();
    _isIntegrationTest = _shouldRunAsIntegrationTests(globals.fs.currentDirectory.absolute.path, testFilePaths);
297

298
    globals.printTrace(
299
      'Found ${_testFileUris.length} files which will be executed as '
300 301 302 303 304
      '${_isIntegrationTest ? 'Integration' : 'Widget'} Tests.',
    );
    return super.verifyThenRunCommand(commandPath);
  }

305
  @override
306
  Future<FlutterCommandResult> runCommand() async {
307
    if (!globals.fs.isFileSync('pubspec.yaml')) {
308
      throwToolExit(
309
        'Error: No pubspec.yaml file found in the current working directory.\n'
310
        'Run this command from the root of your project. Test files must be '
311
        "called *_test.dart and must reside in the package's 'test' "
312
        'directory (or one of its subdirectories).');
313
    }
314
    final FlutterProject flutterProject = FlutterProject.current();
315
    final bool buildTestAssets = boolArg('test-assets');
316 317
    final List<String> names = stringsArg('name');
    final List<String> plainNames = stringsArg('plain-name');
318 319
    final String? tags = stringArg('tags');
    final String? excludeTags = stringArg('exclude-tags');
320
    final BuildInfo buildInfo = await getBuildInfo(forcedBuildMode: BuildMode.debug);
321

322 323 324 325 326
    TestTimeRecorder? testTimeRecorder;
    if (verbose) {
      testTimeRecorder = TestTimeRecorder(globals.logger);
    }

327
    if (buildInfo.packageConfig['test_api'] == null) {
328
      throwToolExit(
329 330 331 332 333 334 335 336 337
        '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',
      );
    }

338
    String? testAssetDirectory;
339
    if (buildTestAssets) {
340
      await _buildTestAsset();
341
      testAssetDirectory = globals.fs.path.
342
        join(flutterProject.directory.path, 'build', 'unit_test_assets');
343 344
    }

345
    final bool startPaused = boolArg('start-paused');
346
    if (startPaused && _testFileUris.length != 1) {
347
      throwToolExit(
348 349 350 351 352
        'When using --start-paused, you must specify a single test file to run.',
        exitCode: 1,
      );
    }

353 354 355
    final String? concurrencyString = stringArg('concurrency');
    int? jobs = concurrencyString == null ? null : int.tryParse(concurrencyString);
    if (jobs != null && (jobs <= 0 || !jobs.isFinite)) {
356 357 358
      throwToolExit(
        'Could not parse -j/--concurrency argument. It must be an integer greater than zero.'
      );
359
    }
360 361

    if (_isIntegrationTest || isWeb) {
362
      if (argResults!.wasParsed('concurrency')) {
363
        globals.printStatus(
364
          '-j/--concurrency was parsed but will be ignored, this option is not '
365
          'supported when running Integration Tests or web tests.',
366 367
        );
      }
368 369 370
      // Running with concurrency will result in deploying multiple test apps
      // on the connected device concurrently, which is not supported.
      jobs = 1;
371
    }
372

373
    final int? shardIndex = int.tryParse(stringArg('shard-index') ?? '');
374 375 376 377 378
    if (shardIndex != null && (shardIndex < 0 || !shardIndex.isFinite)) {
      throwToolExit(
          'Could not parse --shard-index=$shardIndex argument. It must be an integer greater than -1.');
    }

379
    final int? totalShards = int.tryParse(stringArg('total-shards') ?? '');
380 381 382 383 384 385 386 387 388 389 390 391 392 393
    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.');
    }

394
    final bool machine = boolArg('machine');
395
    CoverageCollector? collector;
396 397
    if (boolArg('coverage') || boolArg('merge-coverage') ||
        boolArg('branch-coverage')) {
398
      final String projectName = flutterProject.manifest.appName;
399
      collector = CoverageCollector(
400
        verbose: !machine,
401
        libraryNames: <String>{projectName},
402
        packagesPath: buildInfo.packagesPath,
403 404
        resolver: await CoverageCollector.getResolver(buildInfo.packagesPath),
        testTimeRecorder: testTimeRecorder,
405
        branchCoverage: boolArg('branch-coverage'),
406
      );
407 408
    }

409
    TestWatcher? watcher;
410
    if (machine) {
411
      watcher = EventPrinter(parent: collector, out: globals.stdio.stdout);
412
    } else if (collector != null) {
413 414
      watcher = collector;
    }
415

416 417 418
    final DebuggingOptions debuggingOptions = DebuggingOptions.enabled(
      buildInfo,
      startPaused: startPaused,
419 420
      disableServiceAuthCodes: boolArg('disable-service-auth-codes'),
      serveObservatory: boolArg('serve-observatory'),
421 422
      // On iOS >=14, keeping this enabled will leave a prompt on the screen.
      disablePortPublication: true,
423
      enableDds: enableDds,
424
      nullAssertions: boolArg(FlutterOptions.kNullAssertions),
425
      usingCISystem: usingCISystem,
426
    );
427

428
    Device? integrationTestDevice;
429 430 431
    if (_isIntegrationTest) {
      integrationTestDevice = await findTargetDevice();

432 433 434 435
      // 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');

436 437 438 439 440 441 442
      if (integrationTestDevice == null) {
        throwToolExit(
          'No devices are connected. '
          'Ensure that `flutter doctor` shows at least one connected device',
        );
      }
      if (integrationTestDevice.platformType == PlatformType.web) {
443
        // TODO(jiahaog): Support web. https://github.com/flutter/flutter/issues/66264
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
        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',
        );
      }
    }

459
    final Stopwatch? testRunnerTimeRecorderStopwatch = testTimeRecorder?.start(TestTimePhases.TestRunner);
460
    final int result = await testRunner.runTests(
461
      testWrapper,
462
      _testFileUris.toList(),
463
      debuggingOptions: debuggingOptions,
464 465
      names: names,
      plainNames: plainNames,
466 467
      tags: tags,
      excludeTags: excludeTags,
468
      watcher: watcher,
469 470
      enableVmService: collector != null || startPaused || boolArg('enable-vmservice'),
      ipv6: boolArg('ipv6'),
471
      machine: machine,
472
      updateGoldens: boolArg('update-goldens'),
473
      concurrency: jobs,
474
      testAssetDirectory: testAssetDirectory,
475
      flutterProject: flutterProject,
476
      web: isWeb,
477 478
      randomSeed: stringArg('test-randomize-ordering-seed'),
      reporter: stringArg('reporter'),
479
      fileReporter: stringArg('file-reporter'),
480 481
      timeout: stringArg('timeout'),
      runSkipped: boolArg('run-skipped'),
482 483
      shardIndex: shardIndex,
      totalShards: totalShards,
484
      integrationTestDevice: integrationTestDevice,
485
      integrationTestUserIdentifier: stringArg(FlutterOptions.kDeviceUser),
486
      testTimeRecorder: testTimeRecorder,
487
    );
488
    testTimeRecorder?.stop(TestTimePhases.TestRunner, testRunnerTimeRecorderStopwatch!);
489

490
    if (collector != null) {
491
      final Stopwatch? collectTimeRecorderStopwatch = testTimeRecorder?.start(TestTimePhases.CoverageDataCollect);
492
      final bool collectionResult = await collector.collectCoverageData(
493 494
        stringArg('coverage-path'),
        mergeCoverageData: boolArg('merge-coverage'),
495
      );
496
      testTimeRecorder?.stop(TestTimePhases.CoverageDataCollect, collectTimeRecorderStopwatch!);
497
      if (!collectionResult) {
498
        testTimeRecorder?.print();
499
        throwToolExit(null);
500
      }
501 502
    }

503 504
    testTimeRecorder?.print();

505
    if (result != 0) {
506
      throwToolExit(null);
507
    }
508
    return FlutterCommandResult.success();
509
  }
510

511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
  /// Parses a test file/directory target passed as an argument and returns it
  /// as an absolute file:/// [URI] with optional querystring for name/line/col.
  Uri _parseTestArgument(String arg) {
    // We can't parse Windows paths as URIs if they have query strings, so
    // parse the file and query parts separately.
    final int queryStart = arg.indexOf('?');
    String filePart = queryStart == -1 ? arg : arg.substring(0, queryStart);
    final String queryPart = queryStart == -1 ? '' : arg.substring(queryStart + 1);

    filePart = globals.fs.path.absolute(filePart);
    filePart = globals.fs.path.normalize(filePart);

    return Uri.file(filePart)
        .replace(query: queryPart.isEmpty ? null : queryPart);
  }

527 528
  Future<void> _buildTestAsset() async {
    final AssetBundle assetBundle = AssetBundleFactory.instance.createBundle();
529
    final int build = await assetBundle.build(packagesPath: '.packages');
530 531 532
    if (build != 0) {
      throwToolExit('Error: Failed to build asset bundle');
    }
533
    if (_needRebuild(assetBundle.entries)) {
534 535 536 537 538 539
      await writeBundle(
        globals.fs.directory(globals.fs.path.join('build', 'unit_test_assets')),
        assetBundle.entries,
        assetBundle.entryKinds,
        targetPlatform: TargetPlatform.tester,
      );
540 541
    }
  }
542

543
  bool _needRebuild(Map<String, DevFSContent> entries) {
544
    final File manifest = globals.fs.file(globals.fs.path.join('build', 'unit_test_assets', 'AssetManifest.json'));
545 546 547 548
    if (!manifest.existsSync()) {
      return true;
    }
    final DateTime lastModified = manifest.lastModifiedSync();
549
    final File pub = globals.fs.file('pubspec.yaml');
550 551 552 553
    if (pub.lastModifiedSync().isAfter(lastModified)) {
      return true;
    }

554
    for (final DevFSFileContent entry in entries.values.whereType<DevFSFileContent>()) {
555 556 557 558 559 560 561
      // Calling isModified to access file stats first in order for isModifiedAfter
      // to work.
      if (entry.isModified && entry.isModifiedAfter(lastModified)) {
        return true;
      }
    }
    return false;
562
  }
563
}
564

565 566
/// Searches [directory] and returns files that end with `_test.dart` as
/// absolute paths.
567 568 569
Iterable<String> _findTests(Directory directory) {
  return directory.listSync(recursive: true, followLinks: false)
      .where((FileSystemEntity entity) => entity.path.endsWith('_test.dart') &&
570 571
      globals.fs.isFileSync(entity.path))
      .map((FileSystemEntity entity) => globals.fs.path.absolute(entity.path));
572
}
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597

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