Skip to main content

ensemble_test_runner 1.4.3 copy "ensemble_test_runner: ^1.4.3" to clipboard
ensemble_test_runner: ^1.4.3 copied to clipboard

Declarative test runner for Ensemble apps with runtime mocks, widget assertions, fixtures, and CLI reporting.

ensemble_test_runner #

Dev-only declarative YAML test runner for standalone Ensemble, pure Flutter, and mixed Flutter/Ensemble apps. It uses one exact, YAML-driven UI vocabulary while application-owned state and services remain behind explicit driver capabilities.

This package is not a dependency of modules/ensemble. It is a dev-only dependency — not shipped in release builds.

Write tests (YAML only) #

Add *.test.yaml files under the configured local app path's tests/ directory, for example ensemble/apps/helloApp/tests/:

id: hello_home_renders
startScreen: Hello Home
initialState:
  storage:
    helloApp:
      name:
        first: John
        last: Doe
  # Ensemble encrypted public storage. Keys are logical keys; values are
  # encrypted at bootstrap and persisted internally as enc_<key>.
  secureStorage:
    onboardingComplete: true
  # Platform FlutterSecureStorage, used by keychain/readSecurely actions.
  keychain:
    authToken: test-token
steps:
  - expectVisible:
      id: greeting_text

Each *.test.yaml file is one test (no tests: array). Standalone Ensemble tests require startScreen. Application-driven Flutter and mixed tests omit it unless their driver explicitly implements screen launch. Tests that need reusable app state can set session only when the driver supports checkpoints.

Unified targets #

Existing id: syntax is unchanged. A structured target can address accessible Flutter or Ensemble-originated widgets without a framework selector:

steps:
  - tap:
      target:
        label: Continue
        role: button
        within:
          id: login_form
        occurrence: 0

id, text, label, and role are exact, conjunctive constraints. within limits matching to descendants and occurrence is zero-based. A missing target or an ambiguous target without occurrence fails; the runner does not guess. Snapshot element IDs retain exact observation identity and never fall back to a locator when stale.

Use root-level setup for commands and HTTP requests that must complete before the screen is mounted. This is useful for resetting or configuring a stub server:

id: authenticated_home
session: signin
startScreen: Home
setup:
  - httpRequest:
      method: POST
      url: ${services.testService.url}/api/v1/stub/scenario
      body: {testcase: home, responsename: offline}
steps:
  - expectVisible: {id: offline_message}

Widget YAML must set testId (or id, which maps to the same ValueKey).

Step vocabulary #

The full official catalog (lifecycle, gestures, API assertions, debug, etc.) is in STEP_VOCABULARY.md.

Machine-readable registry (single source): lib/vocabulary/test_step_registry.dart.

JSON Schema (editor validation) #

A JSON Schema for *.test.yaml is hosted at https://cdn.ensembleui.com/schemas/ensemble_tests_schema.json. The committed copy lives at assets/schema/ensemble_tests_schema.json and is generated from the step registry:

cd tools/ensemble_test_runner && dart run tool/generate_schema.dart

Or per file at the top of a test:

# yaml-language-server: $schema=https://cdn.ensembleui.com/schemas/ensemble_tests_schema.json

Suite-wide runner config lives in tests/config.yaml. The schema is hosted at https://cdn.ensembleui.com/schemas/ensemble_test_config_schema.json:

# yaml-language-server: $schema=https://cdn.ensembleui.com/schemas/ensemble_test_config_schema.json
mocks:
  - mocks/common/base.mock.json

initialState:
  storage:
    apiUrl: http://ensemble.test/api/devices
  env:
    APP_LOCALE: nl

services:
  - name: testService
    command: .venv/bin/python
    arguments: [test_service/app.py]
    workingDirectory: ensemble/apps/sample_app/autotests
    readyUrl: /ping

The runner assigns a free local port. Tests can reference that resolved endpoint
as `${services.testService.url}`.

screenshots:
  enabled: true
  includeSteps: []
  excludeSteps: []

# Device matrix (viewport + optional locale/theme). One entry = single device;
# multiple entries expand each test once per device with its own screenshot sheet.
# Widget mode applies platform/model as a viewport. Integration mode keeps
# locale/theme for entries matching the connected emulator/simulator and
# ignores viewport/model.
devices:
  - id: android_nl
    platform: android
    model: Samsung Galaxy S20
    locale: nl
    theme: light
  - id: iphone_en
    platform: ios
    model: iPhone 15 Pro
    locale: en
    theme: dark

