← Validation Lab Bench 1 · Temperature monitor I2CUARTPython simulator
Clean run STR-TMP-002: ready

Stage 05 · Automation

One framework for every bench, built in nine steps. Each step fixes a real problem.

Pick a step to see the problem, the change and the code. The code is taken from the repository when this page is built.

Layers, top to bottom

  1. testspytest · IDs from the STD
  2. pluginpytest plugin and fixtures: --bench, --target, @tc, results.json
  3. coreBenchFactory and the Bench facade
  4. devicesdevice models: TempMonitor
  5. servicesvirtual clock, waits
  6. halProtocols: I2CBus, SerialPort, GpioPin, PowerControl
  7. targetsdrivers per target: sim, netns, vcan, board
  8. configbench.yaml, target overlays, pydantic
  9. baseerrors, registry, shared contracts

A layer imports only the layers below it. import-linter checks the order in CI.

simulator
bench 1
Linux netns
bench 2, later
SocketCAN vcan
bench 4, later
real board
same tests, later

plugin · reads @tc markers, writes results.json → STR, RTM and this site

Switching target is one option: --target sim or, later, --target board. The tests do not change.

Evolution

Step 1 / 9

HAL layer

Problem

Tests welded to the simulator would need a rewrite for a real board.

Change

I2C, UART, GPIO and power become Protocols. The simulator is one implementation.

framework/vlab/hal/i2c.py · I2CBus

class I2CBus(Protocol):
    """Register reads and writes on a 7-bit address.

    On bench 1 the target is the sensor (a sensor emulator in the lab): the
    bench writes the value the DUT reads. Registers auto-increment, so a read
    or write of n bytes covers registers reg to reg + n - 1.

    Raises DriverError when no target answers at `addr`, and ValueError for an
    address, register or length out of range.
    """

    def read(self, addr: int, reg: int, n: int) -> bytes: ...

    def write(self, addr: int, reg: int, data: bytes) -> None: ...
Step 2 / 9

A bench is built from YAML

Problem

Wiring devices by hand in every test file drifts and breaks quietly.

Change

BenchFactory builds the devices from bench.yaml in dependency order and opens their drivers in one ExitStack.

framework/vlab/core/factory.py · BenchFactory.build

def build(self, cfg: BenchConfig, stack: ExitStack) -> Bench:
    plan = self.plan(cfg)
    shared: dict[str, object] = {}
    devices: dict[str, Device] = {}
    with ExitStack() as opened:
        for dp in plan.devices:
            interfaces: dict[str, object] = {}
            for ip in dp.interfaces:
                ctx = OpenContext(
                    bench=cfg.bench,
                    device=dp.name,
                    role=ip.role,
                    clock=self.clock,
                    shared=shared,
                )
                interfaces[ip.role] = self._open(opened, dp, ip, ctx)
            devices[dp.name] = self._construct(dp, interfaces)
        stack.enter_context(opened.pop_all())
    return Bench(config=cfg, clock=self.clock, devices=devices)
Step 3 / 9

Time is a dependency

Problem

A 12 h soak in real time needs a lab machine or a 12 h job.

Change

The firmware model and every wait run on an injected virtual clock.

framework/vlab/services/clock.py · VirtualClock.step

def step(self, deadline_ms: int) -> None:
    """Run what is due now. If nothing is, move to the next event or the deadline."""
    if deadline_ms < self._now:
        raise ClockError(f"deadline {deadline_ms} ms is before now, {self._now} ms")
    if self._run_due():
        return
    nxt = self.next_event_ms()
    self._now = deadline_ms if nxt is None else min(nxt, deadline_ms)
    self._run_due()
Step 4 / 9

Device model

Problem

Tests full of register writes and sleeps say nothing about the requirement.

Change

Tests talk to TempMonitor only. Waits take their timeout from the spec.

framework/vlab/devices/temp_monitor.py · TempMonitor.wait_led

def wait_led(self, on: bool, *, within_ms: int | None = None) -> int:
    """Wait for the LED to be `on`, by default within the Q16 limit. Return the time seen."""
    limit = self.timeouts.led_ms if within_ms is None else within_ms
    state = "on" if on else "off"
    return wait_for(
        self._clock,
        lambda: self.now_ms() if self.led_on() is on else None,
        within_ms=limit,
        what=f"LED {state}",
        reason=f"Q16 assumed: the LED follows within {self.timeouts.led_ms} ms",
        log=self.waits,
        last_seen=lambda: f"LED {'on' if self.led_on() else 'off'}",
    )
Step 5 / 9

STD markers

Problem

Nothing links the code to the STD. Coverage is a guess.

Change

Every test carries its STD ID in a marker. The plugin checks the ID.

framework/vlab/plugin/markers.py · tc

def tc(case_id: str) -> pytest.MarkDecorator:
    """The STD case this test runs."""
    return pytest.mark.tc(check_tc(case_id))
Step 6 / 9

Points from data

Problem

Values typed by hand drift away from the documents.

Change

Points load from std.yaml, the same file this site shows.

framework/vlab/plugin/markers.py · each

def each(*names: str) -> pytest.MarkDecorator:
    """Run each value of the named point sets and test conditions of the card as its own test."""
    if not names or not all(isinstance(n, str) and n.strip() for n in names):
        raise ValueError(f"@each{names!r}: name at least one point set or test condition")
    if len(set(names)) != len(names):
        raise ValueError(f"@each{names!r}: a name repeats")
    return pytest.mark.each(*names)
Step 7 / 9

Fault injection API

Problem

