> Documentation version: main. [HTML page](https://lukewilliamboswell.github.io/roc-native-windows/spec-runner.html)

<a id="test-and-record-win32-apps"></a>

# Test and record Win32 apps

<a id="write-a-spec"></a>

## Write a behaviour spec

Put one named ` (test ...) ` or ` (demo ...) ` form in each
` tests/specs/*.scm ` file. Place input data under ` tests/fixtures/ `.
A spec can look up a control by its type and caption or accessible
label. This scenario adds and checks one item in the Starter app.

``` scheme
(test "mark a title read"
  (steps
    (fill (text-field "Title") "Roc guide")
    (click (button "Add"))
    (expect-row-selected (list-view "Titles") "Roc guide")
    (click (toolbar-button "Mark read"))
    (expect-visible (text "0 unread"))))
```

Run ` roc windows.roc -- test --check ` to check source, run Roc expects,
and validate test and demo syntax. On a Windows desktop, use
` roc windows.roc -- test ` to build the app and run each test against
a fresh process. Each failure names the spec and step. The CLI must match
the runner protocol in the platform bundle. On Windows on Arm, an x64 Roc
process can test an ARM64 build with ` test --target arm64mingw `. Add
` --skip-expects ` when Roc expects run on another machine. Source checks and
the Win32 scenarios still run. Hosted Windows ARM64 uses this option.

Keyboard and mouse actions use the named controls on the scenario’s UI
thread. Scenario windows ignore queued desktop keyboard and mouse messages,
including while shown for recording. Use a normal app build for manual
keyboard traversal and physical mouse capture checks.

Selectors look up ` button `, ` checkbox `, ` toggle-switch `, ` text-field `, ` text-area `, ` text `,
` file-button `, ` folder-button `, ` file-drop-target `, ` image `, ` combo-box `, ` list-box `, ` radio-group `, ` list-view `,
` date-field `, ` time-field `, ` data-grid `, ` tabs `, ` toolbar `, ` toolbar-button `,
` progress-bar `, and ` tree-view `.
Use ` (within OUTER INNER) ` to narrow a
selector to a row or container. An action needs a unique match. Use
` expect-text `, ` expect-visible `, ` expect-absent `, ` expect-disabled ` and
` expect-checked ` to inspect the current control state. Keep control
assertions independent of pixel output. ` text-area ` finds a multiline
control by its visible label. ` expect-text ` compares the full text with LF
line endings. ` fill ` works on editable areas. Use ` "first\nsecond" ` for
multiline content.

Use ` (select (combo-box "Status filter") "unread") ` to propose a choice and
` (expect-selection (combo-box "Status filter") "unread") ` to assert the current
selection. Both forms use the choice key. An empty string represents
no selection for a drop-down or list box. Select a tab by key with
` (select (tabs "File details") "fingerprint") `. A locator scoped to the tabs
finds controls in the active page. Use ` select ` with a ` tree-view ` to
choose a visible item by key. ` expect-selection ` reads an empty string
when the app’s retained selection is hidden.

``` scheme
(expand (tree-view "Picked files") "type:txt")
(expect-expanded (tree-view "Picked files") "type:txt" true)
(collapse (tree-view "Picked files") "type:txt")
```

Use ` (toolbar "Group label") ` to locate a command group and
` (toolbar-button "Caption") ` to click a command or inspect its
enabled state. Scope a command with ` within ` when captions repeat.

For a report list, pass the locator and stable key to ` select-row `,
` activate-row `, ` press-column ` or ` expect-row-selected `. Pass an empty
string to ` select-row ` or ` expect-row-selected ` to clear or verify an empty
selection. Use ` expect-list-rows ` with the row keys in display order,
or with just the locator for an empty report. ` expect-sort ` checks the
sort arrow of a list view or data grid:
` (expect-sort (list-view "Titles") "title" ascending) `, ` descending `, or
` (expect-sort (list-view "Titles") "") ` for no arrow.

Date and time steps compare the committed typed value across locales.
Use ` no-date ` and ` no-time ` to set or assert the unset state.
In the Todos app, clearing the due date also clears the due time.

``` scheme
(set-date (date-field "New due date") (date 2028 2 29))
(set-time (time-field "New due time") (time 9 15))
(expect-date (date-field "New due date") (date 2028 2 29))
(expect-time (time-field "New due time") (time 9 15))
(set-date (date-field "New due date") no-date)
(expect-time (time-field "New due time") no-time)
```

To exercise draft entry, use ` fill `, followed by ` press-enter `.
Use ` expect-invalid ` to check the validation state and ` expect-text `
to check the retained draft. ` press-escape ` restores the committed value.

For an editable data grid, ` focus-cell ` and ` begin-cell ` take a grid,
a one-based mounted row number and a quoted column key. Use ` fill-cell ` with
the grid and a draft, then ` commit-cell ` or ` cancel-cell ` with the grid.
` expect-cell-focused ` takes a row and column. ` expect-cell-text ` and
` expect-cell-feedback ` also take the expected text. An empty feedback
string means the cell has cleared its error.

Use \\` select-cell-range\ ` with the grid and two row-column pairs to set a
rectangle. \\` paste-grid\ ` supplies tab-separated text to the grid’s normal
paste handler without using the shared desktop clipboard.

Custom surfaces accept ` pointer-down `, ` pointer-move `, ` pointer-up ` and
` pointer-cancel ` steps with an image or shader locator. Positions are
normalized to 0–10000 per axis. Use ` outside ` for a move or release
outside the zone. Send several positions in one move step to exercise
latest-only delivery. A native slider accepts ` set-slider `,
` expect-slider ` and navigation via ` key-press `.

``` scheme
(pointer-down (shader-view "Image comparison") 4200 5000)
(pointer-move (shader-view "Image comparison") 4500 5000 7000 5000)
(pointer-up (shader-view "Image comparison") outside)
(expect-slider (slider "Comparison divider") 70)
(key-press (slider "Comparison divider") "ArrowLeft")
(await-work)
(expect-shader (shader-view "Image comparison") "rendered")
```

Shader statuses include ` rendered `, ` fallback ` and ` error `. Wait for
work before checking a frame or capturing it with ` screenshot `.
Use ` (expect-shader-pixel LOCATOR X Y "RRGGBB" TOLERANCE) ` to check a
committed frame at an integer pixel coordinate from the upper left.

Use ` (expect-progress (progress-bar "Request progress") indeterminate) `
while a request is held. An assertion can also check ` idle ` or
` (determinate COMPLETED TOTAL) `. It reads the native bar’s visibility,
mode and determinate position. ` (expect-taskbar-progress indeterminate) `
checks the requested window progress. It works without a Windows
taskbar button.

Use ` (expect-status "2 visible" "1 unread") ` to check the native
status panes in order. Narrow windows may have fewer trailing panes.
An empty ` (expect-status) ` asserts that the app has no status bar.

To exercise file-drop routing with app fixtures, drop a batch over the
labeled target and outside every target in the window.

``` scheme
(drop-files (file-drop-target "Drop files here") "tests/fixtures/hello.txt")
(drop-files-outside "tests/fixtures/elsewhere.txt")
```

<a id="scope-actions-to-a-window-or-dialog"></a>

## Scope actions to a window or dialog

Use the native title to scope a locator when a label appears in more than
one window or dialog. A dialog title can also be scoped to its owner.
Unscoped control locators still work when they match one live control.

``` scheme
(expect-visible (window "File Inspector"))
(select (within (window "File Inspector") (tabs "File details")) "preview")
(fill (within (dialog "Notes for First") (text-area "Notes")) "Remember this")
(dismiss (within (window "Todos") (dialog "Notes for First")))
(expect-absent (dialog "Notes for First"))
```

` close-window ` issues a close request to an independent or main window.
` dismiss ` issues the same title-bar request to a dialog. The app may
keep the surface open. Use ` expect-visible ` or ` expect-absent ` with its
locator to assert the result. Actions against a window blocked by a modal
dialog fail. ` (expect-disabled (window "Todos") true) ` can check that
the owner is blocked while a dialog is open.

When the scenario closes the last window, place ` (expect-exit) ` as its final
step. The runner waits for the application’s successful quit message.
Omitting the assertion makes an early application exit a failed scenario.

<a id="simulate-and-run-effects"></a>

## Simulate and run effects

Tests start with isolated storage and hold HTTP requests, timers and
intervals by default. An optional ` setup ` form can seed
` local-storage ` or ` session-storage `, set ` initial-time ` in milliseconds,
or set a ` worker-pool ` limit. The HTTP example checks a submitted request
and answers it explicitly.

``` scheme
(expect-request 1 :method "GET" :url "https://example.test/guide")
(stub-http "guide" :status 200 :body "Read the guide.")
(run-effect 1)
(expect-visible (text "Read the guide."))
```

Held effects are numbered in issue order, starting at one. Use
` expect-pending-effects ` and ` expect-cancelled ` to inspect them.
Use ` fail-http ` to stage a failure. Advance virtual time with
` advance-time ` to exercise HTTP timeouts. Trigger a one-shot timer or
matching interval with ` fire-timer ` or ` tick-interval `. Inspect a period
with ` expect-interval `.

` (tick-interval 1000) ` delivers each live 1000 ms interval’s tick and
pumps after each one, so every tick is its own turn and its own native
sync. ` (tick-interval 1000 coalesced) ` queues every tick first and then
pumps once, as a running app does when completions arrive between two
pump ticks. The tick’s turns still run one by one, in order, but turns
that change no structure share one native sync. Budget that with
` expect-work `:

``` scheme
(tick-interval 1000 coalesced)
(expect-work (roc-turn = 6) (surface-sync = 1))
```

` (files "tests/fixtures/hello.txt") ` supplies a file as a picker result.
Pass several paths to simulate a multi-file picker. The app reads or
hashes files through the production file adapter.
` (folder "tests/fixtures/photos") ` supplies a directory to a folder picker
and runs the same bounded listing as a live selection. ` (folder) `
simulates cancelling the dialog. Fixture paths are relative to the app.
` (await-work) ` waits for file, Roc worker, image and shader work to settle with a
real-time bound. Use ` (setup (live-effects http)) ` to exercise the real
HTTP adapter or ` (setup (live-effects time)) ` for real timers. Use a
loopback HTTP fixture for an integration test that can run independently.

Clipboard requests in a scenario use a private test clipboard.
` (expect-clipboard N "value") ` checks the successful write count and last
text. ` (clipboard-busy) ` makes the next plain-text copy return
` Unavailable `.

Native specs simulate wall time, monotonic time, and entropy independently.
` (advance-time 1000) ` advances both clocks. ` (set-wall-time -1000) `
changes only signed wall time and leaves HTTP timeout deadlines and
elapsed marks alone. ` (live-effects time) ` opts into real clocks and
regional settings, while ` (live-effects entropy) ` independently uses CNG.

Use ` (regional-fixture "tests/fixtures/regional.txt") ` in setup to
supply regional facts. Fixture lines name a ` locale `, ordered
` language ` entries, a Windows ` zone `, an inclusive ` span ` of two Unix
millisecond values, and ascending ` offset ` entries with a timestamp
and minutes east of UTC. The first offset starts at the span’s start.
For exact formatting, use ` formatted utc|short|0|01/01/1970|00:00:00 `.
The first two fields accept ` utc ` or ` local ` and ` short ` or ` long `.
Simulated formatting requires a matching entry for each timestamp.

Nonzero in-bounds simulated entropy requests wait for a reply. Their
request numbers are independent of HTTP and timer effect numbers.
` (random-bytes 1 "tests/fixtures/reference.bin") ` delivers exact
fixture bytes with the requested length. ` (fail-random 2 failed) `
injects a CNG failure. The other failure modes are ` unavailable ` and
` refused `. ` (expect-random-cancelled 2) ` checks that supersession
retired a request. Cancelled requests cannot receive fixture bytes.
The native caps on timestamps and entropy also apply under simulation.

<a id="expect-work"></a>

## Assert native work

` (expect-work (COUNTER BOUND N) ...) ` checks the native work that the
previous step caused. That covers the step’s input, the sync it
triggered, and the message pump until the queue is empty. It also waits
for the images the step queued, since when the image worker finishes
is timing but what it does is not. An ` (await-work) ` right after a
step extends that step, so an ` expect-work ` after the wait reads the
input and all the work it started. ` BOUND ` is
` <= `, ` = ` or ` >= `. A failure lists every counter the step moved.

``` scheme
(set-slider (slider "Accent hue") 120)
(expect-work (invalidate >= 1) (redraw = 0) (set-window-pos = 0) (dwm-set <= 2))
```

The host names the counters. Use ` set-window-pos `, ` frame-changed `,
` invalidate `, ` invalidate-erase `, ` redraw `, ` redraw-erase `,
` redraw-frame `, ` redraw-all `, ` set-text `, ` repaint-message `, ` set-font `,
` create-brush `, ` create-font `, ` delete-object `, ` dwm-set `, ` set-theme `,
` set-prop `, ` set-scroll-info `, ` scroll-window ` and ` measure-text ` for
native calls. Use
` paint `, ` erase ` and ` nc-paint ` for messages the host handled. Use
` sync-visit `, ` style-visit `, ` layout-visit ` and ` arrange ` for the host’s
tree walks. Use ` tree-scan ` and ` tree-shift ` for the wire tree’s own
child-list searches and moves, ` plan-visit ` for window plan rebuilds and
` bridge-visit ` for the nodes the raster bridge checks. Use ` roc-turn ` for
Roc turns, ` command-bytes ` for the view command bytes they returned, and
` raster-queued `, ` raster-dropped ` and ` raster-backlog ` for image jobs and
queue pressure. Use
` invalidate-rect ` for partial invalidations, and the ` list-* `,
` choice-* `, ` tree-* `, ` uia-* ` and ` collection-scan ` counters for list
views, data grids, option lists, tab strips and tree views. The
contributing guide lists each one. The ` set-window-pos-redundant `,
` set-text-redundant ` and ` dwm-set-redundant ` counters count writes that
repeat the window’s last
value. Test windows stay hidden unless the spec takes a screenshot, so
` paint ` is usually zero there. Budget the calls that cause painting
instead. See [Budget native work](contributing.md#work-budgets).

A sync visits only what the step changed, so ` sync-visit `, ` style-visit `
and ` layout-visit ` make tight budgets: ` (sync-visit <= 2) ` holds however
large the window grows.

<a id="work-report"></a>

### Read the work report

Set ` ROC_HOST_WORK_REPORT=1 ` and each ` expect-work ` step appends one JSON
object, on one line, to ` work.txt ` in the spec’s artifacts directory. The
line describes the step the ` expect-work ` checks:

``` json
{"v": 1, "work": {"set-window-pos": 0, "set-text": 6, ...}, "spans_us": {"turn": 234, "apply": 3, "sync": 181, "layout": 0, "arrange": 0, "paint": 0, "pump": 421}, "span_calls": {"turn": 6, ...}, "gdi_before": 10, "gdi_after": 10, "user_before": 21, "user_after": 21, "peak_working_set": 17211392, "roc_turns": 6, "command_bytes": 120, "raster_queued": 0, "raster_dropped": 0, "line": 11, "column": 5, "spec": "tests/specs/effects.scm", "test": "effects", "step": "tick-interval", "args": ["1000", "coalesced"]}
```

| Field | Holds |
| --- | --- |
| ` v ` | The format version, 1. A new field keeps the version; a changed one bumps it. |
| ` work ` | Every counter, including those at zero, by its ` expect-work ` name. |
| ` spans_us `, ` span_calls ` | Microseconds in, and entries into, each timed span. See [Time the host’s phases](contributing.md#time-the-host). |
| ` gdi_before `, ` gdi_after `, ` user_before `, ` user_after ` | The process’s GDI and USER handle counts from ` GetGuiResources ` as the step began and at the ` expect-work `. |
| ` peak_working_set ` | The process’s peak working set in bytes so far. |
| ` roc_turns `, ` command_bytes `, ` raster_queued `, ` raster_dropped ` | Copies of the ` roc-turn `, ` command-bytes `, ` raster-queued ` and ` raster-dropped ` counters. |
| ` line `, ` column `, ` step `, ` args ` | The measured step’s source position, command and plan arguments. The mount, before the first step, is ` "step": "mount" ` at line 0. |
| ` spec `, ` test ` | The spec file (` ROC_WINDOWS_SPEC_FILE `, which ` windows.roc test ` sets) and the test’s name. |

Identity fields come last, so a reader can take the numbers without a
JSON parser. The verify mode’s work and time are left out, as they are
from ` expect-work `.

Set ` ROC_WINDOWS_SPEC_VERIFY=fresh ` to compare every step’s windows with a
fresh mount of the same tree. See
[Check the host against oracles](contributing.md#host-oracles).

<a id="capture-a-screenshot-or-record-a-demo"></a>

## Capture a screenshot or record a demo

Use a Windows desktop session for capture. A
` (setup (window-size 640 520)) ` form sets client size. Use
` (screenshot "after-add") ` for a PNG checkpoint or
` (screenshot (window "File Inspector") "main-preview") ` to capture
a particular window. A dialog locator can select a dialog screenshot.
Use ` test --screenshot-on-failure ` for a diagnostic image. Results are written
under ` build/specs/ `. Use a test’s control assertions for repeatable
checks across themes and display settings.

A ` (demo ...) ` scenario uses real timing. It is validated with the test
suite and executed by the explicit ` record ` command. The starter’s
` tests/specs/demo.scm ` adds and marks an item.

``` sh
roc windows.roc -- record tests/specs/demo.scm --format gif
```

GIF is the default. Use ` --format png ` for frames. The artifacts are under
` build/specs/ `. Automatic recordings follow the first app window until it
closes. Use explicit screenshot checkpoints to capture other windows. Capture of
minimized, occluded, locked or noninteractive sessions requires separate
verification.

<a id="runner-boundary"></a>

## Runner boundary

Native ` test ` and ` record ` build a separate executable under
` build/spec-executables/<target> `. Only an executable with the embedded
scenario marker accepts the runner’s plan and fixture environment.
Ordinary ` build ` and distribution use the shipping executable
under ` build/<target> `. Shipping executables ignore runner settings,
and the MSI packager refuses a marked scenario executable.

The CLI lowers a parsed scenario to a versioned plan file with source
locations. The built Win32 host executes that plan through its native
window, control and effect paths. Success requires an explicit completion
result. The runner uses separate storage per scenario and a watchdog that
still runs when the scenario uses virtual time.

Capture uses the app’s window and child controls. GDI draws the window
into a bitmap. The installed Windows Imaging Component encodes PNG, and
the host encodes GIF on a separate thread. See
[What the bundle contains](architecture.md#redistributable-inputs).

<a id="check-form-actions"></a>

## Check form actions

` (press-enter (text-field "URL")) ` exercises the window’s default-button
routing from that field. A disabled default leaves the current state
unchanged. Use ` (expect-checked (checkbox "Complete all visible tasks") mixed) `
for a mixed aggregate check box.

