Skip to content

Latest commit

 

History

History
342 lines (286 loc) · 19.1 KB

tests.md

File metadata and controls

342 lines (286 loc) · 19.1 KB

moon test execution flow

This document summarizes what the current moon test implementation does. The behavior is based on crates/moon/src/run/runtest.rs, its private report module, crates/moon/src/run/runtime.rs, and crates/moon/src/cli/test.rs. Treat this as internal documentation: user-facing behavior can change.

Build + run pipeline

moon test includes ordinary tests, doc tests, and Markdown tests by default. Explicit --strip and --no-strip options take precedence over symbol defaults. Tests retain symbols in both debug and release builds by default, including function names and source locations for stack traces. Pass --strip to remove them.

An explicit .mbtx file path selects a standalone script before project discovery. It uses the script's imports and does not load the surrounding project. Exactly one path is accepted in this mode; package-wide testing does not discover scripts. Directories ending in .mbtx still select packages. Standalone tests accept --target all and comma-separated backends, composing their plans before any test runs. Without --target, the script's preferred backend supplies the default. The synthesized script package is always executable. Building, running, and testing it require a user fn main. Inline tests compile alongside the script; doctests remain blackbox tests and import its source compilation. Test targets use the generated test entrypoint and do not execute the script's main. Legacy standalone .mbt and .mbt.md tests retain their library package declaration and do not require a main. For file symlinks, these semantics follow the invoked filename, and the compiler and test runner also receive that filename rather than the target's filename.

Project tests, standalone-file tests, and benchmarks enter the same run_test_workflow after planning. It owns the initial build and dispatches the selected mode. Dry-run stops at the build graph. After the initial build, outline, build-only, and profiling each dispatch once to a dedicated handler for the whole invocation. Build-only emits one combined artifact listing across backends. Ordinary test and benchmark execution goes through run_tests_with_updates, which owns the execution, snapshot promotion, rebuild, and rerun loop, together with the final report. The target-directory lock is held from before planning through the initial build, including prebuild scripts and generated metadata. It is released before test execution or profiling. Outline and build-only read and print their generated metadata under the same lock. Test and benchmark execution and reporting do not block another moon check or build. All commands still share the target directory's n2 database; build execution remains serialized. Releasing the lock does not reserve the test artifacts against replacement by another build.

--outline plans only generated test metadata, using the same test-target selection as an ordinary test invocation. Required prebuild steps still run, and metadata generation may also emit test-driver source, but MoonBit and native compilation and executable linking are skipped. Outline collection reads the metadata directly and does not require executable artifacts.

  1. For test execution, the CLI resolves packages and test targets (via Rupes Recta build planning). Each selected BuildTarget produces two artifacts: the executable (make_executable) and a JSON metadata file (generate_test_info).
  2. When an invocation selects more than one Target Backend, each backend is planned and lowered independently, then their Execution Plans are composed into one n2 graph. The entire graph must build successfully before any test executable starts. This invocation-wide barrier prevents tests for an early backend from running when a later backend fails to build.
  3. run_tests (in runtest.rs) calls gather_tests, which pairs those artifacts and sorts them by executable path (to match legacy ordering). collect_test_invocations then turns each pair into a TestInvocation: it parses the metadata (MooncGenTestInfo) to know which files and indices exist, applies the CLI filter to build the TestArgs payload listing the ranges to execute, and drops binaries for which nothing is selected. The payload omits entries with no selected ranges, including empty metadata groups and files excluded by name, index, or skip filtering. Explicit index selections coalesce consecutive indices without changing execution order. Build-only output uses the same selection.
  4. Benchmarks are then isolated. When bench is true, isolate_invocations splits every invocation into one invocation per selected case, so no benchmark shares a process with another. Cases that share a process share a runtime that the earlier ones have already warmed, grown and specialized, which makes a reported time depend on how many cases ran before it — around 10% on wasm-gc. moon test keeps one invocation per test binary.
  5. Every invocation is launched through run_one_test_executable, which therefore starts a bench executable once per case. The runner:
    • Builds a backend-specific command (see below) and optionally prints it when --verbose is enabled.
    • Captures the test driver event stream between the MOON_TEST_DELIMITER_{BEGIN,END} markers. Coverage sections delimited by MOON_COVERAGE_DELIMITER_* are written to _build/moonbit_coverage_<timestamp>_<rand>.txt.
  6. The collected TestCaseResults are merged per build target inside ReplaceableTestResults, so the several invocations of an isolated benchmark run land in one entry. This structure keeps the latest result per (target, file, index) pair so later reruns can overwrite earlier data. The final report is rendered either as compact text (default) or JSON lines (when --test-failure-json is on).

Coverage runs moonrun <toolchain-root>/bin/moon_cove.wasm -- ..., using the reporter bundled with the selected toolchain.

Test execution parallelism

Within each Target Backend, moon test runs test executables in parallel by default, using the same available-CPU observation as build execution (falling back to one if unavailable). -j N sets the maximum number of concurrent executables. --no-parallelize forces sequential test execution even with -j, without changing build parallelism. The concurrency limit is at least one.

