# Testing

How Mote is tested, how to test a program's back end (`test` blocks, `mote
test`) and its page (`test "…" page`, in a browser), and how Mote's own pages are tested: `tests/all.sh`, the expectations,
`tests/real.mjs` and how a driver is written, the compiler's unit tests,
`docs/check.sh`. Back to the [map](README.md).

## Mental model

There are five layers, from quickest to slowest:

| Layer | Checks | Run |
|---|---|---|
| `mote check` | A program compiles. | `mote check app.mote` |
| [`mote test`](#tests-in-the-program) | A program's back end does what its own `test` blocks say: rules, hooks, `server fn`s, jobs, schedules. A [`test "…" page`](#a-test-of-the-page) drives the program's page in a browser too. | `mote test app.mote` |
| Unit tests | The compiler's output for small sources; the batteries against known answers. | `cd compiler && cargo test` |
| `docs/check.sh` | Every whole program in the docs compiles. | `docs/check.sh` |
| Browser tests | A built page, driven in a headless Chrome, prints what it should. | `tests/all.sh <names>` |

A browser test is **a page, a driver, and an expectation**:

1. the page is a Mote program (`tests/<name>/app.mote`, or an example);
2. the driver is a small script that clicks, types and reads the page, and
   returns lines of text saying what it saw;
3. the expectation is a text file, `tests/expect/<name>.txt`.

The test passes when the lines printed are exactly the expectation. There
are no assertions in a driver: it describes what happened, in sentences, and
the diff against the expectation is the failure message. This makes a
test's expectation readable as a record of intended behaviour, which is why
the docs point at these files.

## Tests in the program

A program's own back end (its rules, its hooks, its `server fn`s, its jobs,
its schedules) is tested by `test` blocks written in the program, and run by
`mote test`:

```mote
// docs: whole
model Person
  id: id = me
  name: string
  muted: bool = false
  read anyone
  add if me != none

model Message
  text: string
  by: id = me
  at: time = now
  read if me != none
  add if me != none

// What no page may read.
model Sent
  to: string
  at: time = now

server before Message.add(m)
  let who = Person.get(m.by)?
  if who?.muted == true fail("you are muted here")?

job fn welcome(who: id) retries=2
  let said = net.send("POST", "https://mail.example/send", {body: {to: who}})?
  if said.status != 200 fail(`the mail service said ${said.status}`)?
  Sent.add({to: who})?

server after Person.add(p)
  welcome(p.id)

server fn join(name: string): Person requires signedIn
  return Person.add({name})?

server fn mute(who: id): number
  Person.set(who, {muted: true})?
  return 1

// Each night, messages a month old go.
server at "03:00"
  Message.del({at: before(now() - 30 * 86400000)})?

test "a muted person cannot post"
  given net "https://mail.example/*" answers {status: 200}
  as "ada@example.com"
  let ada = join("Ada")?
  expect Message.add({text: "hello"}).text == "hello"
  mute(ada.id)?
  expect Message.add({text: "again"}) fails "you are muted here"
  expect Message.count({}) == 1
  as none
  expect join("Nobody") fails kind "signin"

test "a welcome is queued, sent, and tried again if the mail service is down"
  given net "https://mail.example/*" answers {status: 503}
  clock "2026-03-01T09:00"
  as "bob@example.com"
  join("Bob")?
  expect queued(welcome).length == 1
  run jobs
  expect sent(net).length == 1 && sent(net)[0].url.startsWith("https://mail.")
  expect queued(welcome)[0].words == "the mail service said 503"
  given net "https://mail.example/*" answers {status: 200}
  clock +1 second
  run jobs
  expect queued(welcome).length == 0
  trusted
    expect Sent.count({}) == 1

test "old messages go in the night"
  given net "https://mail.example/*" answers {status: 200}
  clock "2026-03-01T23:42"
  as "cy@example.com"
  join("Cy")?
  Message.add({text: "late"})?
  clock +29 days
  expect Message.count({}) == 1
  clock +2 days
  as "cy@example.com"
  expect Message.count({}) == 0