performance:
  enabled: true
timers:
  enabled: true
  maxStartAfterSeconds: 1
  maxRepeatIntervalSeconds: 1
  # Optional per-screen maxNumberOfTimes cap (screen filename without .yaml).
  maxNumberOfTimesByScreen:
    FirmwareUpgrade: 15
logApiCalls:
  enabled: true
logStorage:
  enabled: true

mocks and initialState in config.yaml apply to every test. Test-file mocks / initialState values override suite values for the same API name or storage/secureStorage/keychain/env key. storage, secureStorage, and keychain are separate backends: secureStorage is Ensemble's encrypted public-storage namespace, while keychain is platform secure storage.

When devices is set, each test expands to one run per device (ids look like home[android_nl] when there is more than one device). Device locale sets APP_LOCALE for that run without rewriting startScreenInputs. Device theme (light / dark) is applied through EnsembleThemeManager after boot (any start screen). Each device run writes its own frames manifest under build/ensemble_test_runner/frames/ (for example home[android_nl]_frames.json and home[iphone_en]_frames.json); the HTML report builds the contact-sheet gallery from per-step images packed into report/screenshots.zip; the viewer reads archive entries in memory without extracting them. In integration mode the same matrix is filtered to the connected target's platform: locale/theme still apply, viewport/model do not, and other platforms are skipped with a warning.

Report step capture (screenshot + Observer) #

Per-step report artifacts are written as an atomic pair: screenshot first, then Observer overlays mapped onto that PNG. If the shot is skipped, Observer is not written for that step.

  • User actions (tap, toggle, …): capture before the act so the gallery shows the control that was targeted.
  • Asserts / waits: capture after the condition matches (or mid-wait for waitForText / waitForNavigation) so overlays match the verified screen.
  • Runtime observe (DiagnosticUiSnapshot for locators / waits) is separate from the report Observer tab and is not required to match a PNG.

See lib/runner/step_report_capture.dart for the policy flags (beforeAction, afterCondition, onFailure).

App setup #

  1. Add *.test.yaml files under definitions.local.path/tests/, for example ensemble/apps/helloApp/tests/.
  2. Configure definitions.local in ensemble/ensemble-config.yaml (path, appHome, i18n.path).
  3. Add ensemble_test_runner to dev_dependencies (same git url/ref as your ensemble: dependency).
  4. Run flutter pub get.

Public Dart API #

The package is primarily test-document-first, but it also exposes a small Dart API for integrations and custom tooling through package:ensemble_test_runner/ensemble_test_runner.dart.

  • runEnsembleTests runs a suite from a Flutter test environment.
  • runApplicationTests runs pure Flutter or mixed suites through an ApplicationTestDriver. It selects widget vs integration from the CLI ensembleTestExecutionMode dart-define. In widget mode it installs the shared Firebase bridges automatically; host apps only initialize Firebase with their own options and use their normal sign-in flow.
  • ApplicationTestServices exposes optional navigation, API, storage, and runtime metadata capabilities. ApplicationCheckpointDriver is required when host YAML uses session:.
  • EnsembleTestParser parses test files and suite configuration.
  • EnsembleTestCase, EnsembleTestConfig, and related model types represent the supported test-document format.
  • EnsembleTestRunner and EnsembleTestHarness are available when an integration needs direct control of execution.

The API documentation is generated from the public declarations and is available on the package API tab on pub.dev.

Runnable examples #

example/ is a standalone Ensemble app (runApp(EnsembleApp())) with local screen definitions.

example_host/ is a Flutter host with Ensemble as a child: Flutter login, then a 3-tab Flutter shell (Home, Shop, Account). Shop is an Ensemble screen opened from the bottom nav or from a card on the Flutter Home tab. Ensemble initializes when that shell appears.

cd example
flutter pub get
flutter run
dart run ensemble_test_runner:ensemble_test --mode=widget
cd example_host
flutter pub get
dart run ensemble_test_runner:ensemble_test \
  --tests-dir=tests \
  --test-entry=test/application_tests.dart \
  --mode=widget

Run #

From your app directory (e.g. starter/):

dart run ensemble_test_runner:ensemble_test

The command must run from the Flutter wrapper app root — the directory with pubspec.yaml and ensemble/ensemble-config.yaml. Dart resolves ensemble_test_runner:ensemble_test from the current package's dev_dependencies, so running the command from ensemble/apps/<app> will fail before the runner starts.

The CLI temporarily bundles definitions.local.path/tests/ as an asset (if needed), writes test/ensemble_tests.dart, runs flutter test, then restores your pubspec.yaml and removes the generated test file.