One current-thread Tokio runtime supervises the child processes; CPU parallelism comes from the children themselves. A launch loop awaits a semaphore permit before spawning each async task. The task holds the permit through child execution and result collection, then releases it so the next invocation can start. All tasks are joined before results are reported. The CLI retains this runtime across all backends and snapshot-update passes so the shutdown listener remains available until test execution ends. Finishing one child frees a concurrency slot without dropping the listener. The runner awaits and reaps children even when another invocation fails, and stops launching queued invocations after shutdown is observed.

Collected test results are reported in invocation order, regardless of completion order. Output printed directly by test programs may interleave. Selected Target Backends still execute one after another, and this scheduling does not split individual test cases into separate processes or change async-test concurrency.

The private runtest::report module owns per-test text and JSON output, including benchmark summary decoding and formatting. The runner owns test result data; its private expect module interprets expect/snapshot failures and applies source updates. Shared diff rendering for these reports and moon info lives in Moon's private diff module. BuildSession retains build-lock and rebuild ownership.

Moon's private test_metadata module owns the compiler-produced test-info JSON model shared by driver generation, filtering, and reporting. Rendering that metadata into MoonBit source belongs to cli::generate_test_driver, using the templates in crates/moon/template/test_driver_project. The template project is checked and format-checked by cargo xtask ci. RR plans the generation action and encodes its existing TargetKind as --driver-kind; it does not consume the test-info JSON model or driver templates.

moon bench remains sequential by default to avoid contention affecting measurements. Explicit -j N still opts benchmarks into parallel execution, and --no-parallelize overrides it.

Expect / snapshot promotion loop

TODO: this behavior is suboptimal. See:

moon test --update enables an iterative promotion workflow for expect tests and snapshot tests. The CLI enforces a single target backend in this mode (updating multiple backends at once would diverge binary outputs) and disallows patch files.

  1. After each run, the workflow opens a new BuildSession, acquiring the target-directory lock before promotion and holding it through any partial rebuild. perform_promotion scans that run's ReplaceableTestResults. For every ExpectTestFailed or SnapshotTestFailed case it:

    • Records the owning BuildTarget, file path, and index in a PackageFilter.
    • Batches the failure payloads and forwards them to apply_expect / apply_snapshot, which actually rewrite the .expect/snapshot files on disk.
  2. If the filter is empty, promotion stops immediately. Otherwise the runner:

    • Checks the --limit counter (default 256 passes) to avoid infinite loops.
    • Rebuilds just the affected test artifacts by cloning the saved build graph and calling BuildSession::rebuild with the output paths returned from the filter.
    • Releases the lock before re-running the filtered subset of tests, with the PackageFilter wrapped inside a temporary TestFilter. Only the promoted cases are executed, which keeps reruns fast even for large suites.
    • Merges the rerun results back into the main ReplaceableTestResults so the final summary reflects the updated outcomes.
  3. The loop repeats until either the filter is empty or the pass count hits --limit. The initial run counts as the first pass. Promotion happens before checking the limit, so the last pass can still modify files, but no rebuild or rerun follows. The final report retains the last observed results, including results for tests outside the rerun filter.

During promotion the helpers in Moon's private run::runtest::expect module are responsible for touching files while the caller holds the build session lock. The CLI does not stream diffs; failures are still rendered via render_expect_fail / render_snapshot_fail to provide context when --update is not active or when a promotion pass still fails.

Test driver event transport

The generated test driver reports per-test facts to moon as JSON event records inside the existing MOON_TEST_DELIMITER_{BEGIN,END} section. Each record is a test driver event, not necessarily a completed test result.

The transport payload is intentionally minimal:

----- BEGIN MOON TEST RESULT -----
{"type":"start","file":"exit_wasm_test.mbt","index":0}
----- END MOON TEST RESULT -----
----- BEGIN MOON TEST RESULT -----
{"type":"result","file":"exit_wasm_test.mbt","index":0,"message":""}
----- END MOON TEST RESULT -----
  • type identifies the event kind within the Moon test event stream. The initial event kinds are start and result.
  • file and index identify the selected test case. The runner uses generated metadata to recover package, display name, and source location when those are needed.
  • message exists only on result events and carries the same result payload used by expect, snapshot, panic, benchmark, and runtime-error handling.

The driver escapes file and message as JSON strings, including control characters such as ANSI escape codes. The escaper is embedded in the driver and uses only primitive string/buffer operations, without a core JSON dependency. MoonBit string-literal escaping is not valid JSON escaping.

The transport deliberately does not include package name, test display name, source location, backend, timestamp, duration, or tracing subscriber details. Those are either known by the runner, recoverable from metadata, or belong in Rust tracing rather than the driver-to-runner protocol.

During stdout draining, moon only reads lines, captures delimited protocol sections, and forwards all other stdout unchanged. The runner parses and interprets the captured event payloads only after the test executable exits.

Core dependencies

The shared driver must work inside moonbitlang/core/builtin and in core whitebox tests without importing prelude or json. Driver generation adapts every @moonbitlang/core/prelude. reference: it removes the prefix for builtin and replaces it with @moonbitlang/core/builtin. for other core packages. For ordinary packages the prefix stays unchanged and package resolution injects the prelude dependency.

