# Test without hardware

# Test without hardware

A unit test runs the same compiled program the device runs, with the hardware
replaced: inputs follow a script, output writes are recorded, and the clock
runs as fast as the computer allows. A 60-second sequence tests in
milliseconds, with the same result on every machine.

```python
def vessel():
    estop_ok.hold_at(True)
    if fill == "open":
        pressure.rise_to(50 * bar, over=10 * s)
    elif vent == "open":
        pressure.fall_to(0 * bar, over=5 * s)
    else:
        pressure.hold_at(50 * bar)

simulation(vessel)

def overpressure():
    simulate(estop_ok, True)
    simulate(pressure, rising(from_=50 * bar, to=60 * bar, over=2 * s))
    should_shut_down(within=100 * ms)
    should_be(vent, "open")

def good_unit():
    run_sequence("proof", answers={"bolt torque": 24 * N * m,
                                   "Vessel sealed and area clear": True,
                                   "welds": True},
                 identity="SN-0142")
    should_pass()

unit_test("overpressure shuts the system down", overpressure)
unit_test("a good unit passes", good_unit)
```

## Simulation

`simulation(fn)` says how inputs move, using an `if` on outputs' states. Each
motion is written as a method on the input, and starts when its branch is
chosen, from where the input is:

| Motion | Does |
|---|---|
| `rise_to(v, over=)`, `fall_to(v, over=)` | a straight line to `v` |
| `hold_at(v)` | a fixed value |
| `profile([(t, v), …], repeat=)` | straight lines through points, each `t` from when the branch was chosen; `repeat=True` runs it again and again |
| `oscillate(mean=, amplitude=, period=)` | a sine wave |
| `stay(start=)` | stays wherever it is — a peak-hold or a counter keeps what it reached; `start=` is its value before it has one |
| `follow(x, lag=)` | trails another input, or a number output's command, through a lag |
| `responds_to(output, gain=, lag=, delay=)` | answers a number output's command times `gain=` (`5 * psi / percent`), through a lag after a dead time: a plant to close a [drive](https://phloem.ai/docs/trellis/sequences/)'s loop on |
| `noise(sd=, seed=)` | noise on top of whatever it does |

`after=1 * s` on `rise_to`, `fall_to`, `hold_at`, `profile` or `oscillate`
holds the input where it is that long first. Unit tests use the simulation by
default, and so does Computer's **Simulation** switch. On real hardware it is
ignored.

## Scripting inputs

`simulate(input, source)` overrides an input from that line on:

| Source | Gives |
|---|---|
| `20 * degC`, `True` | a constant |
| `rising(from_=, to=, over=)`, `falling(…)` | a ramp |
| `jump(before, after, at=)` | a step |
| `wave(mean=, amplitude=, period=)`, `noisy(base, sd=)` | a wave, or noise |
| `breaks_at(t)` | non-finite values from `t` |
| `goes_silent_at(t)` | no samples from `t` |

Every input needs a source before time moves — the simulation or a
`simulate` line — or the test fails naming the ones without. A silent input
would otherwise shut the system down and pass a shutdown test for the wrong
reason.

## Assertions

| Word | Passes when |
|---|---|
| `should_shut_down(within=40 * ms)` | a shutdown latches within the window, counted from the moment its trigger first held |
| `should_not_shut_down(for_=)` | none does, once every scripted input has settled — or for `for_=` from now |
| `should_be(output, value)` | the output was commanded to that value |
| `should_alert(name)` | the alert fired |
| `should_not_alert(name, for_=)` | it has not fired, and does not until the inputs settle and any run ends — or for `for_=` |
| `should_reach(step, within=)` | the run reached the step in time |
| `should_pass()`, `should_fail()` | the run ended that way |
| `should_not_look()` | the run ended **incomplete**: every check that did not pass was not measured |
| `should_be_pending()` | the run ended **passed, pending**: every check passed but one written `if_fails="pending"` |

`run_sequence(name, …)` runs a sequence as a person would start and answer it:

| Argument | Gives |
|---|---|
| `answers={…}` | each gate's answer by its name: a reading in a unit, text, a choice or a date as a string, yes/no as `True`/`False`, counted readings as a list, an inspection as `True` or `False` |
| `settings={…}` | settings by name; the rest take their defaults |
| `identity="SN-0142"` or `{"serial number": "SN-0142", "board_rev": "C"}` | the identity, one part or several |
| `fields={"part": {"value": "PSU-1", "max current": "4.5"}}` | run fields: a field's own value, and its row's cells by column |
| `skip=["leak check"]` | optional steps a person skips |
| `scripts={"self_test.py": {"exit_code": 0, "stdout": "current: 48.2 mA", "after": 5 * s}}` | what each script does: its exit code, what it prints, how long it takes, or `"timed_out": True`. A script not described could not start |

A test's runs start on 2026-01-01, so a check against `today()` judges the same
on every machine.

**A pipeline's Mark in a test.** A check between a saved pipeline's Marks is
proved with `pipeline_mark("chilled", at=12 * s)` — the Mark fires 12 s after
the line — or `pipeline_mark("soak", at=2 * s, until=30 * s)` for a span. Only a
Mark the project's pipelines end in is accepted; the file's own marks fire from
the simulated inputs.

**Parameters by unrolling** — a `for` over fixed values gives each case its own
named test:

```python
def stays_up_at(level):
    simulate(estop_ok, True)
    simulate(pressure, level)
    should_not_shut_down()

for level in (40 * bar, 50 * bar):
    unit_test(f"stays up at {level}", stays_up_at, args=(level,))
```

## A recorded run as a test

`replay("SN-0139")` feeds every input the run recorded, each sample at its
recorded time, gaps included. It answers "would this system have done the right
thing on that run?":

```python
def recorded_overpressure():
    replay("SN-0139")
    should_shut_down(within=100 * ms)
    should_alert("pressure over")

unit_test("SN-0139 shut down in time", recorded_overpressure)
```

A run the device does not have makes the test **could not run** — neither
passed nor failed. Outputs are not replayed: the test reads what this system
would have commanded.

## Running tests

In **Code**, tests run on every compile; each `unit_test` shows ✓ or ✗ in the
gutter and **Problems and tests** lists failures with the line. From a terminal
or CI, with no device:

```bash
phloem trellis test                       # every .phl in this folder
phloem trellis test proof_test.phl        # one file
phloem trellis test --only overpressure   # tests whose name contains this
phloem trellis test --junit report.xml    # also write JUnit XML
```

- [Deploy and review](https://phloem.ai/docs/trellis/deploy/): The review reports how the tests did
- [Alerts and shutdown](https://phloem.ai/docs/trellis/alerts/): What a shutdown test proves