By default, output is quiet: no pub get package list, no Flutter test progress lines — SCREEN TRACKER navigation logs plus the boxed suite report. Use --verbose for full subprocess output (useful when debugging).

Optional: --app-dir=<path> when not running from the app root.

Pure Flutter and mixed applications #

Keep host YAML under tests/ (the default; test/ remains Dart widget tests), and provide an application-owned entry file:

import 'package:ensemble_test_runner/ensemble_test_runner.dart';
import 'test_driver.dart';

Future<void> main() => runApplicationTests(driver: MyAppTestDriver());

Widget-mode Firebase support is included: Firebase Core, Auth, Firestore, Cloud Functions, and Remote Config channels are bridged by the runner. Public Firestore reads use the configured project without requiring a user token; private reads require the app's real sign-in flow or an optional ENSEMBLE_TEST_FIREBASE_ID_TOKEN. Remote Config uses app-configured defaults in widget mode and does not claim to fetch live values. Use integration mode when a test requires native plugin behavior or live Remote Config.

Run it with paths relative to the application root:

dart run ensemble_test_runner:ensemble_test \
  --tests-dir=tests \
  --test-entry=test/application_tests.dart

The entry is validated but never generated, overwritten, or deleted. Both paths must remain inside --app-dir. Supplying --tests-dir alone in an existing Ensemble app continues to use the generated legacy entry; a pure Flutter app must provide --test-entry.

--mode=integration uses that same host entry. The CLI writes a temporary integration_test/<entry>.dart wrapper so Flutter detects the native plugin, then deletes it when the run finishes. Relative imports stay on the original entry; runApplicationTests picks the integration binding from --dart-define=ensembleTestExecutionMode=integration.

See example_host/ for a complete Flutter-host + Ensemble-child app: login, bottom nav, and a host card that opens the same Ensemble screen.

The driver lifecycle is suite setup, per-attempt preparation, headless test setup, application launch, one shared execution session, compiled operation execution through FlutterTestRuntime, session close, per-attempt cleanup, then suite teardown. Operations dispatch through the registry-backed runtime. Cleanup receives a nullable handle and still runs after a launch failure. Every retry repeats the complete per-attempt lifecycle.

Execution modes #

Suites run as Flutter widget tests by default. Set the suite mode in tests/config.yaml, or override it from the command line:

mode: widget
# Existing host-side widget-test environment.
dart run ensemble_test_runner:ensemble_test

# Build, install, and launch on an Android emulator or iOS simulator.
dart run ensemble_test_runner:ensemble_test \
  --mode=integration \
  --device-id=emulator-5554

--mode takes precedence over tests/config.yaml. Integration mode is serial and supports one Android or iOS target per invocation (emulator, simulator, or physical device). If one eligible target is connected it is selected automatically; multiple targets are offered interactively, while non-interactive runs must pass --device-id.

The existing devices matrix and --device flag still apply in integration mode for locale/theme, not as additional connected devices. The runner keeps entries whose platform matches the connected target, skips the rest with a warning, and uses that target's real display (no stock device bezel). --device filters those matching rows; --device-id selects the real Flutter target. Widget-mode screenshots still get a device frame for the HTML report.

Contact-sheet WebP encoding is optional. The runner uses the platform cwebp binary when a webp package is present in the consuming app's package config; otherwise it writes device-framed report images as JPEG or PNG (integration captures remain PNG). Add webp to the consuming app's development dependencies to enable the bundled encoder binaries. Native UI such as permission dialogs is not supported in this release.

Physical Android devices use adb reverse for host services (same as emulators). Physical iPhones need the Mac and phone on the same LAN; pass --host-address= to override auto-detection. USB-only iOS networking and wireless debugging setup are not supported yet. Signing/provisioning remain Xcode/Android Studio prerequisites — the runner does not rewrite signing settings.

Integration iOS builds need deployment target 15.0 (Firebase 12). Flutter's default Podfile still comments platform :ios, '13.0', which makes CocoaPods fail with cloud_firestore / "higher minimum iOS deployment version". Set platform :ios, '15.0' in the host app (and matching IPHONEOS_DEPLOYMENT_TARGET), or run dart run ensemble_test_runner:ensemble_test --doctor --fix. The runner does not silently rewrite native project files. Add a version: field to pubspec.yaml so iOS has CFBundleShortVersionString / CFBundleVersion.