Consequently, shared template operations such as println and StringBuilder must be available in builtin, even though the template qualifies them through prelude. Json::stringify is implemented in the separate json package and cannot be used unconditionally. Core blackbox tests receive an injected prelude import; that injection does not extend to whitebox or inline tests.

For async tests, lowering selects the runtime package passed to the private test-driver generator from the current test target's active imports for the selected backend. A package that imports moonbitlang/async (or is that package itself) keeps the legacy runtime; otherwise the generated driver uses moonbitlang/core/async.

Commands per backend (and how to specify test cases)

command_for (in runtime.rs) hides the differences between target backends. The same module owns TestArgs and its command-line encoding. All backends receive TestArgs::to_cli_args() selections in the form filename:start-end,start-end/..., for example math.mbt:0-5,7-9/io.mbt:2-3. Ranges are half-open, and their order and duplicates are preserved. Grouping ranges avoids repeating long filenames for sparse selections.

Names are compiler metadata basenames, not paths, so / cannot occur in a name. The final : separates each name from its ranges; earlier colons, commas, quotes, backslashes, whitespace, Unicode spelling and case are preserved exactly. Backslashes are literal characters on Unix, not escape or path separators. Moon passes the selection as one process argument, without shell interpolation. Generated MoonBit string literals escape these names separately from the wire format. This is an internal protocol between Moon and its test runtimes, with no filesystem lookup or name normalization. Encoding and range parsing are linear in the payload size. JavaScript and native drivers additionally expand ranges into individual test entries, as before. The existing execution interfaces and generated test maps remain unchanged.

Wasm and WasmGC

  • Runner: moonrun binary from the active toolchain.
  • Invocation: moonrun --test-args=<selection> [--policy <path>] <artifact>.wasm --.
  • Moonrun decodes the selection into filenames and index ranges before invoking the existing test-driver exports. Everything after -- is forwarded to the MoonBit program.
  • The runtime initializes test modules before invoking test exports and the test-driver finalizer. It prefers _initialize, falling back to _start when _initialize is absent. The selected export is called once, including when no test indices are selected. Modules without either export remain supported. Initialization failure stops the run before any tests or finalization; a failing _initialize does not fall back to _start.
  • moon test --wasm-policy <path> supplies the optional Moonrun Policy to each Wasm test executable. A relative path is resolved against the effective Moon invocation directory before test commands change to their module roots. Other Target Backends ignore it.

JavaScript

  • Execution command: node --enable-source-maps <artifact>.js '<selection>'.
  • The generated driver accepts the compact selection format. moon test --build-only --target js reports the same compact argument in test_filter_args. The outer artifact listing remains JSON; its strings must be decoded before passing the argument directly to the emitted artifact.
  • The build emits a package.json beside the artifact so Node does not inherit surrounding workspace module settings.

Native and LLVM

  • The compiled executable is run directly.
  • The generated driver accepts the common compact selection format. The previous /-separated filename:start-end format remains valid as its single-range case.

Narrowing which tests run

Filtering is handled by TestFilter (runtest/filter.rs). It stores allowed BuildTargets, then optional files, then optional index sets.

Package selection

  • moon test --package foo --package bar performs fuzzy matching against package fully qualified names. Each match becomes a BuildTarget for every applicable test kind (inline, whitebox, blackbox).
  • If multiple packages match, file- or index-level filters are rejected (the CLI surfaces an error) because the runner would not know which target to narrow down to.

File-level filtering

  • --file path/to/test.mbt narrows the selected packages to a specific file. It can only be used together with exactly one --package. Alternatively, supplying a positional PATH (e.g. moon test src/foo/test.mbt) activates the same logic—PATH is resolved, mapped to its owning package, and treated like --package PKG --file PATH.
  • Files with inline tests may map to multiple build targets (inline tests plus doc tests). TestFilter::add_autodetermine_target inspects the file type to decide whether to request inline, whitebox, or blackbox targets.

Individual test indices

  • --index N selects a single inline test (the index is taken from the generated metadata, displayed in failure output as #N).
  • --index A-B selects a left-inclusive right-exclusive range.
  • --doc-index N selects a single doc test block.
  • When a positional PATH points to a file, the indexes can be provided without an explicit --file. Otherwise, the CLI requires --file whenever --index or --doc-index is used, enforcing the “package → file → index” hierarchy.
  • Each selected index becomes a one-element range (N..N+1) inside TestArgs, which is why skipped tests can still be forced to run when explicitly targeted.

Benchmarks and skips

  • moon bench reuses the same filtering plumbing but passes bench = true, so only benchmark entries (with_bench_args_tests) are collected. It also changes the process model: every selected case is run in a process of its own (step 4 above) rather than one process per test binary.
  • --include-skipped keeps skipped cases in the computed ranges. Without it, skipped tests are excluded unless their indices are explicitly listed.

By understanding the stages above you can reason about how a specific CLI invocation translates to concrete commands and why certain combinations of flags are rejected.