runEnsembleTestsCli function

Future<void> runEnsembleTestsCli(
  1. List<String> arguments
)

Runs declarative tests in an Ensemble app.

The host app must list ensemble_test_runner in dev_dependencies.

Options: --app-dir=

Implementation

Future<void> runEnsembleTestsCli(List<String> arguments) async {
  if (arguments.contains('--help') || arguments.contains('-h')) {
    stdout.writeln(_cliHelp);
    return;
  }
  final verbose = isVerboseCli(arguments);
  final quiet = arguments.contains('--quiet');
  final reportMode = CliArgumentOptions.reportMode(arguments);
  final jsonReport = reportMode == 'json';
  final junitReport = reportMode == 'junit';
  final machineReport = jsonReport || junitReport;
  final streamLiveOutput = !quiet && !machineReport;
  final reportFile = CliArgumentOptions.reportFile(arguments);
  final appDir = CliArgumentOptions.appDirectory(arguments);
  final reportCoordinator = CliReportCoordinator(appDir);
  final workerWorkspace = CliWorkerWorkspace(appDir);
  final ownsFlutterKernelCache =
      flutter_test_command.isRunnerPackageRoot(Directory(appDir));
  try {
    flutter_test_command.validatePlanBatchFile(arguments);
  } on StateError catch (error) {
    stderr.writeln(error.message);
    exit(2);
  }
  final timeoutSeconds = CliArgumentOptions.timeoutSeconds(arguments);
  final jobs = CliArgumentOptions.jobsOverride(arguments);
  final testsDirOptions = CliTestSelection.values(arguments, '--tests-dir');
  final testEntryOptions = CliTestSelection.values(arguments, '--test-entry');
  if (testsDirOptions.length > 1 || testEntryOptions.length > 1) {
    stderr.writeln('--tests-dir and --test-entry may each be specified once.');
    exit(2);
  }
  final testEntry = testEntryOptions.isEmpty ? null : testEntryOptions.first;
  final explicitTestsDir =
      testsDirOptions.isEmpty ? null : testsDirOptions.first;
  if (explicitTestsDir != null &&
      testEntry == null &&
      !File(p.join(appDir, 'ensemble', 'ensemble-config.yaml')).existsSync()) {
    stderr.writeln(
      'Pure Flutter suites require --test-entry=<path> in addition to '
      '--tests-dir.',
    );
    exit(2);
  }
  late final TestAppPatcher patcher;
  try {
    patcher = TestAppPatcher(
      appDir,
      testsDirRelative:
          explicitTestsDir ?? (testEntry == null ? null : 'tests'),
      testEntryRelativePath: testEntry,
    );
  } on StateError catch (error) {
    stderr.writeln(error.message);
    exit(2);
  }

  if (!Directory(appDir).existsSync()) {
    stderr.writeln('App directory not found: $appDir');
    exit(2);
  }

  if (!File('${appDir}/pubspec.yaml').existsSync()) {
    stderr.writeln('No pubspec.yaml in $appDir');
    exit(2);
  }

  if (arguments.contains('--doctor')) {
    if (patcher.usesApplicationEntry) {
      final lines = <String>[
        'Ensemble test runner doctor (application-provided entry)',
        'App: $appDir',
        'Tests: ${patcher.testsDirRelative}',
        'Entry: ${patcher.activeEntryRelativePath}',
      ];
      var hasErrors = false;
      void error(String message) {
        hasErrors = true;
        lines.add('[ERROR] $message');
      }

      void ok(String message) => lines.add('[OK] $message');

      final testsRelative = patcher.testsDirRelative;
      if (testsRelative == null || testsRelative.isEmpty) {
        error('Missing --tests-dir for application-provided suites');
      } else {
        final testsDir = Directory(p.join(appDir, testsRelative));
        if (!testsDir.existsSync()) {
          error('Tests directory not found: $testsRelative');
        } else {
          ok('Found tests directory $testsRelative');
        }
      }

      final entryFile = File(p.join(appDir, patcher.activeEntryRelativePath));
      if (!entryFile.existsSync()) {
        error('test entry not found: ${patcher.activeEntryRelativePath}');
      } else {
        ok('test entry exists and will not be overwritten');
      }

      final result = EnsembleTestValidator(
        appDir,
        testsDirRelative: patcher.testsDirRelative,
        applicationProvided: true,
      ).validate();
      lines.addAll(result.formatText().split('\n'));
      stdout.writeln(lines.join('\n'));
      exit(hasErrors || result.hasErrors ? 1 : 0);
    }
    ExecutionMode? modeOverride;
    try {
      if (CliTestSelection.values(arguments, '--mode').isNotEmpty) {
        modeOverride = _resolveExecutionMode(
          arguments,
          ExecutionMode.widget,
        );
      }
    } catch (error) {
      stderr.writeln(error);
      exit(2);
    }
    final result = await EnsembleTestDoctor(
      appDir,
      modeOverride: modeOverride,
    ).run(fix: arguments.contains('--fix'));
    stdout.writeln(result.lines.join('\n'));
    exit(result.hasErrors ? 1 : 0);
  }

  if (arguments.contains('--inspect-app')) {
    if (patcher.usesApplicationEntry) {
      stdout.writeln(const JsonEncoder.withIndent('  ').convert({
        'launchKind': 'applicationProvided',
        'staticMetadataAvailable': false,
        'message':
            'Host widget and route metadata is available only at runtime.',
      }));
      exit(0);
    }
    try {
      stdout.writeln(EnsembleAppInspector(appDir).inspect().toPrettyJson());
      exit(0);
    } on StateError catch (error) {
      stderr.writeln(error.message);
      exit(2);
    }
  }

  if (arguments.contains('--validate-only')) {
    final result = EnsembleTestValidator(
      appDir,
      testsDirRelative: patcher.testsDirRelative,
      applicationProvided: patcher.usesApplicationEntry,
    ).validate();
    stdout.writeln(jsonReport ? result.toPrettyJson() : result.formatText());
    exit(result.hasErrors ? 2 : 0);
  }

  if (arguments.any((arg) =>
      arg == '--scaffold-test' || arg.startsWith('--scaffold-test='))) {
    try {
      final result = EnsembleTestScaffold(
        appDir,
        testsDirRelative: patcher.testsDirRelative,
        applicationProvided: patcher.usesApplicationEntry,
      ).create(arguments);
      stdout.writeln(
        result.created
            ? 'Created ${result.path}'
            : 'Test file already exists: ${result.path}',
      );
      exit(result.created ? 0 : 2);
    } on StateError catch (error) {
      stderr.writeln(error.message);
      exit(2);
    }
  }

  final testsDirRelative = patcher.testsDirRelative;
  if (testsDirRelative == null) {
    stderr.writeln(
      'Could not find definitions.local.path in ensemble/ensemble-config.yaml.\n'
      'Declarative tests must live under definitions.local.path/tests.',
    );
    exit(2);
  }
  final suiteSource = TestSuiteSource(
    appDirectory: appDir,
    testsDirectory: testsDirRelative,
    testsAssetPrefix: testsDirRelative.endsWith('/')
        ? testsDirRelative
        : '$testsDirRelative/',
    testEntryPath: patcher.activeEntryRelativePath,
    launchKind: patcher.usesApplicationEntry
        ? TestApplicationLaunchKind.applicationProvided
        : TestApplicationLaunchKind.standaloneEnsemble,
  );

  if (!patcher.hasTestsOnDisk) {
    stderr.writeln(
      'No declarative tests found. Add *.test.yaml files under '
      '$testsDirRelative/',
    );
    exit(2);
  }

  late final ExecutionMode executionMode;
  late EnsembleTestConfig suiteConfig;
  try {
    suiteConfig = shard_planner.readCliTestsConfigStrict(patcher.testsDirPath!);
    executionMode =
        CliArgumentOptions.executionMode(arguments, suiteConfig.mode);
    CliArgumentOptions.validateExecutionModeOptions(
      arguments,
      mode: executionMode,
      config: suiteConfig,
      jobs: jobs,
    );
  } catch (error) {
    stderr.writeln(error);
    exit(2);
  }

  final executionBackend = executionBackendFor(executionMode);

  FlutterDevice? integrationDevice;
  try {
    integrationDevice = await executionBackend.selectDevice(
      arguments,
      flutterExecutable: resolveFlutterExecutable(appDir),
    );
    if (integrationDevice != null) {
      _validatePlatformProject(appDir, integrationDevice.platform);
      suiteConfig = shard_planner.applyCliIntegrationDeviceMatrix(
        suiteConfig,
        platform: integrationDevice.platform,
        arguments: arguments,
        quiet: quiet,
      );
      if (!integrationDevice.isVirtual &&
          !arguments.contains('--allow-device-storage-mutation') &&
          !arguments.contains('--reset-device-storage')) {
        throw StateError(
          'Physical device ${integrationDevice.display} will mutate app '
          'storage during the suite. Pass --allow-device-storage-mutation '
          'to acknowledge this, or --reset-device-storage to wipe storage '
          'first on a disposable device.',
        );
      }
    }
  } catch (error) {
    stderr.writeln(error);
    exit(2);
  }

  final artifactLock = CliRunArtifactLock(appDir);
  if (!artifactLock.acquire()) {
    stderr.writeln(
      'Another Ensemble test run is already using the app artifact directory. '
      'Wait for it to finish before starting another run.',
    );
    exit(3);
  }

  if (ownsFlutterKernelCache) {
    try {
      // Reclaim cache left by an interrupted runner invocation before creating
      // more build artifacts. App-owned build caches are never pruned here.
      flutter_test_command.pruneFlutterTestKernelCache(Directory(appDir));
    } catch (_) {
      // Cache maintenance is best effort and must not strand the run lock.
    }
  }
  await _executeCliRun(
    arguments: arguments,
    appDir: appDir,
    patcher: patcher,
    artifactLock: artifactLock,
    pruneKernelCache: ownsFlutterKernelCache,
    verbose: verbose,
    quiet: quiet,
    machineReport: machineReport,
    jsonReport: jsonReport,
    junitReport: junitReport,
    streamLiveOutput: streamLiveOutput,
    reportMode: reportMode,
    reportFile: reportFile,
    timeoutSeconds: timeoutSeconds,
    jobs: jobs,
    suiteConfig: suiteConfig,
    executionMode: executionMode,
    executionBackend: executionBackend,
    integrationDevice: integrationDevice,
    suiteSource: suiteSource,
    reportCoordinator: reportCoordinator,
    workerWorkspace: workerWorkspace,
  );
}