caretline

Testing

Because update and view are pure, a caretline test is just data: a starting state, some keys or messages, and the expected result. No terminal, no timing, no mocks.

Where the tests live

FileWhat it checks
caretline/tests/goldens.rsBehaviour goldens: text and selection before, keys, text and selection after (and frames where it matters). The baseline is a macOS text field
caretline/tests/rehydrate.rsA state survives JSON exactly; a recorded session replays to the live result
caretline/tests/fuzz.rsProperty tests: seeded random documents and messages, with invariants checked after every step
caretline/tests/marks.rsBlock marks: each mapping rule, undo and redo restoring marks exactly, cut and paste keeping ids, serialization; random sessions with marks at line starts and unique ids after every step, every undo restoring the marks
caretline/tests/outline.rsBlock goldens in block notation (‖ blocks with a blank row between, ¦ without, ⏎ a soft break), with block ids: Enter, Backspace and Delete at block edges, Tab, tags, moves, atomic images, copy and paste, blank rows, host messages and effects
caretline/tests/host.rsThe extension points with a made-up host: commands (undo, traces, replay with the host, the protocol), input rules, mark payloads through cut, paste, undo and JSON, decorations and hit-testing, tags
caretline/tests/hooks.rsThe generic hooks with a made-up host (a counter and a pin that follows the text): view values through JSON, the protocol and replay; Msg::Ext and observers (passive, read-only views, the changes update_with_changes returns, every view holding a key); cell_px through resize, old traces included; frame passes and the Frame writers around wide graphemes; locate as the inverse of hit, with folds; catalog entries and host ops over the protocol
caretline/tests/layout.rsThe outline layout (markers in a hang, columns per depth, virtual rows, folds, row info, hit-testing) and prose rows at the column’s edge: none wider than the column, wide graphemes included
caretline/tests/commands.rsThe command catalog and the keymap as data: ids, messages, bindings, agreement with the hand-written keymap it replaced, the protocol ops
caretline/tests/serde_features.rsThe engine’s JSON under serde_json features a host may turn on: the engine’s manifest enables neither preserve_order nor arbitrary_precision, responses keep their key order, marks, payloads, clipboards, messages, protocol requests and traces round-trip
caretline/tests/single_line.rsOne-line documents: Enter, flattened typing, paste, CRLF, host edits and changes from elsewhere, undo across a flattening paste, loading a state with line breaks, Up and Down, sideways scrolling, several carets, the protocol, and random sessions that never break the line
caretline/tests/scope.rsNo host concept (task, status vocabulary, journal…) named in the engine’s sources
caretline/tests/docs.rsThe examples in these docs run
caretline/tests/outline_fuzz.rsOutline properties over random outlines and messages: blocks and marks agree, ids unique, no caret in a marker or an image, undo and redo exact (marks included), kind changes move no other block, host commands (a made-up retagging host) included, cut and paste in place keeps ids, Markdown files round-trip. CARETLINE_OUTLINE_SEEDS runs more seeds
caretline/tests/keymap.rsKey bindings and the key-script parser
caretline/tests/common/mod.rsShared helpers: caret notation, golden, keys, send, frame, random generators
caretline-layers/tests/conformance.rsThe shared host conformance kit: placement invariants, deliberately broken plans, determinism, JSON, replay, mapping, protocol contract, stable snapshots and inspector agreement (feature conformance)
caretline-layers/tests/head.rsRow-bound arrow heads, clear-cell routing and stable reasons when no head fits
caretline-tour/tests/conformance.rsEvery example walkthrough step checked on the host’s scenes at several sizes (feature caretline-layers/conformance)
caretline/src/helix/**Helix’s own unit tests, vendored with the code
caretline-cli/tests/cli.rsThe binary: fixtures render to their saved snapshots, traces replay, --keys and --dump-state round-trip, effects are reported and never performed
caretline-cli/tests/demo.rsDemo frames against tests/goldens, live PTY controls, socket subscriptions and command-line edits. The showcase’s --headless report verifies all 13 invariants
caretline-cli/src/screen.rsIn-process screen tests, test-only: the runtime’s real draw writes into memory (Painter) and a vt100 emulator reads the cells back (Screen), so a test asserts what the screen shows (the frame, other carets as reverse cells) with no process or pseudo-terminal
caretline-cli/src/harness.rsKey-to-screen tests, test-only (Harness::new, press, check): a key goes through the simulated Ghostty, the decoder, update and draw into vt100, and the screen-truth check runs after every key. caretline sim tries a case from the shell before it becomes a test
caretline-cli/src/harness_fuzz.rsThe harness fuzz, test-only: random documents (wide graphemes, tabs, blank lines), sizes and physical key presses through the simulated Ghostty (its defaults and as caretline doctor fixes it, with and without the keyboard protocol), the screen-truth check after every key. A failure is shrunk to the fewest keys and printed as a caretline sim command (see The harness fuzz). CARETLINE_HARNESS_SEEDS runs more seeds than the default 32
caretline-cli/tests/harness.rsEvery golden in tests/goldens/harness/ replays: a golden’s first line is the caretline sim command that shows it, the rest is what that command prints. The bugs found by hand and by the harness fuzz. CARETLINE_GOLDENS=update rewrites them
caretline-cli/tests/common/mod.rsShared by the binary’s and the MCP server’s tests: child processes and scratch directories that clean up after themselves, a pseudo-terminal, deadlines (see Tests that start processes)

Run them:

cargo test -p caretline
cargo test -p caretline-cli

Cargo turns a dependency’s features on for a whole build, so a host that enables serde_json’s preserve_order (insertion-ordered objects) or arbitrary_precision (exact numbers) enables it in the engine too. The engine enables neither itself (it would change JSON for every crate in the host’s build), and its output must not depend on them: protocol responses are structs, whose keys come out in declaration order, never json! maps. CI runs the engine’s tests with neither and with each:

cargo test -p caretline
cargo test -p caretline --features serde_json/preserve_order
cargo test -p caretline --features serde_json/arbitrary_precision

cargo test -p caretline on its own runs with neither; cargo test --workspace runs it with preserve_order, which the binaries enable for their own output.

Host layers integration tests

The layers crate’s optional conformance feature gives every host the same checks over its own screens. Build conformance::Scene values using your actual renderer measurements and anchor resolver, then run check_sizes at wide, normal and narrow sizes. Add replay, anchor-mapping and protocol contract checks and commit snapshots of representative screens. The integration guide describes the helpers; the inspector explains placement failures.

CI runs the kit against the layers fixtures, ratatui example, CLI layers demo and walkthrough example on both Linux and macOS:

cargo test --workspace --features caretline-layers/conformance --locked

The default workspace tests do not enable the kit; keep this feature-enabled run in a host’s CI too. Narrow strips, off-screen chips and omitted arrows can be valid fallbacks: the report lists them separately from invariant violations so your goldens can document what people see.

Tests that start processes

The binary’s tests and the MCP server’s start real processes: editors on a pseudo-terminal, caretline serve on a socket, caretline-mcp. Through the helpers in caretline-cli/tests/common, none outlives its test:

Waits are for output, not on a clock: a pseudo-terminal wakes the waiting test as output arrives, and requests wait for their response. Each wait still has a deadline, so a hang fails with the screen it got to. Deadlines are nominal times multiplied by CARETLINE_TEST_TIMEOUT_SCALE (default 6, so a nominal 10 s is a minute), which leaves room for a loaded machine; set it to 1 to find a slow wait, or higher on a slow CI runner.

The showcase can also validate itself directly, without a terminal or real-time waits:

cargo run -p caretline-cli -- demo showcase --headless
cargo run -p caretline-cli -- demo showcase --snapshot 100x30 --keys '4<wait:7000>'

Its unit tests compare frequent and delayed polling, verify pause/navigation clocks, check text-preserving overlay placement, rapid pixel cleanup, live paste suppression, bounded/paused finale frames, distinct bundled font outlines and small windows. The CLI palette is checked against the site’s design tokens, and pixel panels/arrows/rings have PNG goldens.

Caret notation

Goldens write the text and the selection as one string:

NotationMeans
▮The caret (the selection’s head)
⟦abc▮⟧abc selected left to right: the anchor before a, the caret after c
⟦▮abc⟧abc selected right to left: the caret before a

state("Hello ⟦wor▮⟧ld") builds a state at 80x24 from notation; state_wh(…, w, h) picks the size. show(&state) prints the primary selection back in notation.

Goldens

A golden is a before, a key script and an after:

#[test]
fn e01_left_collapses_to_start() {
    golden("Hello ⟦wor▮⟧ld", "<left>", "Hello ▮world");
}

When a case needs more than text and selection, drive the state and assert on what you need: effects, the clipboard, the history, the frame or the caret’s cell.

#[test]
fn e37_cut_is_one_undo_step() {
    let mut s = state("Hello ⟦wor▮⟧ld");
    let fx = keys(&mut s, "<c-x>");
    assert_eq!(fx, vec![Effect::ClipboardSet { text: "wor".into() }]);
    assert_eq!(show(&s), "Hello ▮ld");
    keys(&mut s, "<c-z>");
    assert_eq!(show(&s), "Hello ⟦wor▮⟧ld");
}
HelperDoes
golden(before, script, after)Builds, runs the keys, compares the notation
keys(&mut state, script)Runs a key script through the keymap; returns the effects
send(&mut state, msgs)Sends messages; returns the effects
frame(&state)The rendered frame as text
cursor(&state)The caret’s screen cell

Use <wait:MS> in a script when undo grouping matters: "one<wait:2000> two<c-z>" undoes only " two".

Try it

Every change also ends its CHANGELOG entry, commit and PR with a Try it: line, a command anyone can paste to see the change working, such as curl -fsSL https://caretline.app/install.sh | sh -s -- --ref main -- doctor --keys. scripts/check-try.sh enforces it; the rule is in AGENTS.md.

Rehydration and replay tests

rehydrate.rs checks two promises.

The property fuzzer

fuzz.rs runs 24 seeds of 500 random messages each (SEEDS, STEPS). Documents mix ASCII, tabs, CRLF, emoji with skin tones, ZWJ families, flags, combining accents, CJK, zero-width and control characters. Viewports range from 1x1 to 200 columns. Now and then a step starts from a random multi-range selection.

After every step it checks:

Invariant
PositionsEvery anchor and head is within the text and on a grapheme boundary
EI1A motion without Shift leaves no selection
EI2A motion with Shift never moves the anchor
EI4Copy changes nothing but the clipboard
EI5An edit that made a new revision undoes to exactly the state before it and redoes to exactly the state after
EI6, EI7Typing over a selection replaces exactly it; a delete with a selection removes exactly it
EI13 (screen)The screen shows the selection: in a focused view, a cell drawing a char is a Caret cell exactly when an empty range other than the primary sits on it, else a Selection cell exactly when a range covers it; each such caret is drawn where the cursor would be if it were the primary
EffectsEffects are plain values that match the message
viewNever panics, at the state’s size and at extreme sizes
SerializationAt random points, the state round-trips to the same state and frame
Undo allUndoing everything gives back the original text

Separate tests check EI3 and EI8 (cut-then-paste and copy-then-paste in place are identities) and EI12 (select all, delete, one undo restores everything).

A failure names its seed and step (seed 7 step 312: …). The generator is seeded, so the same seed fails the same way every time. To focus on it, temporarily run only that seed in random_sessions_keep_every_invariant.

The harness fuzz

harness_fuzz.rs does for the screen what fuzz.rs does for the state: each seed builds a random document, terminal size and run of physical key presses, sends them through the simulated Ghostty, the decoder, update and draw into a terminal emulator, and checks after every key that the screen shows the state. It runs 32 seeds; CARETLINE_HARNESS_SEEDS runs more:

CARETLINE_HARNESS_SEEDS=500 cargo test -p caretline-cli harness_fuzz

A failure is shrunk to the fewest keys that still fail and printed as a caretline sim command, so it replays from the shell:

seed 7: the screen doesn't show the state.
…
replay (2 keys):
  caretline sim 'a▮\nカナ\nb' '<s-down><s-down>' --size 10x3

Once fixed, the case becomes a golden: add a file to crates/caretline-cli/tests/goldens/harness/ whose first line is that command, and write the rest of it from the command’s output:

CARETLINE_GOLDENS=update cargo test -p caretline-cli --test harness

tests/harness.rs replays every golden from then on.

Snapshot fixtures

crates/caretline-cli/fixtures holds NAME.state.json files with NAME.snapshot.txt and NAME.snapshot.ansi beside them. fixtures_render_their_snapshots finds every *.state.json, renders it at its own viewport in both formats, and compares. Adding a fixture needs no code:

cd crates/caretline-cli/fixtures
printf 'First line\nA second line that is long enough to wrap.\n' > my-case.md
caretline --new-state my-case.md --size 30x6 > my-case.state.json && rm my-case.md
caretline --state my-case.state.json --keys '<down><s-end>' --dump-state my-case.state.json
caretline --state my-case.state.json --snapshot 30x6 > my-case.snapshot.txt
caretline --state my-case.state.json --snapshot 30x6 --format ansi > my-case.snapshot.ansi

The snapshot size must be the state’s viewport, because the test renders each fixture at its own viewport.

--new-state records the path you give it, so run it from the fixtures directory (or edit path afterwards) to keep machine paths out of the fixture. Review the snapshot by eye before committing it: from then on, the test holds the engine to it.

From a recorded trace to a test

When something goes wrong in a real session, record it and turn it into a test.

1. Record it.

caretline draft.md --trace bug.jsonl

2. Check that it replays. The replay is exact, so the bug shows up in the final frame or state.

caretline --replay bug.jsonl --snapshot 80x24
caretline --replay bug.jsonl --dump-state -

3. Split it into a starting state and a message file. Then you can trim messages until only the ones that matter remain:

head -1 bug.jsonl | jq .state > bug.state.json
tail -n +2 bug.jsonl | jq -c .msg > bug.msgs.jsonl
caretline --state bug.state.json --msgs bug.msgs.jsonl --snapshot 80x24   # same frame as the replay

--msgs and --replay agree as long as the trace has a single state line. A trace that was appended to by several sessions has one state line per session; split at the last one.

4. Write the test. Pick one:

use caretline::trace::replay_trace;
use caretline::view;

#[test]
fn recorded_session_replays_to_the_saved_frame() {
    let trace = include_str!("../../caretline-cli/fixtures/session.trace.jsonl");
    let (state, _) = replay_trace(trace).unwrap();
    // The trace ends with a resize to 36x8, the snapshot's size.
    assert_eq!(
        view(&state).to_text(),
        include_str!("../../caretline-cli/fixtures/session.snapshot.txt")
    );
}

Run it before the fix to see it fail, then fix the engine and keep the test.

This page on GitHub: docs/testing.md