Configured test services remain host processes. Android emulator and USB device runs use adb reverse to reach them, while iOS simulators use host loopback. Physical iPhones need the host LAN address (see --host-address). Ensemble API mocks and initial storage continue to use the shared YAML engine; native plugins are supplied by the installed application rather than widget-test method-channel doubles.

Independent integration tests restore storage to a pre-suite baseline so device credentials that existed before the run are preserved. Pass --reset-device-storage on disposable emulators when a full wipe is intended. Physical devices also require --allow-device-storage-mutation (or --reset-device-storage) before the suite may capture or rewrite storage.

Integration results, logs, and screenshot PNGs are transported back to the host and written under the same build/ensemble_test_runner/ paths as widget mode. JSON, JUnit, HTML, history, filters, retries, and sessions retain their existing contracts.

Pass test-runner inputs with repeatable --input key=value flags. Tests can reference them as ${inputs.key} in initialState, mocks, and steps:

dart run ensemble_test_runner:ensemble_test \
  --input adminPassword='s4C>M7U6t~' \
  --input expectedDeviceCount=2
initialState:
  keychain:
    adminPassword: ${inputs.adminPassword}
steps:
  - expectText:
      text: ${inputs.expectedDeviceCount}

There is no implicit whole-suite timeout; individual steps and services keep their own bounded timeouts. Add one when CI should enforce a suite deadline:

dart run ensemble_test_runner:ensemble_test --timeout=30s
dart run ensemble_test_runner:ensemble_test --timeout=15m
dart run ensemble_test_runner:ensemble_test --timeout=1h

Validate setup #

Run doctor when setting up a new app or debugging discovery issues:

dart run ensemble_test_runner:ensemble_test --doctor

It checks the wrapper app, ensemble-config.yaml, definitions.local, test folder, YAML parsing, duplicate IDs, sessions, schema comments, and obvious widget id/testId references.

For generated tests, use fast validation without booting Flutter:

dart run ensemble_test_runner:ensemble_test --validate-only
dart run ensemble_test_runner:ensemble_test --validate-only --report=json

App inspection and scaffolding #

--inspect-app is a static EDL walk (no Flutter launch). It prints screens, widget IDs, APIs, and navigation targets from YAML definitions — useful when authoring tests offline:

dart run ensemble_test_runner:ensemble_test --inspect-app

Create a starter test under definitions.local.path/tests/:

dart run ensemble_test_runner:ensemble_test --scaffold-test=login_valid --feature=login --tag=smoke --screen=Login

See docs/TEST_AUTHORING.md for the test authoring workflow, mock file conventions, validation rules, and repair-loop output.

CI output #

For machine-readable results:

dart run ensemble_test_runner:ensemble_test --report=json
dart run ensemble_test_runner:ensemble_test --report-file=build/ensemble_test_results.json
dart run ensemble_test_runner:ensemble_test --report=junit --report-file=build/ensemble_test_results.xml

--report=json prints the final run result as JSON. --report=junit prints JUnit XML. --report-file writes the selected machine report to disk while keeping the normal console report.

Stable exit codes: 0 pass, 1 test failures, 2 setup/config/validation failures, 3 internal runner errors.

Run a subset:

dart run ensemble_test_runner:ensemble_test --id=login_valid
dart run ensemble_test_runner:ensemble_test --feature=login
dart run ensemble_test_runner:ensemble_test --profile=alternate
dart run ensemble_test_runner:ensemble_test --tag=smoke
dart run ensemble_test_runner:ensemble_test --path=auth/
dart run ensemble_test_runner:ensemble_test --device=android_nl

--profile selects expanded suite profile run(s) from tests/config.yaml (repeatable, or comma-separated).

--device selects suite device id(s) from tests/config.yaml (repeatable, or comma-separated). Default is all configured devices. In integration mode it filters locale/theme rows after the connected platform is applied.

Session producer tests are included automatically for selected session tests.

On success the console prints one consolidated boxed report for the suite: each test id (with YAML path), timing, start screen, optional session, navigation flow, and a numbered step outline.

Per-test sidecars under logs/ and parallel worker_* folders are written during the run, folded into the latest run's compressed report_data value in SQLite, then deleted. What remains:

  • report/index.html + report/ensemble_test.db
  • report/screenshots.zip (when screenshots are enabled)

The database also stores recent per-test durations used to balance the next run's worker shards. The report reads suite history and live run state from that same database.

When performance capture is enabled, those payloads are embedded per screen in the current report stored in ensemble_test.db under test_results.report_data / tests[].report.screens.

Examples #

Login flow #

