mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

Testing with and of mjdi

This page covers both directions: how mjdi's own quality gates work (the

Source: mjdi/docs/testing.md

This page covers both directions: how mjdi's own quality gates work (the test suite, compile-fail fixtures, coverage methodology) and how to test applications built on mjdi. Everything here runs on Mojo 1.2.0, where mojo test does not exist — the suite is a set of standalone programs driven by a shell script.

The mjdi test suite

bash scripts/run_tests.sh          # or: bash scripts/run_tests.sh /path/to/mojo

The runner exits non-zero on any failure and prints one line per check. The counts are never quoted by hand: tests/INVENTORY.md (the authoritative inventory, generated by scripts/test_inventory.py — P0-07) derives every figure from the runner itself and is the single quotable source; CI fails when the report is stale or a document quotes an unreconciled total. The 0.10.0 inventory reports 114/114 suite checks on mojo 1.2.0 (2016d0cd), composed of:

LayerCountWhat it proves
Unit tests (tests/test_*.mojo)52Runtime behavior: resolution, every provider kind, the third-party use_* family, scopes, aliases, values, custom construction, nested graphs, the scanner, lifecycle hooks (counted pre_destruct markers), graph export / DOT / explain-resolution, the override family, runtime validation and the value inventory, lifecycle tracing, cache statistics, the lexical guards (including error-path cleanup), the re-entrancy guard, the construction-ordering contract, the linear-resources and testing-patterns example suites, and the v0.10.0 capability suites (keyed and qualified registrations, multi-bindings, optional dependencies, provider decorators, assisted injection, registry bundles, factory dependency metadata, named/child scopes, and the runtime-error contract for unresolved optional/multi/assisted dependencies). Each program ends with print("PASS ..."), which the runner greps for.
Compile-fail fixtures (tests/compile_fail/cf_*.mojo)33Structural rejections: each file must fail to compile, and the compiler output must contain the expected diagnostic fragment — including the v0.8.0 guarantees (override of an unregistered service, re-registration after an override, explain of an unregistered service, the double destruction of a linear value) and the v0.10.0 guarantees (duplicate keyed registrations, resolving a qualified dependency with no keyed registration, assisted resolution outside an assisted factory, factory dependencies on unregistered services, non-copyable multi-binding products, bundle collisions).
Crash-expected fixtures (tests/crash_expected/*.mojo)4Runtime misuses (unresolved value() read, scoped class provider resolved from the container, scoped factory product resolved from the container, and an Assisted field read before the assisted factory populated it) abort with the exact diagnostic.
Strengthening checks2The MJDI-A001 abort diagnostic carries its stable ID in the output, and the golden debug-diagnostics pair (MJDI-D001 + MJDI-D002) prints both destructor diagnostics.
End-to-end example (examples/e2e_example.mojo)1The full walkthrough; output checked against [info] User-42.
Golden-output example runs17Every example application (including linear_resources, testing_patterns, keyed_providers, plugin_pipeline, assisted_reports, and scope_hierarchy) is executed and its printed output matched exactly.
Composition-root templates4The four starter templates run self-testing (PASS templates/<name>).
Python checks1python3 -m unittest discover tests/python — the graph-diff utility, the diagnostic catalog (including the shared-ID variant convention and retired IDs), the generated API reference, and the release metadata (54 tests).

Compile-fail tests

The harness (from scripts/run_tests.sh) compiles each fixture expecting failure and asserts the message:

out=$(mojo build -I . tests/compile_fail/cf_missing_provider.mojo -o /tmp/mjdi_cf_out 2>&1)
# PASS requires: non-zero exit AND output matching "no provider is registered"

This is the strongest guarantee in the suite: not just "it fails" but "it fails for the documented reason". The fixtures and their fragments are cataloged in Compile-time validation.

Crash-expected tests

Two misuses are runtime by nature and abort with a diagnostic:

  • crash_unresolved_inject.mojo — reads value() on a never-populated marker ("was never resolved").
  • crash_scoped_from_container.mojo — resolves a scoped provider from the container ("can only be resolved through a Scope").

The runner executes each and requires a non-zero exit and the diagnostic text in the output.

Golden-output verification

Every example's main() prints a deterministic report. The runner executes each examples/<name>/app.mojo and greps for the expected golden string, so any change in mjdi that alters observable behavior fails loudly. The goldens are listed in the Examples guide.

Testing applications built on mjdi

Pattern: one registry per test, built at comptime

Because registries are values and containers are cheap to construct, the natural test pattern is: each test scenario declares its own comptime registry, sets its values, resolves, and asserts. This is exactly what tests/test_scopes.mojo does — three registries in one main(), one per lifetime scenario:

from std.testing import assert_equal

def main() raises:
    comptime reg = (
        Registry()
        .register_value[Config]()
        .register[DbService, provider_scope.singleton]()
    )
    var app = Container[type_of(reg)]()
    app.set_value[Config](Config("db://one"))
    var first = app.resolve[DbService]()
    app.set_value[Config](Config("db://changed"))
    assert_equal(app.resolve[DbService]().url(), "db://one",
                 "singleton was constructed only once")
    print("PASS")

Pattern: derive the test registry by override (P1-08 / P1-09)

The highest-leverage test setup is registry composition: build the production registry once, then derive per-test registries with the override family — a pre-built double through override_value, a replacement factory through override_factory, or lifetime surgery through override. No production registration code is duplicated, and consumers keep compiling unchanged:

comptime production = (
    Registry().register_value[Env]().register[Gateway, provider_scope.singleton]().register[Client]()
)
comptime with_double = (
    Registry().register_value[Env]().register[Gateway, provider_scope.singleton]()
        .override_value[Gateway]()      # the test double replaces the provider
        .register[Client]()
)

var test = Container[type_of(with_double)]()
test.set_value[Env](Env("ignored"))
test.set_value[Gateway](fake_gateway("test"))
assert_equal(test.resolve[Client]().fetch(), "GET https://test", "the double wins")

examples/testing_patterns is the runnable, tested catalog of every pattern in this section.

The mjdi.testing helpers

The assertion family that keeps these tests tight (all generic over the container/scope specialization):

from mjdi import (
    assert_missing_values,       # pins the missing-value report exactly
    assert_value_inventory,      # pins the value-provider inventory
    assert_validate_runtime,     # pins the startup-validation verdict
    assert_resolve_fails_with,   # expects a specific mjdi runtime diagnostic
    assert_trace_count,          # pins the lifecycle-trace event count
    assert_trace_last,           # pins the last recorded trace event
    assert_stats_line,           # pins cache-statistics fragments ("hits=2")
)

Scope companions (assert_trace_count_scope, assert_trace_last_scope, assert_stats_line_scope) mirror the trace/stat assertions for scopes.

Testing lifetimes with statistics, not counters

With collect_stats=True, lifetime behavior becomes one assertion — assert_stats_line(app, "insertions=0") proves a transient override never caches; "constructions=3" proves transient reconstruction; the singleton hit/miss counts prove canonical-construction semantics. See Cache statistics.

Testing construction and cleanup ordering

With traced=True, the deterministic event stream is the ordering proof: tests/test_construction_order.mojo pins depth-first construction, dependency-completion order, cache initialization order, and reverse-registration release order against trace_event(i) — see Construction ordering.

Testing scope isolation

with_scope is the scope-isolation helper: the body resolves inside a scope that closes on both exit paths, so leakage is impossible by construction — see Scope guard.

Useful testing idioms, all verified in the suite:

  • Make construction observable. A transient service that captures a value-provider value at construction turns "was it constructed once or twice?" into an assertion about the value it holds — no counters or mocks needed (see tests/test_scopes.mojo).
  • Test the error paths. Missing value → resolve and expect the runtime error; factory failure → register a raising factory and assert the propagation (tests/test_factories.mojo).
  • Test compile-time guarantees with the compile-fail harness above — a project-specific compile_fail/ directory costs twenty lines of shell.
  • Assert introspection — type_of(reg).provides[T]() / scope_of[T]() / kind_of[T]() let tests pin down registration shape without resolving anything (used by tests/test_aliases.mojo).

What to test, per layer

LayerTest it with
Service logicOrdinary unit tests — construct inputs directly; no container needed.
Wiring correctnessOne resolve of the root service; assert end-to-end output (the golden-output pattern).
Lifetime semanticsValue-provider snapshotting per lifetime (the singleton/scoped/transient trio in test_scopes.mojo).
MisconfigurationCompile-fail fixtures per guarantee you rely on.

Documentation quality gate (P2-15)

scripts/verify_docs.py (CI: the tests job's documentation step) keeps the documentation from rotting. It is reproducible and offline:

  • Explicit block tags. Every fenced block carries a tag from a documented convention — nothing is auto-classified as executable:
    • mojo — a complete, compilable program; the gate runs mojo build -I . on it, so standalone examples cannot silently break.
    • mojo snippet — a partial fragment of a larger narrative (context elided); never compiled.
    • mojo pseudocode — illustrative; may not be valid Mojo.
    • text — illustrative output such as compiler diagnostics.
    • sh / bash — shell transcripts; never executed.
  • Internal links. Every relative markdown link and #anchor resolves (GitHub-style heading slugs, the same algorithm the website renderer uses).
  • Versioned pages. Every archived documentation version named by release/manifest.json has its snapshot under website/content/docs/.
  • Stale API references. Identifiers used in Mojo blocks are checked against the declarations in mjdi/*.mojo; an unknown register_* / resolve[ / graph_* style identifier fails the gate.

Every failure prints path:line: message, so CI output is directly actionable.

Coverage methodology

Mojo 1.2.0 has no coverage instrumentation, so mjdi measures coverage statically, the same way for the library and the examples:

  • scripts/coverage_report.py walks every public declaration in the library's modules and checks it is referenced from the executable artifacts (unit tests, compile-fail fixtures, crash-expected fixtures, the end-to-end example). Current: 814/814 declarations (100%).
  • scripts/example_coverage.py does the same for every def/struct in each examples/*/app.mojo, checking references from that example's dedicated test file. Constructors are counted implicitly (every object the tests build runs __init__), and each example's main() is verified by the runner's golden-output execution instead. Current: 166/166 declarations (100%).

These gates measure API-surface coverage — that every declaration is referenced from executed code. They are not behavioral/branch coverage: Mojo 1.2.0 has no coverage instrumentation, mjdi reports no line/branch percentage anywhere, and the distinction is part of the inventory's coverage definitions (P0-07).

Both scripts print a per-module table and enforce the 95% gate:

python3 scripts/coverage_report.py
python3 scripts/example_coverage.py

Honest limits of the method, stated plainly:

  • It is declaration coverage (every API surface exercised somewhere), not branch or line coverage. A declaration being referenced does not prove every branch inside it executed.
  • The mapping is static; it cannot see dynamically dead branches that never run. That residual risk is covered the honest way — dedicated fixtures for the branches that matter (the compile-fail and crash-expected files exist precisely because of this).
  • Constructor coverage is inferred, not traced.

The acceptance criteria treat the 95% gate as satisfied by this methodology (Acceptance criteria → Test coverage); if your project needs branch-level numbers, wait for compiler instrumentation and keep the static gate as the faster first line.

Writing tests for a new mjdi feature

The suite's own layout is the template:

  1. Unit test tests/test_<feature>.mojo — scenarios as registry/value triples, assert_equal throughout, print("PASS test_<feature>") last.
  2. If the feature has a guaranteed compile-time rejection, add tests/compile_fail/cf_<feature>.mojo and register the expected fragment in the CF_CASES table of scripts/run_tests.sh.
  3. If it has a guaranteed runtime abort, add to crash_expected/ and the CRASH_CASES table.
  4. Run bash scripts/run_tests.sh and both coverage scripts; the coverage gate will tell you if any new declaration is unreferenced.