Every fault needed its own hand-made setup.

Change

One call injects a fault on any target that supports it. A target without it raises a precondition error, so the test carries @requires.

framework/vlab/devices/temp_monitor.py · TempMonitor.inject_fault

def inject_fault(self, fault: Fault | str, *, count: int | None = None) -> None:
    """Make the sensor fail the next `count` reads by the DUT, or every read until cleared.

    A target that can't inject `fault` raises PreconditionError: the case
    should carry `@requires(fault)` and be skipped there (ADR-005).
    """
    name = str(fault)
    if self._faults is None or name not in self._faults.capabilities:
        raise PreconditionError(
            f"this target can't inject {name!r}, mark the test @requires({name!r}). "
            f"It can: {', '.join(sorted(self.capabilities))}"
        )
    faults = self._faults
    self._call("i2c", f"inject {name}", lambda: faults.inject(name, count=count))
    self._changed_ms = self.now_ms()
Step 8 / 9

Artifacts on failure

Problem

A red test without logs costs an hour of guessing.

Change

Every record that did not pass gets a text file: traceback, output and waits.

framework/vlab/plugin/pytest_plugin.py · Recorder._write_artifact

def _write_artifact(self, record: ResultRecord, text: str) -> ResultRecord:
    if record.outcome == "passed" or self.artifacts_dir is None:
        return record
    digest = hashlib.sha256(record.nodeid.encode()).hexdigest()[:8]
    stem = re.sub(r"[^A-Za-z0-9_.-]+", "_", record.nodeid)[-80:].strip("_.")
    name = f"{stem}-{digest}.txt"
    waits = [
        f"{w.device}: {w.what} ({w.reason}), within {w.within_ms} ms, "
        f"{w.start_ms} to {w.end_ms} ms, {'met' if w.met else 'not met'}"
        + (f", last seen: {w.last}" if w.last else "")
        for w in record.waits
    ]
    head = [
        f"nodeid: {record.nodeid}",
        f"tc: {record.tc}",
        f"outcome: {record.outcome} ({record.phase})",
    ]
    body = "\n".join(head) + "\n\n" + text + "\n\n== waits ==\n" + "\n".join(waits) + "\n"
    _write(self.artifacts_dir / name, self.scrub.text(body))
    return record.model_copy(update={"artifact": name})
Step 9 / 9

One command

Problem

Long soak tests made every run slow and burned CI minutes.

Change

The virtual clock makes the soak fast, so nox -s ci runs everything CI runs, with one command.

noxfile.py · ci

@nox.session(python=False)
def ci(session: nox.Session) -> None:
    """Static checks, spec lint, tests, report and security checks."""
    started = time.monotonic()  # history.json keeps the wall time up to the report
    session.run("uv", "sync", "--locked", external=True)

    # 1. Static checks
    uv_run(session, "ruff", "check", ".")
    uv_run(session, "ruff", "format", "--check", ".")
    uv_run(session, "mypy")
    uv_run(session, "lint-imports")
    uv_run(session, "python", "-m", "tools.check_dashes")

    # 2. Spec lint
    uv_run(session, "python", "-m", "tools.check_spec")

    # 3. Framework unit and contract tests
    uv_run(session, "pytest", "framework_tests")

    # 4. Bench suites on the simulator: one clean run, then one run per seeded bug (T12).
    bench_seconds: list[str] = []
    for tests in sorted(Path("benches").glob("*/tests")):
        bench = tests.parent.name
        bench_started = time.monotonic()
        results = RESULTS_DIR / bench
        shutil.rmtree(results, ignore_errors=True)  # no stale results from an earlier run
    ...

Key decisions · ADR register 001 to 032

framework has its own unit testscontract tests on every HAL drivermypy --strictruffimport-linter
ADRDecisionStatus
ADR-001Tests talk only to device modelsAccepted
ADR-002Session bench, reset per testAccepted
ADR-003A bench is built, not wiredAccepted
ADR-004Dependency injection into devicesAccepted
ADR-005Spec timeouts and declared capabilitiesAccepted
ADR-006Protocols plus contract testsAccepted
ADR-007Registry, open for extensionAccepted
ADR-008The bench is dataAccepted
ADR-009Time is a dependencyAccepted
ADR-010No blind retriesAccepted
ADR-011Test points in YAMLAccepted
ADR-012Package layout framework/vlabAccepted
ADR-013Simulated firmware as a discrete-event modelAccepted
ADR-014A shared base below the layersAccepted
ADR-015Sim firmware by name, seeded bugs in the power settingsAccepted
ADR-016The TempMonitor device modelAccepted
ADR-017Waits on Clock.step, a spec timeout is a FAILAccepted
ADR-018Sim wiring checked when the bench is builtAccepted
ADR-019Verdicts and results.jsonAccepted
ADR-020Per-run overrides through load_benchAccepted
ADR-021STD cases reach the tests through the pluginAccepted
ADR-022Bench 1 test conventionsAccepted
ADR-023The break-it gate and break_it.jsonAccepted
ADR-024Report data filesAccepted
ADR-025STR IDs and numberingAccepted
ADR-026Defect drafts and EC-3 before triageAccepted
ADR-027history.jsonAccepted
ADR-028Site build and URL layoutAccepted
ADR-029The data is in the page, JS only shows and hides itAccepted
ADR-030Self-hosted variable fonts, latin subsetAccepted
ADR-031check_live.py, the live-site check after a deployAccepted
ADR-032Mail for the domain is received by the owner's mail serviceAccepted
Next: run, debug and report →