text "A shop"
```

```text
$ mote test app.mote
ok      a muted person cannot post
ok      a welcome is queued, sent, and tried again if the mail service is down
ok      old messages go in the night
3 tests: all ok
```

- **`test "what is so"`** + a block, at the top level of any file of the
  program. `mote test app.mote` runs each; `mote test app.mote muted` runs
  those whose name has every word given; `--json` prints `{tests: [{name,
  at, ok, line, source, words, left, right, ms}], passed, failed}` instead.
  It ends with status 1 if any failed. It needs Bun, and nothing else.
- **Every build checks them, and only `mote test` contains them.** `mote
  check`, `build` and `dev` say what is wrong in a test as in any code; what
  they write has no test in it, and no fn that only a test calls.
- **Each test has a back end of its own that has just started**: its own
  models' database (in memory, at this build's schema, its `migrate` blocks
  run), its own accounts, its own data folder (gone after), its `server
  start` blocks run. Nothing a test does is there for the next. The back end
  listens to nothing, unless the test is [of the page](#a-test-of-the-page).

**Who, and through what.**

- **`as "ada@example.com"`**: the lines that follow are run as that person,
  signed in (the first time an address is named, an account is made for
  it). **`as none`**: as nobody. Before either, nobody is signed in.
- **A line of a test asks as a page would.** A call of a `server fn` goes
  through what a page's call goes through: its `requires`, its arguments
  checked against their types, what a model hides left out of its answer.
  An operation of a model (`Message.add({…})`) goes through the model's
  rules, as whoever the test is being: an operation with no rule is `no
  such call`, as a page would be told. That is what a test is mostly for:
  what a person may and may not do.
- **What stands at a call's door stands at a test's.** A `requires` that
  names a [rule](back-end.md#rules) is asked (`expect sweep(c.id) fails kind
  "refused"`; signed out, `kind "signin"`), and a
  [`limit`](back-end.md#limits) counts the test's calls: its bucket fills by
  the test's clock, so `clock +1 minute` is a minute's worth of calls again.
  What a test does not have is a request: no origin is asked of, and no call
  is [answered once](back-end.md#a-call-is-answered-once) under an id.
- **A [`secret`](back-end.md#secrets) that is not set** where the test runs
  is `test secret <KEY>`: a test's back end starts with nothing set, and
  what was sent with the secret can be looked at (`sent(net)[0].headers`).
  One that is set in the environment is itself.
- **`given env "KEY" is "value"`**: a setting the test's back end starts
  with, for that test alone ([below](#settings-for-one-test)); `given secret
  "PAY_KEY" is "sk-test"` is the same for a secret, in place of `test secret
  PAY_KEY`.
- **[Acting as someone](back-end.md#acting-as-someone)** works as it does
  for a page: after a call of a fn that says `auth.as(…)`, the test's lines
  are that person's (`auth.actor()` is who the test was), a write while
  only looking `fails kind "refused"`, and `auth.asEnd()` is the way back.
- **`trusted`** + a block: its lines are the back end's own code, past the
  rules, as in a `server fn`. For arranging rows a page could not write,
  and for looking at what a page cannot read. (A fn the test calls is the
  back end's own code too: only the lines written in the test go through
  the door.)

#### Settings for one test

What `env("KEY")`, `secret("KEY")` and a rule's `setting("KEY")` read, said
for one test:

```mote
// docs: whole
rule staff = me.email in setting.list("SHOP_STAFF")

model Note
  text: string
  read if staff
  add if staff

fn keepDays(): number = Number(env("KEEP_DAYS")) || 90

server fn days(): number requires staff
  return keepDays()

test "staff are who the setting says"
  given env "SHOP_STAFF" is "ada@shop.test"
  as "ada@shop.test"
  Note.add({text: "hello"})?
  expect days() == 90
  as "bo@shop.test"
  expect Note.add({text: "no"}) fails
  expect days() fails kind "refused"

test "the setting is read for each test, and so is how long things are kept"
  given env "SHOP_STAFF" is "bo@shop.test"
  given env "KEEP_DAYS" is "30"
  as "bo@shop.test"
  expect days() == 30

text "Notes"
```

- **The whole test's.** The test's back end starts with them, before its
  `server start` blocks and its first line, wherever in the test they are
  written; after it, each setting is again what it was (unset, or what the
  environment says). So the same file tests a program with a setting and
  without it, in one `mote test`, with no environment to set around it.
- **Written out**, the name and the value, and among the test's own lines,
  not inside a block (`H167`): they are read before anything runs.
- **A rule's `setting`** is read as each test's back end starts, as it is
  read as a real one starts ([a rule that reads a
  setting](back-end.md#a-rule-that-reads-a-setting)).
- `given secret "KEY" is "…"` says a secret's value: it is still shown as
  `[secret]` in the log, and still kept out of what leaves the back end.

**What is expected.**

- **`expect a == b`** (`!=`, `<`, `<=`, `>`, `>=`), or `expect` anything
  that is a yes or no. A call that can fail needs no `?` inside it: if it
  fails, the test does. When it does not hold, both sides are shown.
- **`expect call fails`**: the call is to fail, as a program says no (`fail`,
  a rule, a check, `requires`). `fails "you are muted here"`: with these
  words. `fails kind "signin"`: of this
  [kind](back-end.md#when-something-fails) (`"signin"`, `"invalid"`,
  `"said"`, `"taken"`, the program's own, or `"fault"`). Something that broke is not
  what `fails` alone expects.
- **A line that fails with `?` fails the test**, and is told with its line.

```text
FAILED  a muted person cannot post
        app.mote:52: expect Message.count({}) == 1
        it does not hold
        left:  2
        right: 1
