| // Copyright 2014 The Flutter 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 'package:meta/meta.dart'; | |
| import 'package:package_config/package_config_types.dart'; | |
| import '../asset.dart'; | |
| import '../base/common.dart'; | |
| import '../base/config.dart'; | |
| import '../base/file_system.dart'; | |
| import '../base/io.dart'; | |
| import '../base/logger.dart'; | |
| import '../base/platform.dart'; | |
| import '../base/template.dart'; | |
| import '../base/utils.dart'; | |
| import '../build_info.dart'; | |
| import '../bundle_builder.dart'; | |
| import '../context/tool_context.dart'; | |
| import '../devfs.dart'; | |
| import '../device.dart'; | |
| import '../native_assets.dart'; | |
| import '../project.dart'; | |
| import '../runner/flutter_command.dart'; | |
| import '../test/coverage_collector.dart'; | |
| import '../test/event_printer.dart'; | |
| import '../test/runner.dart'; | |
| import '../test/test_time_recorder.dart'; | |
| import '../test/test_wrapper.dart'; | |
| import '../test/watcher.dart'; | |
| import '../web/compile.dart'; | |
| import '../web/web_constants.dart'; | |
| import '../web/web_debug_config.dart'; | |
| import '../web/web_options.dart'; | |
| /// 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 _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/to/unit-testing | |
| /// - https://flutter.dev/to/widget-testing | |
| /// | |
| /// ## 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/to/integration-testing | |
| class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts { | |
| TestCommand({ | |
| required this._assetBundleFactory, | |
| required this._templateRenderer, | |
| required super.toolContext, | |
| super.applicationPackages, | |
| this.nativeAssetsBuilder, | |
| FlutterTestRunner? testRunner, | |
| this.testWrapper = const TestWrapper(), | |
| this.verbose = false, | |
| super.verboseHelp = false, | |
| }) : _customTestRunner = testRunner { | |
| requiresPubspecYaml(); | |
| registerOptionBundles(const <OptionBundle>[ | |
| DdsAndDevToolsOptionsBundle(includeDevTools: false), | |
| ]); | |
| argParser.addDescriptors(const <OptionDescriptor<Object?>>[ | |
| CommonOptions.pub, | |
| BuildInfoOptions.frontendServerStarterPath, | |
| BuildInfoOptions.trackWidgetCreation, | |
| CommonOptions.enableExperiment, | |
| CommonOptions.dartDefines, | |
| CommonOptions.dartDefineFromFile, | |
| CommonOptions.deviceUser, | |
| BuildInfoOptions.flavor, | |
| DebuggingOptionDescriptors.enableImpeller, | |
| CommonOptions.machine, | |
| DebuggingOptionDescriptors.enableFlutterGpu, | |
| DebuggingOptionDescriptors.enableHcpp, | |
| WebOptions.deprecatedJsInterop, | |
| CommonOptions.fatalWarnings, | |
| _experimentalFasterTesting, | |
| _name, | |
| _plainName, | |
| _tags, | |
| _excludeTags, | |
| _preset, | |
| _startPaused, | |
| _failFast, | |
| _runSkipped, | |
| DebuggingOptionDescriptors.disableServiceAuthCodes, | |
| DebuggingOptionDescriptors.disableServiceOriginCheck, | |
| _coverage, | |
| _mergeCoverage, | |
| _branchCoverage, | |
| _ipv6, | |
| _coveragePath, | |
| _coveragePackage, | |
| _updateGoldens, | |
| _concurrency, | |
| _testAssets, | |
| _platform, | |
| _testRandomizeOrderingSeed, | |
| _totalShards, | |
| _shardIndex, | |
| _enableVmService, | |
| _reporter, | |
| _fileReporter, | |
| _timeout, | |
| _ignoreTimeouts, | |
| _wasm, | |
| WebOptions.crossOriginIsolation, | |
| _uninstall, | |
| ], verboseHelp: verboseHelp); | |
| } | |
| static const _experimentalFasterTesting = FlagOptionDescriptor( | |
| name: 'experimental-faster-testing', | |
| negatable: false, | |
| verboseOnly: true, | |
| help: | |
| '(deprecated) This option is deprecated and no longer has any effect. ' | |
| 'This flag will be removed in a future version of Flutter.', | |
| ); | |
| static const _name = MultiOptionDescriptor( | |
| name: 'name', | |
| help: 'A regular expression matching substrings of the names of tests to run.', | |
| valueHelp: 'regexp', | |
| splitCommas: false, | |
| ); | |
| static const _plainName = MultiOptionDescriptor( | |
| name: 'plain-name', | |
| help: 'A plain-text substring of the names of tests to run.', | |
| valueHelp: 'substring', | |
| splitCommas: false, | |
| ); | |
| static const _tags = MultiOptionDescriptor( | |
| name: 'tags', | |
| abbr: 't', | |
| help: 'Run only tests associated with the specified tags. See: https://pub.dev/packages/test#tagging-tests', | |
| splitCommas: false, | |
| ); | |
| static const _excludeTags = MultiOptionDescriptor( | |
| name: 'exclude-tags', | |
| abbr: 'x', | |
| help: 'Run only tests that do not have the specified tags. See: https://pub.dev/packages/test#tagging-tests', | |
| splitCommas: false, | |
| ); | |
| static const _preset = MultiOptionDescriptor( | |
| name: 'preset', | |
| abbr: 'P', | |
| help: 'The configuration preset(s) to use. Presets are defined in "dart_test.yaml".', | |
| splitCommas: false, | |
| ); | |
| static const _startPaused = FlagOptionDescriptor( | |
| name: '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' | |
| 'Instructions for connecting with a debugger are printed to the ' | |
| 'console once the test has started.', | |
| ); | |
| static const _failFast = FlagOptionDescriptor( | |
| name: 'fail-fast', | |
| help: 'Stop running tests after the first failure.', | |
| ); | |
| static const _runSkipped = FlagOptionDescriptor( | |
| name: 'run-skipped', | |
| help: 'Run skipped tests instead of skipping them.', | |
| ); | |
| static const _coverage = FlagOptionDescriptor( | |
| name: 'coverage', | |
| negatable: false, | |
| help: 'Whether to collect coverage information.', | |
| ); | |
| static const _mergeCoverage = FlagOptionDescriptor( | |
| name: 'merge-coverage', | |
| negatable: false, | |
| help: | |
| 'Whether to merge coverage data with "coverage/lcov.base.info".\n' | |
| 'Implies collecting coverage data. (Requires lcov.)', | |
| ); | |
| static const _branchCoverage = FlagOptionDescriptor( | |
| name: 'branch-coverage', | |
| negatable: false, | |
| help: | |
| 'Whether to collect branch coverage information. ' | |
| 'Implies collecting coverage data.', | |
| ); | |
| static const _ipv6 = FlagOptionDescriptor( | |
| name: 'ipv6', | |
| negatable: false, | |
| verboseOnly: true, | |
| help: 'Whether to use IPv6 for the test harness server socket.', | |
| ); | |
| static const _coveragePath = DefaultedStringOptionDescriptor( | |
| name: 'coverage-path', | |
| defaultsTo: 'coverage/lcov.info', | |
| help: 'Where to store coverage information (if coverage is enabled).', | |
| ); | |
| static const _coveragePackage = MultiOptionDescriptor( | |
| name: 'coverage-package', | |
| help: | |
| 'A regular expression matching packages names ' | |
| 'to include in the coverage report (if coverage is enabled). ' | |
| 'If unset, matches the current package name.', | |
| valueHelp: 'package-name-regexp', | |
| splitCommas: false, | |
| ); | |
| static const _updateGoldens = FlagOptionDescriptor( | |
| name: 'update-goldens', | |
| negatable: false, | |
| help: | |
| 'Whether "matchesGoldenFile()" calls within your test methods should ' // ignore: golden_test_tags | |
| 'update the golden files rather than test for an existing match.', | |
| ); | |
| static const _concurrency = IntOptionDescriptor( | |
| name: 'concurrency', | |
| abbr: 'j', | |
| help: | |
| 'The number of concurrent test processes to run. This will be ignored ' | |
| 'when running integration tests.', | |
| valueHelp: 'jobs', | |
| ); | |
| static const _testAssets = FlagOptionDescriptor( | |
| name: 'test-assets', | |
| defaultsTo: true, | |
| 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.', | |
| ); | |
| // --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. | |
| static const _platform = DefaultedStringOptionDescriptor( | |
| name: 'platform', | |
| allowed: <String>['tester', 'chrome'], | |
| verboseOnly: true, | |
| defaultsTo: 'tester', | |
| help: 'Selects the test backend.', | |
| allowedHelp: <String, String>{ | |
| 'tester': 'Run tests using the VM-based test environment.', | |
| '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.', | |
| }, | |
| ); | |
| static const _testRandomizeOrderingSeed = StringOptionDescriptor( | |
| name: 'test-randomize-ordering-seed', | |
| 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.', | |
| ); | |
| static const _totalShards = IntOptionDescriptor( | |
| name: '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.', | |
| ); | |
| static const _shardIndex = IntOptionDescriptor( | |
| name: '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.', | |
| ); | |
| static const _enableVmService = FlagOptionDescriptor( | |
| name: 'enable-vmservice', | |
| verboseOnly: true, | |
| 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.', | |
| ); | |
| static const _reporter = StringOptionDescriptor( | |
| name: 'reporter', | |
| abbr: 'r', | |
| help: 'Set how to print test results. If unset, value will default to either compact or expanded.', | |
| allowed: <String>['compact', 'expanded', 'failures-only', 'github', 'json', 'silent'], | |
| allowedHelp: <String, String>{ | |
| 'compact': 'A single line, updated continuously (the default).', | |
| 'expanded': 'A separate line for each update. May be preferred when logging to a file or in continuous integration.', | |
| 'failures-only': 'A separate line for failing tests, with no output for passing tests.', | |
| 'github': 'A custom reporter for GitHub Actions (the default reporter when running on GitHub Actions).', | |
| 'json': 'A machine-readable format. See: https://dart.dev/go/test-docs/json_reporter.md', | |
| 'silent': 'A reporter with no output. May be useful when only the exit code is meaningful.', | |
| }, | |
| ); | |
| static const _fileReporter = StringOptionDescriptor( | |
| name: '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".', | |
| ); | |
| static const _timeout = StringOptionDescriptor( | |
| name: 'timeout', | |
| help: | |
| 'The default timeout for individual tests, specified either in ' | |
| 'seconds (e.g. "60s"), as a multiplier of the default test timeout ' | |
| '(e.g. "2x"), or as the string "none" to disable test timeouts ' | |
| 'entirely. This value does not apply to the default test suite ' | |
| 'loading timeout.', | |
| ); | |
| static const _ignoreTimeouts = FlagOptionDescriptor( | |
| name: 'ignore-timeouts', | |
| negatable: false, | |
| help: | |
| 'Ignore all timeouts. Useful when testing a big application ' | |
| 'that requires a longer time to compile (e.g. running integration ' | |
| 'tests for a Flutter app).', | |
| ); | |
| static const _wasm = FlagOptionDescriptor( | |
| name: FlutterOptions.kWebWasmFlag, | |
| negatable: false, | |
| help: 'Compile to WebAssembly rather than JavaScript.\n$kWasmMoreInfo', | |
| ); | |
| static const _uninstall = FlagOptionDescriptor( | |
| name: 'uninstall', | |
| defaultsTo: true, | |
| help: | |
| 'Whether to uninstall the app after running integration tests. ' | |
| 'Set "--no-uninstall" to keep the app installed on the device.', | |
| ); | |
| /// The interface for starting and configuring the tester. | |
| final TestWrapper testWrapper; | |
| final AssetBundleFactory _assetBundleFactory; | |
| final TemplateRenderer _templateRenderer; | |
| final FlutterTestRunner? _customTestRunner; | |
| /// Interface for running the tester process. | |
| late final FlutterTestRunner _testRunner = | |
| _customTestRunner ?? | |
| FlutterTestRunner( | |
| analytics: analytics, | |
| applicationPackageFactory: applicationPackages, | |
| templateRenderer: _templateRenderer, | |
| toolContext: toolContext, | |
| ); | |
| final TestCompilerNativeAssetsBuilder? nativeAssetsBuilder; | |
| final bool verbose; | |
| @visibleForTesting | |
| bool get isIntegrationTest => _isIntegrationTest; | |
| var _isIntegrationTest = false; | |
| final _testFileUris = <Uri>{}; | |
| bool get isWeb => getValue(_platform) == 'chrome'; | |
| bool get useWasm => getValue(_wasm); | |
| @override | |
| Future<Set<DevelopmentArtifact>> get requiredArtifacts async { | |
| final Set<DevelopmentArtifact> results = _isIntegrationTest | |
| // Use [DeviceBasedDevelopmentArtifacts]. | |
| ? await super.requiredArtifacts | |
| : <DevelopmentArtifact>{}; | |
| if (isWeb) { | |
| results.add(DevelopmentArtifact.web); | |
| } | |
| return results; | |
| } | |
| @override | |
| String get name => 'test'; | |
| @override | |
| String get description => 'Run Flutter unit tests for the current project.'; | |
| @override | |
| String get category => FlutterCommandCategory.project; | |
| @override | |
| Future<FlutterCommandResult> verifyThenRunCommand(String? commandPath) { | |
| final ToolContext(:FileSystem fs, :Logger logger) = toolContext; | |
| final List<Uri> testUris = argResults!.rest.map(_parseTestArgument).toList(); | |
| if (testUris.isEmpty) { | |
| // We don't scan the entire package, only the test/ subdirectory, so that | |
| // files with names like "hit_test.dart" don't get run. | |
| final Directory testDir = fs.directory('test'); | |
| if (!testDir.existsSync()) { | |
| throwToolExit('Test directory "${testDir.path}" not found.'); | |
| } | |
| _testFileUris.addAll(_findTests(testDir, fs).map(Uri.file)); | |
| if (_testFileUris.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 { | |
| for (final 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 = fs.path.absolute(testPath); | |
| testPath = fs.path.normalize(testPath); | |
| if (fs.isDirectorySync(testPath)) { | |
| _testFileUris.addAll(_findTests(fs.directory(testPath), fs).map(Uri.file)); | |
| } else { | |
| _testFileUris.add(Uri.file(testPath).replace(query: uri.query)); | |
| } | |
| } | |
| } | |
| // This needs to be set before [super.verifyThenRunCommand] so that the | |
| // correct [requiredArtifacts] can be identified before [run] takes place. | |
| final List<String> testFilePaths = _testFileUris | |
| .map((Uri uri) => uri.replace(query: '').toFilePath()) | |
| .toList(); | |
| _isIntegrationTest = _shouldRunAsIntegrationTests( | |
| fs.currentDirectory.absolute.path, | |
| testFilePaths, | |
| fs, | |
| ); | |
| logger.printTrace( | |
| 'Found ${_testFileUris.length} files which will be executed as ' | |
| '${_isIntegrationTest ? 'Integration' : 'Widget'} Tests.', | |
| ); | |
| return super.verifyThenRunCommand(commandPath); | |
| } | |
| // Keep in sync with the [RunCommandBase.webRenderer] getter. | |
| WebRendererMode get webRenderer { | |
| final List<String> dartDefines = extractDartDefines( | |
| defineConfigJsonMap: extractDartDefineConfigJsonMap(), | |
| ); | |
| return WebRendererMode.fromDartDefines(dartDefines, useWasm: useWasm); | |
| } | |
| @override | |
| Future<FlutterCommandResult> runCommand() async { | |
| final ToolContext( | |
| :FileSystem fs, | |
| :Logger logger, | |
| :FlutterProjectFactory projectFactory, | |
| :Stdio stdio, | |
| ) = toolContext; | |
| 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 ' | |
| "called *_test.dart and must reside in the package's 'test' " | |
| 'directory (or one of its subdirectories).', | |
| ); | |
| } | |
| final FlutterProject flutterProject = projectFactory.fromDirectory(fs.currentDirectory); | |
| final bool buildTestAssets = getValue(_testAssets); | |
| final BuildInfo buildInfo = await getBuildInfo( | |
| forcedBuildMode: BuildMode.debug, | |
| forcedUseLocalCanvasKit: true, | |
| ); | |
| TestTimeRecorder? testTimeRecorder; | |
| if (verbose) { | |
| testTimeRecorder = TestTimeRecorder(logger); | |
| } | |
| if (buildInfo.packageConfig['test_api'] == null) { | |
| throwToolExit( | |
| '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', | |
| ); | |
| } | |
| if (getValue(_experimentalFasterTesting)) { | |
| logger.printWarning( | |
| 'The "--experimental-faster-testing" flag is deprecated and no longer ' | |
| 'has any effect. This flag will be removed in a future version of Flutter.', | |
| ); | |
| } | |
| final bool startPaused = getValue(_startPaused); | |
| if (startPaused && _testFileUris.length != 1) { | |
| throwToolExit( | |
| 'When using --start-paused, you must specify a single test file to run.', | |
| exitCode: 1, | |
| ); | |
| } | |
| final debuggingOptions = DebuggingOptions.enabled( | |
| buildInfo, | |
| startPaused: startPaused, | |
| disableServiceAuthCodes: getValue(DebuggingOptionDescriptors.disableServiceAuthCodes), | |
| disableServiceOriginCheck: getValue(DebuggingOptionDescriptors.disableServiceOriginCheck), | |
| // On iOS >=14, keeping this enabled will leave a prompt on the screen. | |
| disablePortPublication: true, | |
| enableDds: enableDds, | |
| usingCISystem: usingCISystem, | |
| enableImpeller: ImpellerStatus.fromBool(getValue(DebuggingOptionDescriptors.enableImpeller)), | |
| enableFlutterGpu: getValue(DebuggingOptionDescriptors.enableFlutterGpu) ?? false, | |
| debugLogsDirectoryPath: debugLogsDirectoryPath, | |
| platformOptions: <PlatformDebuggingOptions>[ | |
| WebDebugConfig( | |
| renderer: webRenderer, | |
| crossOriginIsolation: getValue(WebOptions.crossOriginIsolation), | |
| useWasm: useWasm, | |
| ), | |
| ], | |
| printDtd: getValue(CommonOptions.printDtd), | |
| enableHcpp: explicitEnableHcpp, | |
| uninstallApp: getValue(_uninstall), | |
| ); | |
| final (:Uri? nativeAssetsManifest, :FlutterHookResult? flutterHookResult) = _isIntegrationTest | |
| ? ( | |
| nativeAssetsManifest: null, | |
| flutterHookResult: null, | |
| ) // Don't build for host when running integration tests. | |
| : (await nativeAssetsBuilder?.buildWithHookResult( | |
| buildInfo, | |
| featureFlags: runner!.featureFlags, | |
| toolContext: toolContext, | |
| ) ?? | |
| (nativeAssetsManifest: null, flutterHookResult: null)); | |
| String? testAssetPath; | |
| if (buildTestAssets) { | |
| await _buildTestAsset( | |
| flavor: buildInfo.flavor, | |
| impellerStatus: debuggingOptions.enableImpeller, | |
| buildMode: debuggingOptions.buildInfo.mode, | |
| packageConfigPath: buildInfo.packageConfigPath, | |
| flutterHookResult: flutterHookResult, | |
| ); | |
| } | |
| if (buildTestAssets || nativeAssetsManifest != null) { | |
| testAssetPath = fs.path.join(flutterProject.directory.path, 'build', 'unit_test_assets'); | |
| } | |
| if (nativeAssetsManifest != null) { | |
| final Directory testAssetDirectory = fs.directory(testAssetPath); | |
| if (!testAssetDirectory.existsSync()) { | |
| await testAssetDirectory.create(recursive: true); | |
| } | |
| final File copiedNativeAssetsManifest = testAssetDirectory.childFile( | |
| 'NativeAssetsManifest.json', | |
| ); | |
| await fs.file(nativeAssetsManifest).copy(copiedNativeAssetsManifest.path); | |
| } | |
| int? jobs = getValue(_concurrency); | |
| if (jobs != null && (jobs <= 0 || !jobs.isFinite)) { | |
| throwToolExit( | |
| 'Could not parse -j/--concurrency argument. It must be an integer greater than zero.', | |
| ); | |
| } | |
| if (_isIntegrationTest || isWeb) { | |
| if (wasParsed(_concurrency)) { | |
| logger.printStatus( | |
| '-j/--concurrency was parsed but will be ignored, this option is not ' | |
| 'supported when running Integration Tests or web tests.', | |
| ); | |
| } | |
| // Running with concurrency will result in deploying multiple test apps | |
| // on the connected device concurrently, which is not supported. | |
| jobs = 1; | |
| } | |
| final int? shardIndex = getValue(_shardIndex); | |
| if (shardIndex != null && (shardIndex < 0 || !shardIndex.isFinite)) { | |
| throwToolExit( | |
| 'Could not parse --shard-index=$shardIndex argument. It must be an integer greater than -1.', | |
| ); | |
| } | |
| final int? totalShards = getValue(_totalShards); | |
| 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.'); | |
| } | |
| final bool enableVmService = getValue(_enableVmService); | |
| CoverageCollector? collector; | |
| if (getValue(_coverage) || getValue(_mergeCoverage) || getValue(_branchCoverage)) { | |
| final Set<String> packagesToInclude = _getCoveragePackages( | |
| getValue(_coveragePackage), | |
| flutterProject, | |
| buildInfo.packageConfig, | |
| ); | |
| collector = CoverageCollector( | |
| branchCoverage: getValue(_branchCoverage), | |
| libraryNames: packagesToInclude, | |
| packagesPath: buildInfo.packageConfigPath, | |
| resolver: await CoverageCollector.getResolver(buildInfo.packageConfigPath), | |
| testTimeRecorder: testTimeRecorder, | |
| toolContext: toolContext, | |
| verbose: !outputMachineFormat, | |
| ); | |
| } | |
| TestWatcher? watcher; | |
| if (outputMachineFormat) { | |
| watcher = EventPrinter(parent: collector, out: stdio.stdout); | |
| } else if (collector != null) { | |
| watcher = collector; | |
| } | |
| if (!isWeb && useWasm) { | |
| throwToolExit('--wasm is only supported on the web platform'); | |
| } | |
| if (webRenderer == WebRendererMode.skwasm && !useWasm) { | |
| throwToolExit('Skwasm renderer requires --wasm'); | |
| } | |
| Device? integrationTestDevice; | |
| if (_isIntegrationTest) { | |
| integrationTestDevice = await findTargetDevice(); | |
| // 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'); | |
| if (integrationTestDevice == null) { | |
| throwToolExit( | |
| 'No devices are connected. ' | |
| 'Ensure that `flutter doctor` shows at least one connected device', | |
| ); | |
| } | |
| if (integrationTestDevice.platformType == PlatformType.web) { | |
| // TODO(jiahaog): Support web. https://github.com/flutter/flutter/issues/66264 | |
| 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', | |
| ); | |
| } | |
| if (getValue(BuildInfoOptions.flavor) != null && !integrationTestDevice.supportsFlavors) { | |
| throwToolExit('--flavor is only supported for Android, Linux, macOS, and iOS devices.'); | |
| } | |
| } | |
| final filterSpec = TestFilterSpecification( | |
| names: getValue(_name), | |
| plainNames: getValue(_plainName), | |
| tags: getValue(_tags), | |
| excludeTags: getValue(_excludeTags), | |
| presets: getValue(_preset), | |
| runSkipped: getValue(_runSkipped), | |
| shardIndex: shardIndex, | |
| totalShards: totalShards, | |
| ); | |
| final executionSpec = TestExecutionSpecification( | |
| debuggingOptions: debuggingOptions, | |
| buildInfo: buildInfo, | |
| filter: filterSpec, | |
| watcher: watcher, | |
| enableVmService: collector != null || startPaused || enableVmService, | |
| machine: outputMachineFormat, | |
| updateGoldens: getValue(_updateGoldens), | |
| concurrency: jobs, | |
| testAssetDirectory: testAssetPath, | |
| flutterProject: flutterProject, | |
| web: isWeb, | |
| randomSeed: getValue(_testRandomizeOrderingSeed), | |
| reporter: getValue(_reporter), | |
| fileReporter: getValue(_fileReporter), | |
| timeout: getValue(_timeout), | |
| ignoreTimeouts: getValue(_ignoreTimeouts), | |
| failFast: getValue(_failFast), | |
| integrationTestDevice: integrationTestDevice, | |
| integrationTestUserIdentifier: getValue(CommonOptions.deviceUser), | |
| testTimeRecorder: testTimeRecorder, | |
| nativeAssetsBuilder: nativeAssetsBuilder, | |
| ); | |
| final Stopwatch? testRunnerTimeRecorderStopwatch = testTimeRecorder?.start( | |
| TestTimePhases.TestRunner, | |
| ); | |
| final int result = await _testRunner.runTests( | |
| testWrapper, | |
| _testFileUris.toList(), | |
| executionSpec, | |
| ); | |
| testTimeRecorder?.stop(TestTimePhases.TestRunner, testRunnerTimeRecorderStopwatch!); | |
| if (collector != null) { | |
| final Stopwatch? collectTimeRecorderStopwatch = testTimeRecorder?.start( | |
| TestTimePhases.CoverageDataCollect, | |
| ); | |
| final bool collectionResult = await collector.collectCoverageData( | |
| getValue(_coveragePath), | |
| mergeCoverageData: getValue(_mergeCoverage), | |
| ); | |
| testTimeRecorder?.stop(TestTimePhases.CoverageDataCollect, collectTimeRecorderStopwatch!); | |
| if (!collectionResult) { | |
| testTimeRecorder?.print(); | |
| throwToolExit(null); | |
| } | |
| } | |
| testTimeRecorder?.print(); | |
| if (result != 0) { | |
| throwToolExit(null, exitCode: result); | |
| } | |
| return FlutterCommandResult.success(); | |
| } | |
| Set<String> _getCoveragePackages( | |
| List<String> packagesRegExps, | |
| FlutterProject flutterProject, | |
| PackageConfig packageConfig, | |
| ) { | |
| final packagesToInclude = <String>{}; | |
| if (packagesRegExps.isEmpty) { | |
| void addProject(FlutterProject project) { | |
| packagesToInclude.add(project.manifest.appName); | |
| project.workspaceProjects.forEach(addProject); | |
| } | |
| addProject(flutterProject); | |
| } | |
| try { | |
| for (final regExpStr in packagesRegExps) { | |
| final regExp = RegExp(regExpStr); | |
| packagesToInclude.addAll( | |
| packageConfig.packages.map((Package e) => e.name).where((String e) => regExp.hasMatch(e)), | |
| ); | |
| } | |
| } on FormatException catch (e) { | |
| throwToolExit('Regular expression syntax is invalid. $e'); | |
| } | |
| return packagesToInclude; | |
| } | |
| /// 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) { | |
| final ToolContext(:FileSystem fs, :Platform platform) = toolContext; | |
| // 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 = fs.path.absolute(filePart); | |
| filePart = fs.path.normalize(filePart); | |
| try { | |
| return Uri.file( | |
| filePart, | |
| windows: platform.isWindows, | |
| ).replace(query: queryPart.isEmpty ? null : queryPart); | |
| } on ArgumentError catch (e) { | |
| throwToolExit('Invalid test path "$arg": ${e.message}'); | |
| } on FormatException catch (e) { | |
| throwToolExit('Invalid test path "$arg": ${e.message}'); | |
| } | |
| } | |
| Future<void> _buildTestAsset({ | |
| required String? flavor, | |
| required ImpellerStatus impellerStatus, | |
| required BuildMode buildMode, | |
| required String packageConfigPath, | |
| FlutterHookResult? flutterHookResult, | |
| }) async { | |
| final ToolContext(:Config config, :FileSystem fs) = toolContext; | |
| final AssetBundle assetBundle = _assetBundleFactory.createBundle(); | |
| final int build = await assetBundle.build( | |
| flutterHookResult: flutterHookResult, | |
| packageConfigPath: packageConfigPath, | |
| flavor: flavor, | |
| includeAssetsFromDevDependencies: true, | |
| targetPlatform: TargetPlatform.tester, | |
| ); | |
| if (build != 0) { | |
| throwToolExit('Error: Failed to build asset bundle'); | |
| } | |
| if (await _needsRebuild(assetBundle.entries, flavor, flutterHookResult)) { | |
| await writeBundle( | |
| fs.directory(fs.path.join(getBuildDirectory(config, fs), 'unit_test_assets')), | |
| assetBundle.entries, | |
| buildMode: buildMode, | |
| impellerStatus: impellerStatus, | |
| projectDir: fs.currentDirectory, | |
| targetPlatform: TargetPlatform.tester, | |
| toolContext: toolContext, | |
| ); | |
| final File cachedFlavorFile = fs.file( | |
| fs.path.join(getBuildDirectory(config, fs), 'test_cache', 'flavor.txt'), | |
| ); | |
| if (cachedFlavorFile.existsSync()) { | |
| await cachedFlavorFile.delete(); | |
| } | |
| if (flavor != null) { | |
| cachedFlavorFile.createSync(recursive: true); | |
| cachedFlavorFile.writeAsStringSync(flavor); | |
| } | |
| } | |
| } | |
| Future<bool> _needsRebuild( | |
| Map<String, AssetBundleEntry> entries, | |
| String? flavor, | |
| FlutterHookResult? flutterHookResult, | |
| ) async { | |
| final ToolContext(:Config config, :FileSystem fs) = toolContext; | |
| final String unitTestAssetsDir = fs.path.join( | |
| getBuildDirectory(config, fs), | |
| 'unit_test_assets', | |
| ); | |
| final File manifest = fs.file(fs.path.join(unitTestAssetsDir, 'AssetManifest.bin')); | |
| if (!manifest.existsSync()) { | |
| return true; | |
| } | |
| final DateTime lastModified = manifest.lastModifiedSync(); | |
| final File pub = fs.file('pubspec.yaml'); | |
| if (pub.existsSync() && pub.lastModifiedSync().isAfter(lastModified)) { | |
| return true; | |
| } | |
| for (final MapEntry(key: String assetPath, value: AssetBundleEntry assetEntry) | |
| in entries.entries) { | |
| final File file = fs.file(fs.path.join(unitTestAssetsDir, assetPath)); | |
| if (!file.existsSync()) { | |
| return true; | |
| } | |
| final DevFSContent content = assetEntry.content; | |
| if (content is DevFSFileContent) { | |
| if (content.isModifiedAfter(lastModified)) { | |
| return true; | |
| } | |
| } else { | |
| final List<int> entryBytes = await assetEntry.contentsAsBytes(); | |
| if (entryBytes.length != await file.length()) { | |
| return true; | |
| } | |
| final List<int> fileBytes = await file.readAsBytes(); | |
| if (!listEquals(entryBytes, fileBytes)) { | |
| return true; | |
| } | |
| } | |
| } | |
| for (final Uri dependency in flutterHookResult?.dependencies ?? const <Uri>[]) { | |
| final FileStat stat = fs.statSync(dependency.toFilePath()); | |
| if (stat.type == FileSystemEntityType.notFound || stat.modified.isAfter(lastModified)) { | |
| return true; | |
| } | |
| } | |
| final File cachedFlavorFile = fs.file( | |
| fs.path.join(getBuildDirectory(config, fs), 'test_cache', 'flavor.txt'), | |
| ); | |
| final String? cachedFlavor = cachedFlavorFile.existsSync() | |
| ? cachedFlavorFile.readAsStringSync() | |
| : null; | |
| if (cachedFlavor != flavor) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| } | |
| /// Searches [directory] and returns files that end with `_test.dart` as | |
| /// absolute paths. | |
| Iterable<String> _findTests(Directory directory, FileSystem fs) { | |
| 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)); | |
| } | |
| /// 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, FileSystem fs) { | |
| final String integrationTestDirectory = 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.', | |
| ); | |
| } |