# yaml-language-server: $schema=https://cdn.ensembleui.com/schemas/ensemble_tests_schema.json
id: login_flow
startScreen: Login
retry: 3
mocks:
  login:
    body:
      token: test-token
steps:
  - enterText:
      id: email_field
      value: user@test.com
  - enterText:
      id: password_field
      value: password
  - tap:
      id: login_button
  - expectApiCalled:
      name: login
  - expectVisible:
      id: dashboard_title

Storage/env setup #

Shared defaults belong in tests/config.yaml initialState. Per-test values override suite keys:

# tests/config.yaml
initialState:
  storage:
    apiUrl: http://ensemble.test/api/devices
  secureStorage:
    onboardingComplete: true
  keychain:
    authToken: test-token
  env:
    APP_LOCALE: nl

# *.test.yaml — only deltas
id: logged_in_home
startScreen: Home
initialState:
  storage:
    auth:
      token: test-token
steps:
  - expectVisible:
      id: welcome_text

Reusable authenticated session #

The session producer runs once. After it passes, the runner captures public storage, encrypted secure-storage values, keychain values, and locale in memory. Each consumer restores that snapshot, runs its setup, and mounts a fresh requested screen.

id: signin
startScreen: Login
steps:
  - tap: {id: login_button}
  - waitForNavigation: {screen: Home}
id: devices
session: signin
startScreen: Home
setup:
  - httpRequest:
      method: POST
      url: ${services.testService.url}/api/v1/stub/reset
steps:
  - tap: {id: devices_button}

Use session when tests need the same signed-in data but should otherwise start independently. Session snapshots are not written to disk.

Package layout #

lib/
  entry/          Flutter test entry (`runEnsembleTests`)
  cli/            `dart run ensemble_test_runner:ensemble_test` subprocess runner
  runner/         Runtime boot, orchestration, session state
  session/        TestExecutionSession (observe/act/wait/assert)
  actions/        Step execution
  assertions/     expect* handlers
  discovery/      Find and plan test definition files
  parser/         Documents → models
  reporters/      Console report formatting
  vocabulary/     Step registry + JSON Schema shapes
  models/         Shared data types
  mocks/          Mock HTTP provider + test logger
bin/ensemble_test.dart   CLI executable
tool/                    Schema/registry generators

TestExecutionSession (programmatic API) #

Test documents remain the primary authoring format. The same local adapter can also be driven without constructing TestStep objects:

final session = LocalTestExecutionSession.attach(
  tester: tester,
  harness: harness,
  context: context,
);
try {
  final obs = await session.observe();
  await session.act(TapAction(ElementTarget(testId: 'login_button')));
  await session.waitFor(ScreenWait(screen: 'Home'));
  await session.assertCondition(ScreenAssertion(screen: 'Home'));
} finally {
  await session.close(); // does not dispose suite-owned harness
}

SessionCapabilities describes what the adapter can provide; SessionPermissions describes what the caller may invoke. Standalone (format-independent) creation uses StandaloneTestSessionFactory inside a Flutter test binding and reuses EnsembleTestHarness.

Runtime hooks (in ensemble core) #

The runner uses small, optional hooks in the core module — not a package dependency:

  • Test harness applies EnsembleTestSetup (storage seeds, env overrides) before EnsembleApp mounts
  • Test harness installs MockAPIProvider on EnsembleConfig.apiProviders['http']
  • Navigation flow for expectVisited is recorded in the test runner via ScreenTracker.onScreenChange

EnsembleTestHarness runs storage init inside tester.runAsync() so GetStorage can finish under the widget test binding.

Internal runner benchmarks #

Use the standalone benchmark command to measure runner services with fixed fixtures:

dart run tool/benchmark_runner.dart --preset=quick
dart run tool/benchmark_runner.dart --preset=full --service=screenshot,observer

Normal test runs do not collect benchmark records. Results, SQLite history and the offline HTML trend report live in .ensemble_benchmarks/. CI uploads a report artifact retained for 30 days and comments its link on same-repository pull requests. See BENCHMARKING.md for architecture, coverage, measurement semantics, integration prerequisites, comparison/import commands and CI.

Source and executable size audit #

The redesign budgets can be measured without loading the runner package:

dart run tool/audit_size_budgets.dart \
  --aot=build/runner-redesign/current-runner --json

The report separates generated code, lists handwritten files over the 700-line limit, and records the optional AOT executable size. Keep its output with benchmark evidence when evaluating a size change; source-line counts and AOT bytes are separate measurements.