```

**The clock.** On the back end everything that asks the time asks one
clock: `now()`, `Date.now()`, a field's `= now`, `time.…`, when a job is
due, how long a session lasts, a lease, when a `server every` or `server
at` block is next. In a test:

- **`clock "2026-03-01T09:00"`** sets it (UTC; `clock "2026-03-01T09:00"
  "Europe/Paris"` for a zone's own clock). From then on it stands still: it
  moves when the test moves it. Nothing runs for the time jumped over.
- **`clock +30 minutes`** moves it on (`ms`, `second`, `minute`, `hour`,
  `day`, `week`, with or without an `s`), and each `server every` and
  `server at` block that falls due on the way is run at its own moment, in
  order. One that fails, fails the test.
- Unset, it is the machine's clock. No timer runs in a test: a `server
  every` or `server at` block runs only when the test moves the clock past
  its moment.
- With [usage](usage.md) on, what was gathered is handed to the `server on
  usage` blocks whenever the test moves its clock (`clock +1 second`),
  first, as of the moment the clock still reads.

**Jobs.** A `job fn` queued in a test waits: no worker runs by itself.

- **`run jobs`** runs every job that is due now, one after another, until
  none is (a job one of them queues too). A job that fails is tried again
  when its wait has passed: move the clock (1 s, then 4 s, 16 s, … exactly,
  in a test), and `run jobs` again.
- **`queued(welcome)`** is the jobs of that name that are waiting, each
  `{id, name, args, state, due, tries, words, kind, at}`; `queued()` is
  every job that is.

**What would leave the process does not.**

| | In a test |
|---|---|
| `net.…`, a call to [another back end](back-end.md#another-back-end), a push | Answered by the last **`given net "https://mail.example/*" answers {status, json, text, headers}`** whose address fits (`*` stands for anything). A request nothing was said of fails the test (`this test made a request to …: say what it answers`), whatever the program made of the failure. **`sent(net)`** lists them: `{method, url, headers, body, text}` (`body`: the JSON sent, else the text). |
| `notify.send` | Kept in the person's inbox as ever; pushed nowhere. **`sent(notify)`**: `{to, title, body, url, data}`. |
| `emit`, `emitTo` | No page is open to hear. **`sent(emit)`**: `{name, value, to}` (`to`: none for `emit`). |
| `proc.run` | Answered by **`given proc "git *" answers {code, out, err}`** (matched against the command's words with spaces between); one nothing was said of fails the test. **`sent(proc)`**: `{cmd}`. `proc.start` is refused. |
| `net.lookup(host, kind)` | Answered by **`given dns "example.com TXT" answers {records: […]}`** (matched against the name, a space, and the kind), each record as the kind gives it (a TXT record may be a list of its strings); `{kind: "offline"}` makes it fail. One nothing was said of fails the test. **`sent(dns)`**: `{name, kind}`. |
| `fs`, a model's files | A data folder of the test's own, removed after. |
| `sql.open("name")` | A database in memory, the test's own. |

### A test of the page

`test "what is so" page`: the test has a browser, at the program's page,
served by the test's own back end. `page` is that browser. Its lines and the
back end's stand in the one test, so a test presses a button and then asks
the database what became of it:

```mote
// docs: whole
app "Notes" routes=paths

model Note
  text: string
  by: id = me
  read if me != none
  add if me != none

live notes: Note[] = Note.find({}) else []
state draft = ""
state gone = false

action add()
  Note.add({text: draft})?
  draft = ""

action later()
  time.sleep(5000)
  gone = true

input value=draft placeholder="New note"
button "Add" press={add()}
button "Later" press={later()}
if gone
  text "It went"
for n in notes key=n.id
  text n.text

test "a note is added by the page, and is on the back end" page
  as "ada@example.com"
  page.type("New note", "Milk")
  page.press("Add")
  expect page.has("Milk")
  expect Note.count({}) == 1

test "a note added behind the page comes to it" page
  as "bo@example.com"
  page.open("/")
  Note.add({text: "From behind"})?
  page.see("From behind")

test "five seconds, at once" page
  page.press("Later")
  expect !page.has("It went")
  clock +5 seconds
  expect page.has("It went")
