registerEnsembleTestsInternal function

Future<void> registerEnsembleTestsInternal(
  1. EnsembleTestOptions options,
  2. Iterable<TestIntegrationRegistration> integrations
)

Registers the shared test suite after an execution-specific binding exists.

Integration entry points initialize IntegrationTestWidgetsFlutterBinding and call this function with ExecutionMode.integration.

Implementation

Future<void> registerEnsembleTestsInternal(
  EnsembleTestOptions options,
  Iterable<TestIntegrationRegistration> integrations,
) async {
  configureArtifactTransport(options.mode);
  EnsembleTestHarness.configureTestIntegrations(integrations);
  final runtimeAdapter = EnsembleTestHarness.runtimeAdapterFor(options.mode);
  runtimeAdapter.initialize();
  tearDown(() async {
    try {
      // Dual path with the suite `finally`. After the first attempt the harness
      // clears the baseline, so this is usually a no-op. If finally never ran,
      // a restore failure here fails the test (infrastructure error).
      await EnsembleTestHarness.restorePreSuiteStorageAtSuiteEnd();
      EnsembleTestHarness.resetTestRuntime();
    } finally {
      EnsembleTestHarness.disposeTestStorage();
    }
  });

  testWidgets(
    'Ensemble app test suite',
    (tester) async {
      if (!usesDeviceArtifactTransport) {
        ScreenshotArchive.clearPendingImages(ensembleTestArtifactRoot);
      }
      await EnsembleTestHarness.runWithRealNetworkHttpOverrides(
        () => withFlutterErrorIsolation(() async {
          var emittedMachineReport = false;
          void emitMachineReport(EnsembleTestRunResult result) {
            emitMachineTestReport(result);
            emittedMachineReport = true;
          }

          Object? suiteError;
          StackTrace? suiteStackTrace;
          Object? storageRestoreError;

          try {
            if (options.bootstrap == null) {
              fail(
                'Ensemble tests require module bootstrap. '
                'In test/ensemble_tests.dart call runEnsembleTests with '
                'bootstrap: () => EnsembleModules().init() '
                '(see ensemble_test_runner README).',
              );
            }
            await tester.runAsync(() async {
              await options.bootstrap!();
              runtimeAdapter.afterBootstrap();
              // Module constructors may schedule follow-up async init work.
              await Future<void>.delayed(Duration.zero);
            });
            if (options.mode == ExecutionMode.integration &&
                usesDeviceArtifactTransport) {
              emitEnsembleTestArtifactTransportBegin();
            }

            final target = await EnsembleTestDiscovery.loadAppTarget();
            final workerBatch = await workerBatchFromEnvironment();
            final plan = workerBatch?.plan ??
                await FlutterTestExecutionPlanner.build(
                  target: target,
                  selection: testSelectionFromEnvironment(),
                  inputs: testInputsFromEnvironment(),
                );
            final harness = EnsembleTestHarness(
              externalMethods: options.externalMethods,
              executionMode: options.mode,
            );

            final runner = EnsembleTestRunner(harness: harness);
            final serializedPlans = workerBatch?.serializedPlans ?? const {};
            final planResult = await runner.runPlan(
              plan,
              tester,
              onTestStart: emitTestProgressStart,
              onTestComplete: emitTestProgressComplete,
              serializedPlans: serializedPlans,
            );
            final resultsById = planResult.resultsById;
            final pendingFrameworkExceptions = <Object?>[];
            await _pumpBestEffort(tester, pendingFrameworkExceptions);

            final failures = <String>[];
            final orderedResults = <EnsembleSingleTestResult>[];

            for (final def in plan.ordered) {
              final result = resultsById[def.testCase.id]!;
              orderedResults.add(
                EnsembleSingleTestResult(
                  testId: '${result.testId}  (${def.assetPath})',
                  metadata: result.metadata,
                  status: result.status,
                  durationMs: result.durationMs,
                  attempts: result.attempts,
                  retry: result.retry,
                  failedStepIndex: result.failedStepIndex,
                  failedStep: result.failedStep,
                  message: result.message,
                  stackTrace: result.stackTrace,
                  failureOperation: result.failureOperation,
                  failureSource: result.failureSource,
                  logs: result.logs,
                  report: result.report,
                ),
              );

              if (result.status == TestStatus.failed) {
                failures.add(def.assetPath);
              }
            }

            final suiteLogs = <String>[
              ...planResult.suiteLogs,
            ];
            var runResult = EnsembleTestRunResult(
              results: orderedResults,
              suiteLogs: suiteLogs,
              metadata: _runMetadata(options.mode),
            );
            if (options.mode == ExecutionMode.widget &&
                !isEnsembleTestParallelWorker() &&
                !usesDeviceArtifactTransport) {
              if (await _recordHistory(runResult)) {
                suiteLogs.add('history: $_historyDisplayPath');
                runResult = EnsembleTestRunResult(
                  results: orderedResults,
                  suiteLogs: suiteLogs,
                  metadata: _runMetadata(options.mode),
                );
              }
            }
            if (options.mode == ExecutionMode.widget &&
                !isEnsembleTestParallelWorker() &&
                !usesDeviceArtifactTransport) {
              final htmlPath = HtmlTestReporter().writeShell(
                cleanIntermediates: true,
              );
              suiteLogs.add('htmlReport: $htmlPath');
              runResult = EnsembleTestRunResult(
                results: orderedResults,
                suiteLogs: suiteLogs,
                metadata: _runMetadata(options.mode),
              );
            }
            // Background app errors are recorded by TestErrorTracker and can be
            // asserted with expectNoRenderErrors/expectError. Explicitly unmount
            // the app and drain teardown exceptions so a suite with passing YAML
            // assertions does not fail after the summary is printed.
            pendingFrameworkExceptions.addAll(
              await _drainPendingExceptionsAndUnmount(tester),
            );

            final reporter = TestReporter();
            final suiteSummary = reporter.formatSummary(
              runResult,
              testFile: '${target.testsAssetPrefix}*.test.yaml',
            );
            print(suiteSummary);
            emitMachineReport(runResult);
            _ignorePostTestAnimationInvariant();

            if (failures.isNotEmpty) {
              fail(
                reporter.formatFailureSummary(
                  runResult,
                  failedPaths: failures,
                  pendingFrameworkExceptions: pendingFrameworkExceptions,
                ),
              );
            }
          } catch (error, stackTrace) {
            suiteError = error;
            suiteStackTrace = stackTrace;
            if (!emittedMachineReport) {
              final runResult = EnsembleTestRunResult(
                results: [
                  EnsembleSingleTestResult.failed(
                    testId: 'test-process',
                    durationMs: 0,
                    message: error.toString(),
                    stackTrace: stackTrace.toString(),
                  ),
                ],
                suiteLogs: const [],
                metadata: _runMetadata(options.mode),
              );
              emitMachineReport(runResult);
            }
          } finally {
            try {
              await EnsembleTestHarness.restorePreSuiteStorageAtSuiteEnd();
            } catch (error) {
              storageRestoreError = error;
              stderr.writeln(
                'Failed to restore pre-suite storage at suite end: $error',
              );
            }
            if (options.mode == ExecutionMode.integration &&
                usesDeviceArtifactTransport) {
              emitEnsembleTestArtifactTransportComplete();
            }
          }

          reportSuiteEndWithStorageRestore(
            suiteError: suiteError,
            suiteStackTrace: suiteStackTrace,
            storageRestoreError: storageRestoreError,
          );
        }),
      );
    },
    timeout: _timeoutSeconds > 0
        ? Timeout(Duration(seconds: _timeoutSeconds))
        : Timeout.none,
  );
}