```

- **No waits.** Each call finds its thing as
  [`mote`](agents.md#mote-the-page-without-a-picture) does (its `data-mote`
  name, the words on it, its number, or `{name, text, nth, within}`), sends
  real input (the mouse, fingers and keys a person's browser would), and
  comes back when the page is at rest: no request out, no timer about to
  ring, nothing moving. A call to the back end, a live value arriving and a
  move to another page are waited for with nothing said.
- **`as "ada@example.com"`** signs the browser in as well as the test's own
  lines (an open page is loaded again, as that person); `as none` signs it
  out. A test that begins by pressing something is at `/`: `page.open` is
  for another path.
- **One clock.** From the first `clock +…` the page's timers are the
  test's: `clock +5 seconds` moves the back end's clock and the page's
  together, each timer due on the way ringing in its turn. (`clock
  "2026-03-01T09:00"` sets the back end's alone.)
- **What fails it**: a thing that is not on the page, words never seen, a
  page that does not come to rest; each is told in a sentence, with what
  the page does say. And anything the page said was wrong (an error thrown,
  `console.error`) that the test did not read with `page.errors()`.
- **What it needs**: Bun, and a Chrome, Chromium or Edge on the machine
  (`$CHROME` says where, if not in a usual place). One browser is started
  for the run, when the first such test asks; each test has a tab with
  cookies of its own, and a back end at a free port. `MOTE_TEST_SHOW=1`
  shows the window.

| Call | Does, and gives |
|---|---|
| `page.open(path)`, `page.go(path)`, `page.reload()`, `page.back()` | Loads a path whole; moves to a page of the app; again; back. |
| `page.press(t)`, `page.tap(t)`, `page.hover(t)` | The mouse; a finger; the mouse over it. Each call that does something gives what changed on the page, as text. |
| `page.type(t, text, {add, enter})`, `page.key("mod+k", t?)` | Real typing, in place of what the field holds; a key or a chord. |
| `page.check(t, on)`, `page.pick(t, option)` | A checkbox or switch set; an option chosen. |
| `page.hold(t, ms)`, `page.swipe(t, way)`, `page.drag(t, onto)`, `page.pinch(t, scale)`, `page.scroll(t, to)` | Fingers, and a list moved. |
| `page.see(words)` | Waits until the page says them (five seconds), and gives the line. |
| `page.has(words)`, `page.read()`, `page.changed()` | Whether the page says them now; the page as text; what changed since it was last read. |
| `page.path()`, `page.title()` | Where the page is (path, query and hash); its title. |
| `page.size(w, h, {touch})`, `page.scheme("dark")`, `page.shot("page.png")` | The screen (a phone: `390, 844, {touch: true}`); the colours; a picture, written to that file. |
| `page.errors()` | What the page said was wrong, and takes it: what is left at the end fails the test. |
| `page.eval(js)` | Anything else, in the page. |

`page` in a test that does not say `page` is `H336`. The driver under it is
the one [`mote drive`](agents.md#driving-a-mote-page) writes out, for a
script of one's own. Run whole by `tests/all.sh real_page_tests`
(`tests/page_tests/`).

**What `mote test` does not do.**

- **A page in a plain test.** In a test that does not say `page`, nothing
  is drawn and no action, state or component is run.
- A fn the page calls too can be called from a test, and is then run as the
  back end runs it: `time` with no zone is UTC's there, not a reader's.
- `live` values are not kept for anyone: there is no open line. What a page
  would be sent is what its read answers when the test asks.
- `net.send` with `public: true` looks the host up for real before asking;
  `proc.start`, calls (`rtc`), and stopping (`server stop`) are not stood
  in for.
- A test's back end is one process alone: what several back ends do at one
  database is tested with real ones (`tests/all.sh real_jobs`).

Run whole, with a test for each line above, by `tests/all.sh real_mote_test`
(`tests/mote_test/`: `app.mote` passes, `failing.mote` shows each kind of
failure, `bad.mote` what `mote check` refuses in a test).

Source: `runtime/server/test.mote` (the harness), `runtime/shared/clock.mote`
(the clock), `compiler/src/parse/c3.rs`, `emit/c3.rs`, `types/c3.rs`.

## tests/all.sh

```text
tests/all.sh                      every test, one after another (about 50 minutes)
tests/all.sh -j 8                 every test, eight at a time (about 12 minutes)
tests/all.sh real_el counter      only those named
tests/all.sh --affected main      only those a change since `main` touches
tests/all.sh --accept real_kit    rewrite that test's expectation from what it prints now
TIMES=t.txt tests/all.sh …        and append `name seconds status` to t.txt for each
```

**Run only what a change affects.** A change to one example or one part of
the runtime needs only the tests that use it.

It prints one line per test, with how long it took: `ok     real_el   1.4 s`,
or `FAILED real_el   1.4 s` followed by a diff of expected against got, or
`skip   real_vid   port 4877 held by pid 56488 (mote, cwd …)` (below); then,
for more than one, how many ran, failed and were skipped, and the time in
all. Its exit code is 1 if any failed; a skip is not a failure, unless
`STRICT_PORTS=1`.

Two kinds of name:

- **`real_<name>`**: a shell function in `all.sh` that builds a page, serves
  it if it needs serving, and runs `node tests/real.mjs` on it with
  `tests/<name>.real.mjs`. Expectation: `tests/expect/real_<name>.txt`.
- **A plain name** (`counter`, `todo`, `notes`, `pages`, `kitchen`): the
  older kind. `tests/browser.sh` builds `tests/pages/<name>/app.mote`,
  appends `tests/<name>.drive.html` (a script that drives the page with
  synthetic events) and prints what it wrote. Expectation:
  `tests/expect/<name>.txt`.

What a `real_` function looks like:

```sh
# Element handles: `ref=`, `el.…`, `resized`.
real_el() {
  "$mote" build "$here/el/app.mote" --out "$here/out/el" --single >/dev/null
  node "$here/real.mjs" "$here/out/el/index.html" "$here/el.real.mjs"
}
```

and for a page that needs HTTP, or a back end:

```sh
real_search() {
  "$mote" build "$here/search/app.mote" --out "$here/out/search" >/dev/null
  (cd "$here/out/search" && exec bun server/main.js --port 4917 >/dev/null 2>&1) &
  pid=$!
  ready "$pid" 4917
  node "$here/real.mjs" http://localhost:4917/ "$here/search.real.mjs"
  kill $pid 2>/dev/null
  wait $pid 2>/dev/null
}
```

`ready <pid> <port>` waits until the back end answers `/readyz` (it is up
and its data is open), and `listening <pid> <port>` until it listens on the
port (`mote serve`, a stand-in). Both also wait until what listens there is
`<pid>` or a process it began, so another program on the port is never
taken for it (with `""` for the pid, anything listening will do). Both give
up when the process has stopped, or after 20 seconds, and then say who holds
the port if another program does. Use them, not a fixed `sleep`, which is
too long on a quiet machine and too short on a busy one.

**A port another program holds.** Before a test starts, every port it surely
uses (`node tests/entries.mjs sure <name>`: those its shell function, its
drivers and its program name, not the numbers that only keep two tests
apart) is looked at: a TCP listener on 127.0.0.1, ::1 or every address, or
a UDP socket bound to it. If one is held by a program that is not this run's
(a `mote dev` of another project, a back end left from a run that was cut
short), the test is not run, since its driver would drive that program and
fail in ways that say nothing of Mote: it prints
`skip   real_vid   port 4877 held by pid 56488 (mote, cwd /Users/…)` and is
counted apart. Nothing is stopped: free the port (or choose to) and run it
again. A process still going away is given three seconds first.
`STRICT_PORTS=1` makes a skip fail the run, for a machine where nothing else
should be running.

Each test has its own ports and its own folders under `tests/out/`. One run
of a name happens at a time in a checkout (`tests/out/.locks/<name>`), and
one run on a port at a time on the machine, whatever checkout or `TMPDIR` it
runs from (`/tmp/mote-test-ports/<port>`). A lock is a folder holding the
pid of the run that took it; one whose run is gone is taken over. A run
that waits for one says so on its standard error.

### Which compiler

`MOTE_BIN`, as it is, when it is set. Otherwise
`compiler/target/release/mote` when nothing it was built from is newer
(`compiler/target/release/mote.d` lists those: the compiler's sources, the
runtime, the batteries, the kit, the icons): then no `cargo` runs at all.
When it is not up to date, a run of more than ten tests builds it with
`cargo build --release` (about a minute after a change; then each program
builds two to four times faster than with the debug compiler), and a run of
ten or fewer builds and uses `compiler/target/debug/mote`, quicker to make.
`MOTE_PROFILE=release` or `debug` chooses instead. `tests/browser.sh` and the
drivers that build use the same one (`MOTE_BIN` is set for them).

### Running several at once: -j

`-j N` runs N tests at once (`tests/parallel.mjs`), each as
`tests/all.sh --one <name>` with its own locks. What each prints is shown
whole, in the same order as without `-j`, as soon as those before it are
done; the exit code is the same. Two tests never run together when they
share:

- **a port**, or a **folder under `tests/out/`**: `node tests/entries.mjs`
  reads both off `all.sh`, the drivers and the test programs (`show <name>`
  for one test, `check` for every pair that may not overlap). The reading
  errs one way: a number that only looks like a port keeps two tests apart.
  While they run, what each one's processes listen on is looked at every
  second, and a port it was not given is said at the end (and kept in
  `tests/out/.ports-seen`): add it where `entries.mjs` will find it.
- **a thing of the machine** (a named group, locked like a port, across
  checkouts too): `clipboard`, a driver that grants the clipboard and reads
  it back with `navigator.clipboard` (`real_desk`, `real_kitall`,
  `real_pg_site`, `real_policy_kit`); `full-chrome`, a test that runs a full
  Chrome for a camera or notifications (`real_scan`, `real_notify`,
  `real_fulltext_server`, `real_rtc_ring_push`, `real_sw_push`). A copy or
  paste made with a `ClipboardEvent` and a `DataTransfer` of the driver's
  own (`real_richtext`, Slick's) touches no clipboard and is in no group.
- And some run **alone**, last, with nothing beside them (`ALONE` in
  `tests/entries.mjs`): `real_bigfiles` and `real_mail_lib`, which write
  gigabytes and watch a tab's memory, and `real_perf`, which measures time.

The longest go first, by how long each took last time (`tests/out/.times`).
The floor is the longest test: `real_policy_kit` and `real_kitall` take
over four minutes each, `real_pg_playground` and `real_policy_playground`
nearly three. On a machine with many cores `-j 8` is a good start; more than the cores, or
other work on the machine, and tests that count on time (an animation, a
debounce, a timeout) can fail: such a test waits for the state it means, or
goes in `ALONE` with its reason. (`MOTE_TEST_RUNNER=<script>` runs another
script in `all.sh`'s place, given `--one <name>`: a stand-in that sleeps and
prints is how the scheduling itself is tried.)

### --affected

`tests/all.sh --affected <git-ref>` runs the tests that the changes since
`<ref>` (committed or not, and new files) touch, and says how many first.
`node tests/entries.mjs affected <ref> --why` lists them with the reason. It
is coarse, and when unsure it takes more:

- a file a test names (its program, its driver and what that imports, the
  example or extension it builds, its expectation): that test;
- `tests/all.sh`: the tests whose function the change is in (a comment just
  above a function is that function's), those that call a helper that
  changed, and every test for a change to the runner itself;
- a part of the runtime (`runtime/page/x.mote`, `runtime/server/x.mote`) or
  a battery (`batteries/x/`): the tests whose name or program says `x`, and
  those that build an example; every test for the parts every program goes
  through (`core`, `dom`, `serve`, `model`, …: `CORE_RUNTIME`);
- the kit: the tests whose program says `kit`;
- a compiler file: every test, but for the few in `COMPILER_PARTS`
  (`lsp.rs`, `openapi.rs`, `policy.rs`, …);
- docs, the CHANGELOG, the compiler's own unit tests: none (`cargo test` and
  `docs/check.sh` are theirs);
- anything else: every test.

### The big ones

`real_bigfiles` writes a zip of about 3 GB (`BIGFILES_GB`) and wants 8 GB
free; `real_mail_lib` an mbox of 5 GB (`MAIL_LIB_GB`; 1 GB when the disk has
less than 12 GB free). Both are deleted when the run ends. The default is the
full size. `MOTE_TEST_SIZE=quick` makes the mbox 1 GB, which prints the same;
the zip stays 3 GB, as what it checks is a message that lies past 2^31 bytes.

Environment:

| Variable | Meaning |
|---|---|
| `MOTE_BIN` | The compiler to use, as it is. Without it, see [Which compiler](#which-compiler). |
| `MOTE_PROFILE` | `release` or `debug`: which compiler of the tree to build and use, when `MOTE_BIN` is not set. |
| `TIMES` | A file to append `name seconds status` to, a line a test (`status`: ok, FAILED, wrote, skip). |
| `STRICT_PORTS` | `1`: a test skipped because another program holds its port fails the run. |
| `MOTE_TEST_SIZE` | `quick` for the smaller mbox of `real_mail_lib`; `full` (the default) otherwise. |
| `BIGFILES_GB`, `MAIL_LIB_GB` | The sizes of `real_bigfiles`'s zip (3) and `real_mail_lib`'s mbox (5). |
| `MOTE_RUNTIME` | A runtime folder for that compiler to read instead of the one built into it: test a runtime change without rebuilding the compiler. |
| `CHROME` | The browser binary. Default: a Playwright `chrome-headless-shell` found under `~/Library/Caches/ms-playwright`. |
| `CHROME_FLAGS` | More flags for one test, space-separated (a pretend camera, a software GPU). |
| `GPU` | Set to leave the GPU on (WebGL tests). |

What the tests need on the machine: Node, a Chromium (see `CHROME`), and
Bun for the tests with a back end. Two entries need the network once:
`real_crypto` and `real_crypto_vectors` first run `tests/crypto/fetch.sh`,
which fetches the published vectors of `crypto`'s standards (NIST's ACVP,
C2SP's CCTV, BLAKE2's, the Keccak team's, the Argon2 reference's; some 11 MB)
at pinned commits, checks each file's SHA-256, and keeps them in
`tests/crypto/vectors/`, which git ignores. Offline, with nothing fetched,
those two say why and fail; `cargo test` runs without them, and its five
tests that read them say on one line each that they did not run
(`tests/crypto/README.md`).

## Driving a page with no waits

A test of a page of your own is a [`test "…" page`](#a-test-of-the-page)
in the program; or, where a script suits better (several tabs, Puppeteer
beside it), one on the driver ([agents.md](agents.md#driving-a-mote-page),
`mote drive --out mote-drive.mjs`): it names things as the page does, sends
real input, and each call comes back when the page is at rest, so there is
no time to guess. Timers are the page's clock, held and advanced:

```js
import { launch } from "./mote-drive.mjs";
const app = await launch("http://localhost:4870");
await app.clock.hold();
await app.type("draft", "Milk", { enter: true });   // however long the back end takes
await app.see("Milk");
await app.press("undo");
await app.clock.advance(5000);                      // "the note goes after five seconds", at once
console.log(await app.read());                      // the page as text: diff it against a file
await app.close();
```

`tests/agent.drive.mjs` is such a script, and `tests/expect/real_agent.txt`
what it prints. The older drivers below (`tests/real.mjs` and the `*.real.mjs`
files) came first and still sleep in places; a new test is better written
this way.

## tests/real.mjs

```sh
node tests/real.mjs <page.html or http URL> <steps.mjs>
```

Drives a built page with real input: trusted clicks and key presses sent
over the Chrome DevTools Protocol, which dispatch as a person's do. It
starts a headless Chrome, opens the page at 900 by 600, runs the driver,
prints the lines the driver returns, then any errors the page threw or
logged, and exits.

The driver module default-exports `async (page) => string[]`. `page` has:

| | |
|---|---|
| `page.eval(js)` | Runs JavaScript in the page and gives its value (promises are awaited). Throws if the script throws. |
| `page.click(selector)` | A real click at the middle of the first match. |
| `page.type(text)` | Key presses, one per character, into whatever has focus. |
| `page.key(name)` | One key pressed (nothing is typed: `page.type` types), sent as a keyboard sends it (its name, code and number), so the browser acts on it: `"Enter"`, `"Escape"` (closes a `dialog` or a popover), `"ArrowLeft"`, `"Home"`, `"End"`, `"Delete"`, `"PageUp"`, `"F2"`, `"a"`. With keys held, joined by `+`: `"Shift+ArrowLeft"`, `"Mod+k"`, `"Control+Shift+End"`, `"Alt+ArrowDown"` (`Alt`, `Control`, `Meta`, `Shift`; `Mod` is ⌘ on a Mac and Control elsewhere, as `keys.mod`). A name it does not know throws. |
| `page.touch([…])` | Real fingers on the page (the browser taps, scrolls and takes a touch away as it would a person's), all at once; it returns when they are done. A finger is a record: `{at: "#id"}` is a tap (`at` is a selector, its middle, or `[x, y]`; `from: [dx, dy]` beside it moves the place). `by: [dx, dy]` draws it along, in `ms` (150 unsaid) and `steps` moves (10); a list of them is one leg after another. `hold: 200` rests that long before lifting, `after: 80` comes down that much later. `end: "cancel"` is the system taking every touch away, `end: "stay"` leaves the finger down until a later `page.touch([])`. A swipe is `page.touch([{at: "#card", by: [-120, 0]}])`, two fingers `page.touch([{at: [100, 80], by: [-40, 0]}, {at: [200, 80], by: [40, 0]}])`. |
| `page.reload()` | Reloads the page. |
| `page.size(width, height)` | Sets the window's size. |
| `page.shot(path)` | Saves a PNG of the page. |
| `page.sleep(ms)` | Waits. |
| `page.setFiles("#pick", [paths])` | Presses what opens a file chooser (a selector, or a function that does it) and chooses those files in it (a folder's path, for a folder). `[]` dismisses it as Cancel does; `null` leaves it unanswered, as a camera that was dismissed and said nothing. Gives `{mode, accept, capture}`, or `null` if no chooser opened. |
| `page.another(url)` | Opens a second page with cookies of its own (another person's browser) and gives its `page`. What it logs is printed with the rest. |
| `page.send(method, params)` | Any other DevTools Protocol command (a mouse move, a wheel, a modifier key). |
| `page.events`, `page.errors` | What the protocol reported so far. |

After the driver returns, every uncaught exception adds a line
`page error: …` and every `console.error` a line `console.error: …`. So a
page that logs an error fails its test without the driver saying anything.

### Violations of a policy

With `VIOLATIONS=1` in its environment, `tests/real.mjs` also gathers what
the page's Content-Security-Policy refused: every `securitypolicyviolation`
event of each page it opened, and what the browser's own log says of one
(which has a worker's too). After the driver's lines it prints a line
`refused by the policy: <directive> <what>` for each distinct one, and
`refused by the policy: N in all`. A run of a page built with
[`policy=strict`](delivery.md#the-strict-policy) is to end `0 in all`.

| Run | What it holds |
|---|---|
| `real_policy` | A page under the policy (`tests/policy`): what it sends, what stays open (its own script and styles, a worker, a battery, a listed origin), what is refused (another origin, a script, a `style=`, a `<style>`, text run as code), from a host that sends the headers and from one that sends none. |
| `real_policy_kit` | The kit's page and its eight galleries (`examples/kit`), built with the policy: each says what `real_kit` and `real_kitall` record, and nothing is refused. |
| `real_policy_playground` | The playground with its back end, built with the policy: what `real_pg_playground` records, and what is refused, each with its cause. |
| `real_policy_ahead`, `real_policy_share` | A page the back end draws, and one it sends at a route's own path, under the policy. |
| `real_update_ask` | [`update=ask`](delivery.md#updates-that-ask): a build kept until the page agrees, a build that is not what its list names, a worker of other bytes, the server gone. |
| `real_build_same` | [The same build twice](delivery.md#the-same-build-every-time): two folders, two times, two users, homes, locales and time zones; and `mote build --check`. |

## tests/slowproxy.mjs

```sh
node tests/slowproxy.mjs <port to listen on> <port of the back end>
```

A bad network, for a run that needs one: it stands between the page and its
back end, and passes everything on as it is (calls, files, the page itself,
the open line's WebSocket) until the driver tells it otherwise. The page is
opened at the proxy's port. It is told at its own address, which is never
passed on, with a JSON body holding any of:

| | |
|---|---|
| `up`, `down` | ms added to everything on its way to the back end, and back: a call's round trip grows by `up + down`, and so does a message on the open line each way. |
| `cut` | `true`: the line is dead. Every request's connection closes with no answer, the open lines close, and none opens. `false`: back. |
| `hold` | `true`: what the open line carries is kept, both ways, until `false` (to let a call's answer arrive before the row's message, or after it). |
| `rules` | `[{match, times, …}]`: for a request whose path holds `match`, `times` times (1 unless said), one of `lose: "answer"` (the back end is asked and answers, and the answer is thrown away: the connection closes), `lose: "request"` (the connection closes; the back end is never asked), `status: 503` (answered so by the proxy, with `headers` if given), `wait: ms` (held that much longer on the way in), `late: ms` (its answer held that much longer on the way back). |
| `clear` | `true`: forget the rules, and what was seen. |

```js
const proxy = (said) => fetch(process.env.A2_PROXY + "/__proxy", { method: "POST", body: JSON.stringify(said) }).then((r) => r.json());
await proxy({ up: 300, down: 300 });
await proxy({ rules: [{ match: "Note.add", lose: "answer" }] });
const seen = (await proxy({})).seen; // [{path, call, did}…]
```

What it answers is what it is set to and `seen`: one entry a request,
`{path, call, did}`: the id the page sent (`x-mote-call`) and what became
of it (`"waiting"`, then `"passed"`, `"lost answer"`, `"lost request"`,
`"status 503"`, `"cut"`). So a driver can say "the page sent the same id
twice, and the second was answered". It uses `node:http` and `node:net`
and nothing else. Run it with Node: under Bun the open line's bytes are not
passed on.

`a2_run` in `tests/all.sh` starts a program's back end with the proxy in
front (`A2_PROXY`, `A2_BACK`: the two addresses, for the driver). The
page's own waits can be shortened by a driver, for a run that would
otherwise spend seconds waiting: `self.__motecall = {pauses: [80, 160],
timeout: 150}` (between a call's tries; how long a call may take) and
`self.__motewrites = {again: 200, most: 3, age: 500}` (before kept writes
are tried again; how many are kept, and for how long). The runs that use
it: `real_instant_writes`, `real_refused_writes`, `real_answered_once`,
`real_offline_writes`.

## Writing a test

The page (`tests/hello/app.mote`):

```mote
// docs: whole
state n = 0
state name = ""

action add
  n += 1

column gap=8 padding=16
  input value=name id="name"
  button "Add" press=add
  text `${name} pressed ${n} times` id="say"
```

The driver (`tests/hello.real.mjs`):

```js
// What tests/hello/app.mote does when it is used.
export default async (page) => {
  const out = [];
  const say = () => page.eval(`document.querySelector('#say').textContent`);
  out.push("at first: " + (await say()));
  await page.click('[data-mote="add"]');
  await page.click('[data-mote="add"]');
  out.push("after two presses: " + (await say()));
  await page.click('[data-mote="name"]');
  await page.type("Ada");
  out.push("after typing a name: " + (await say()));
  return out;
};
```

Then:

1. Add a function to `tests/all.sh` (copy `real_el`), and add its name to
   the list in the `for drive in …` line near the end.
2. `tests/all.sh --accept real_hello` writes `tests/expect/real_hello.txt`.
3. **Read the expectation.** It is now the record of what the page does;
   accept it only if every line is what should happen.
4. `tests/all.sh real_hello` from then on.

To try a driver without `all.sh`:

```sh
mote build tests/hello/app.mote --out /tmp/hello --single
node tests/real.mjs /tmp/hello/index.html tests/hello.real.mjs
```

Conventions that keep tests steady:

- **Select by `data-mote` or `id`**, not by text or position. Every control
  already has a `data-mote` ([agents.md](agents.md#data-mote)).
- **Each line says what was done and what was seen**, as a sentence:
  `"sent to the top (el.scrollTo): scrolled to 0 of 64"`.
- **Wait for the page, not for the clock**, where you can. `click`, `type`
  and `key` already wait 30 ms, which covers a state change (effects run in
  a microtask). For something that waits (a worker, the network), poll with
  `page.eval` until it is there, with a limit.
- **Keep what varies out of the output**: times, dates, sizes that depend
  on the machine. Print "under 50 ms: true", not the number.
- Use `--single` and a `file://` page when nothing needs HTTP; a service
  worker, `net`, `fs`, `sql`, the camera and a back end need a server.

## The compiler's unit tests

`compiler/src/tests.rs` compiles small sources and looks at the result:

```rust
#[test]
fn text_is_escaped() {
    let h = ok("text \"a < b & c\"\n");
    assert!(h.contains("a &lt; b &amp; c"), "{h}");
}
```

`ok(src)` gives the built HTML (and panics with the diagnostics if it does
not compile); `ids(src)` gives the ids of the errors a source raises, for
testing a refusal. The batteries' cores (`batteries/*/core.rs`) are tested
there too, against known answers. `cd compiler && cargo test`.

## docs/check.sh

Every fenced `mote` block in `docs/*.md` (and the top `README.md`) whose
first line is `// docs: whole` is a whole program. `docs/check.sh` extracts
them and runs `mote check` on each:

```text
docs/check.sh              all pages
docs/check.sh language     one page
docs/check.sh --keep       leave the programs in $TMPDIR/mote-docs to look at
```

It prints `FAILED docs/<page>.md:<line>` with the compiler's message for
each one that does not pass, and exits 1. Blocks without the marker are
fragments and are not checked. When you add an example that can stand
alone, mark it.

## Pitfalls

- **Do not accept an expectation you have not read.** `--accept` writes
  whatever was printed, wrong or right.
- **A full run is slow and uses fixed ports.** Name the tests you need, or
  `--affected <ref>`; for many, `-j`.
- **`all.sh` may build the compiler** unless `MOTE_BIN` is set. When others
  share the binary, set `MOTE_BIN` to the one you mean to test.
- **A new test's ports** must be where `tests/entries.mjs` reads them
  (`--port N`, `localhost:N`, `taken N`, `X_PORT=N`, a stand-in's first
  number), or in the comment above its function ("ports 6100 to 6109"):
  `node tests/entries.mjs show real_x` says what it found, and `-j` says what
  it saw that it was not told of.
- **A synthetic event is not a real one.** `element.click()` in `page.eval`
  runs listeners with no microtasks between them, and has no pointer
  position. Use `page.click` for what a person does.
- **`localStorage` survives a reload** within one run; each run starts with
  a fresh browser profile.
- **A test that needs a GPU** sets `GPU=1` and the SwiftShader flags (see
  `real_surface` in `all.sh`).
- **The newest `toast` may not be on the page yet.** Three notes show at
  most and the rest wait their turn ([language.md](language.md#built-in)),
  and a driver makes notes faster than a person does: the last child of
  `[role=status]` is then an older note, and the one just made arrives up
  to a second later. Wait until fewer than three are up, then read the last
  (a note on its way out carries `data-leaving`):
  `document.querySelectorAll('[role=status] > :not([data-leaving])')`.

## In the source

| What | Where |
|---|---|
| The runner | `tests/all.sh`; `-j`: `tests/parallel.mjs`; what each test uses (ports, folders, files, groups) and `--affected`: `tests/entries.mjs` |
| The browser driver | `tests/real.mjs` |
| The older harness | `tests/browser.sh`, `tests/*.drive.html` |
| Drivers | `tests/*.real.mjs` (`tests/el.real.mjs` is a short one) |
| Pages under test | `tests/<name>/app.mote`, `tests/pages/<name>/app.mote`, `examples/` |
| Models: local (`real_models`), on the back end (`real_models_server`) | `tests/models/`, `tests/models_server/` and their drivers; the driver builds each next schema itself |
| Apps that share their accounts, a password reset written in Mote (`real_accounts`) | `tests/accounts/` (two programs), `tests/accounts.real.mjs`: three back ends on 5730 to 5732, one accounts folder |
| Continue with Google against a pretend provider (`real_google_signin`, `real_google_hostile`) | `tests/google_fakeidp.mjs` (the provider), `tests/google_client.mjs` (a browser as far as cookies and redirects go), `tests/google_signin/`, the two drivers; the extension's own tests are `extensions/google/tests.mote` |
| The kit's Carousel and Drawer, by finger, mouse and keys, on a phone and turned on its side (`real_carousel`, `real_drawer`) | `tests/carousel/`, `tests/drawer/` and their drivers |
| Drags that end, and swipes, by finger and by mouse (`real_drags`, `real_swipe`) | `tests/drags/`, `tests/swipe/` and their drivers; `compiler/src/tests_touch.rs` |
| Expectations | `tests/expect/*.txt` |
| Fixtures (pictures, MP4s, codes) and how they were made | `tests/fixtures/` |
| Unit tests | `compiler/src/tests.rs` |
| A test of the page | `runtime/server/test.mote` (`TPG`, the listener begun and a tab asked for each test), `tools/drive/mote-drive.mjs`, `compiler/src/main.rs` (`test`: the page built beside the harness); run by `tests/all.sh real_page_tests` |
| A program's own tests: the harness, the clock | `runtime/server/test.mote`, `runtime/shared/clock.mote`; run by `tests/all.sh real_mote_test` (`tests/mote_test/`) and, on a copy of Slick, `real_test_slick` (`tests/test_slick/tests.mote`) |
| The docs' check | `docs/check.sh` |
