Testing
Test components and whole applications without a window — component tests, input, timers, transcripts and golden files, headless application tests, the accessibility tree and the display list.
zgui tests run without a screen, a graphics device or font files. A component test builds one component into an in-memory tree and sends it input. A headless application test runs the whole frame loop, including style, layout and paint, and lets you check geometry, the accessibility tree and what was drawn.
Write your first component test
Add the view testkit as a dev-dependency:
[dev-dependencies]
zgui-testkit-view = "0.1"Use the same version (or the same git revision) as zgui. A component test passes a DomHandle
between crates, so two copies of zgui-view in one build fail to compile.
A test opens a zgui_testkit_view::Window, mounts a view into it, and runs a frame. Building a view
returns an anchor; mounting attaches its nodes. Put that in a small helper:
use zgui::prelude::*;
use zgui_testkit_view::Window;
/// Builds `view` and mounts it under the window's root.
fn mount(window: &Window, view: impl IntoView) -> (NodeId, Box<dyn Anchor>) {
let mut built = window.scope.with(|| view.into_view().build(&mut window.cx.cx()));
built.mount(&window.dom_handle, window.root, None);
let node = built.first_node().expect("the view produced a node");
(node, Box::new(built))
}Keep the anchor alive. Dropping it unmounts the view and drops its nodes, signals and timers.
Now test a counter:
#[component]
fn Counter() -> impl IntoView {
let (count, set_count) = signal(0);
view! {
row(class = "counter") {
label(class = "counter__value") {{move || count.get().to_string()}}
control(
class = "counter__step",
a11y:label = "Increment",
on:click = move |_| set_count.update(|n| *n += 1)
) {
"+"
}
}
}
}
#[test]
fn pressing_the_step_control_raises_the_count() {
let window = Window::open();
let (root, _held) = mount(&window, view! { Counter() });
window.frame();
// Give the control a box so a click can hit it.
let step = window.dom.tree().children(root)[1];
window.place(step, 0.0, 0.0, 24.0, 24.0);
assert_eq!(window.dom.tree().text_content(root), "0+");
let delivered = window.click(10.0, 10.0);
assert_eq!(delivered.target, Some(step));
assert_eq!(window.dom.tree().text_content(root), "0+", "not flushed yet");
window.frame();
assert_eq!(window.dom.tree().text_content(root), "1+");
}The component test runs your view, listeners and timers, but no document, style, layout or window.
It checks what the view built and how it reacts to input. The boxes come from place, not from
layout; for real geometry, use a headless application test.
Run a frame after each change
A signal write only marks its subscribers; the next frame runs them. In a component test,
window.frame() is that frame. It flushes, applies any values and selections the view wrote back
into the tree, and repeats until nothing changes (at most eight rounds).
Call frame() | Why |
|---|---|
| after mounting | the mount's effects have not run yet |
| after each interaction, or after writing a signal from the test | the handler only wrote a signal |
not after advance() | advance already runs a frame |
A headless application test has the same rule; its method is settle.
Read the tree
window.dom.tree() returns the in-memory tree:
| To read | Call |
|---|---|
| children of a node | children(node) |
| text of a subtree | text_content(node) |
| classes | classes(node) |
| one attribute | attribute(node, zgui::view::AttrName::new("variant")) |
| one inline style property | style_property(node, "color") |
interaction states (:hover, :disabled, …) | ui_state(node) |
| accessibility description | semantics(node) |
a prop: value | property(node, key) |
| size of the tree | node_count(), listener_count() |
Send input
window.click(x, y) covers the common case. For anything else, window.dispatcher() returns a
Dispatcher, which sends a real event to a point or a node: it builds the capture and bubble path,
runs the handlers and honours what they ask for.
use zgui::vocab::{EventKind, Key, Modifiers, NamedKey};
window.dispatcher().pointer_at(point, EventKind::PointerDown);
window.dispatcher().key(field, Key::Named(NamedKey::Enter));
window.dispatcher().with_modifiers(Modifiers::SHIFT).key(grid, Key::Named(NamedKey::PageUp));
window.dispatcher().send_to(button, EventKind::Click, payload);| Method | Sends |
|---|---|
click_at(point) | a click at a point, after a hit test |
pointer_at(point, kind) | one pointer event of any EventKind at a point |
key(node, key) | a key at a node, plus the window's default handling |
type_text(node, text) | a text event |
send_to(node, kind, payload) | one event at a node, with no hit test |
with_modifiers(modifiers) | the same dispatcher with modifiers held |
listener_at(node, kind, position) | the identity of one registered listener |
A wheel is send_to(node, EventKind::Wheel, Payload::Wheel(WheelEvent { … })); the WheelEvent
fields are shown under Send input to the surface.
Keys and typing
key does what a window does. It delivers key_down. If no handler prevented the default, it
offers the key to the editing model of a field or editor, and otherwise turns Enter or Space
into a click. A button with no key handling is therefore activated by Space in a test, as on
screen.
To type into a field, send characters with key. The view can also place the caret: a selection
the view sets with set_selection or select_all is applied to the testkit's editing model on the
next frame(), after any values, so the next key lands where the view put the caret.
window.host.set_value(field, "resta");
window.frame();
window.host.set_selection(field, 2..2);
window.frame();
window.dispatcher().key(field, Key::Character("-".into()));
assert_eq!(window.dom.tree().text_content(field), "re-sta");What a dispatch returns
pub struct Delivered {
pub target: Option<NodeId>,
pub path: Vec<NodeId>, // root first
pub ran: Vec<(NodeId, Phase)>, // handlers that ran, in order
pub default: DefaultAction, // whether the default action survived
pub commands: Vec<Command>, // what the handlers asked for
}reached_anything() is true when any handler ran. commands holds CapturePointer,
ReleasePointer, RequestFocus and Synthesize. The first three are recorded but not carried out
(the runtime also defers them), so assert on them directly. Synthesize is carried out: the extra
dispatch's handlers are appended to ran and its commands to commands.
An event aimed at an element that has left the tree reaches nothing: path and ran are empty.
A real window behaves the same way.
Hit testing
The testkit hit-tests against the boxes declared with place:
- a node without a declared box is not hit, but its descendants can be;
- a descendant wins over its ancestor;
- at equal depth, the later node in document order wins.
place and bounds_of return the test's own numbers, so asserting on them only tests your own
arithmetic. For real geometry, use a headless application test.
Test timers
The host owns a virtual clock, so timers fire without waiting. window.advance(by) moves the clock,
fires due timers, then runs a frame.
let window = Window::open();
let shown = window.scope.with(|| RwSignal::new(false));
let _pending = window.scope.with(|| {
set_timeout(Duration::from_millis(700), move || shown.set(true))
});
window.advance(Duration::from_millis(699));
assert!(!shown.get_untracked());
window.advance(Duration::from_millis(1));
assert!(shown.get_untracked());Dropping the handle set_timeout returns cancels the timer, so bind it. Never sleep in a test.
Check what the view did with the transcript
The transcript records every operation the view asked of its backend, in order. The tree, the host and the dispatcher all write to it, so it can answer questions about order and about redundant work. Clear it after mounting so you assert on the interaction, not the mount:
window.transcript.clear();
window.click(10.0, 10.0);
window.frame();
// One handler run and one text write.
assert_eq!(window.transcript.len(), 2);
assert!(window.transcript.to_string().contains("click target"));| Method | Gives |
|---|---|
to_string() | one line per operation (the golden-file format) |
ops() | the operations as Op values |
len(), is_empty() | how much was recorded |
clear() | forget everything so far |
assert_matches(path) | compare with a golden file |
All clones of a Transcript share one list. Each line names an operation and its node, for
example create #1 control, insert #2 into #1, text #2 "hello", class #2 danger on,
state #2 hover on, semantics #2 button, listen #2 click, selection #2 0..3,
handler #2 click target or command request-focus #2.
Nodes are written as # plus the number the backend assigned. Show, For and dynamic children
create marker nodes, which appear too. Writes that change nothing are not recorded. If a component
writes the same class twice per change, the transcript shows it even though the final tree looks
right.
Compare against golden files
Snapshots are golden files, compared by zgui_testkit_scene::dump::golden. A transcript uses it
through assert_matches.
use std::path::{Path, PathBuf};
fn golden(name: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/goldens").join(name)
}
#[test]
fn counter_steps() {
// … mount, place, click and frame as above …
window.transcript.assert_matches(golden("counter_steps.txt"));
}| Situation | Result |
|---|---|
| golden missing | the test fails and tells you to re-run with ZGUI_BLESS=1 |
ZGUI_BLESS=1 and the golden differs or is missing | the file is written and the test still fails, showing the change |
no ZGUI_BLESS, output matches | the test passes |
Blessing always fails so that you read the diff; the next run passes. Any non-empty value other
than 0 counts as set.
Answer the view's questions with the scripted host
window.host is a ScriptedHost. It answers the runtime questions a view asks from values the test
declares, and records the commands it receives.
| Declare | Method |
|---|---|
| a node's box | set_border_box(node, rect), or Window::place |
| the scale factor | set_scale(scale) |
| a scroll container's offset | set_scroll_position(node, position) |
| what is focusable under a root | set_focusables(root, nodes) |
| that one node contains another | set_contains(ancestor, descendant) |
| document order | set_tree_order(order) |
| running animations on a node | set_running_animations(node, count) |
| Ask | Method |
|---|---|
| requested scrolls | scroll_commands() |
| live focus traps | live_focus_traps(), topmost_focus_trap() |
| installed sheets | stylesheet(name), stylesheet_names(), stylesheet_count(), stylesheet_installs() |
| pending timers | live_timers() |
| whether scrolling is frozen | scrolling_frozen() |
focus_is_text_entry() also works in a component test when called inside window.scope. The
scripted host counts a focused node as a text entry once it holds a selection.
Test the whole application
zgui-platform-headless is a platform backend with no window system: a clock the test moves,
scripted input, and buffer surfaces. The real frame loop runs (dispatch, reactive flush, restyle,
layout, paint); only the renderer is replaced. Use it to check geometry, engine-computed states such
as :hover, the accessibility tree and the display list.
[dev-dependencies]
zgui-platform-headless = "0.1"
zgui-testkit-scene = "0.1"Build the app with the normal app() builder. into_handler does the same wiring as run, and
Handler::into_runtime returns the frame loop for the harness to drive.
use std::sync::Arc;
use zgui::geom::{DevicePx, Size};
use zgui::platform::{Surface, SurfaceEvent};
use zgui::prelude::*;
use zgui::render::{RenderTarget, Renderer};
use zgui::runtime::{AppError, Runtime};
use zgui_platform_headless::Harness;
use zgui_testkit_scene::CaptureRenderer;
/// A renderer that records the display list instead of drawing it.
fn capture(_surface: &Arc<dyn Surface>, target: RenderTarget) -> Result<Box<dyn Renderer>, AppError> {
let mut renderer = CaptureRenderer::new();
renderer.configure(target);
Ok(Box::new(renderer))
}
fn open() -> Harness<Runtime> {
let runtime = app()
.with_title("test")
.with_size(400.0, 300.0)
.with_stylesheet(SHEET)
.with_renderer(Box::new(capture))
.into_handler(|| view! { Counter() })
.expect("the reactive runtime installs")
.into_runtime();
let mut harness = Harness::new(runtime);
harness.deliver_to_first(SurfaceEvent::Resized(Size::new(DevicePx(400.0), DevicePx(300.0))));
harness.settle(64);
harness
}Send input to the surface
Input arrives as SurfaceEvents, as it would from a window system:
use zgui::geom::{Css, CssPx, Point};
use zgui::vocab::{
Modifiers, PointerAction, PointerEvent, PointerId, PointerKind, ScrollDelta, ScrollPhase,
Timestamp, WheelEvent,
};
fn pointer(action: PointerAction, at: Point<CssPx, Css>, time: Timestamp) -> SurfaceEvent {
let event = PointerEvent::mouse(at);
SurfaceEvent::Pointer { action, event, modifiers: Modifiers::NONE, timestamp: time }
}
fn wheel(at: Point<CssPx, Css>, lines: f32) -> SurfaceEvent {
let event = WheelEvent {
delta: ScrollDelta::Lines { x: 0.0, y: lines },
phase: ScrollPhase::Discrete,
position: at,
id: PointerId::MOUSE,
kind: PointerKind::Mouse,
};
SurfaceEvent::Wheel { event, modifiers: Modifiers::NONE, timestamp: Timestamp::ORIGIN }
}
/// A click is `Moved`, `Pressed`, `Released`.
fn click(harness: &mut Harness<Runtime>, at: Point<CssPx, Css>, time: Timestamp) {
for action in [PointerAction::Moved, PointerAction::Pressed, PointerAction::Released] {
harness.deliver_to_first(pointer(action, at, time));
}
harness.settle(8);
}Keys are SurfaceEvent::Key { state: KeyState::Pressed, event, modifiers, timestamp }, with event
built by KeyEvent::named(NamedKey::Enter, PhysicalKey::Unidentified(0)) or
KeyEvent::character("q").
Engine-owned states such as :hover, :active and :focus can only be produced by real input:
deliver pointer events and settle.
A double click is two clicks on the same element within 500 ms and 4 CSS pixels. The window
dispatches double_click after the second click; a third click starts a new count. The event
timestamps decide the interval, so give the clicks distinct times:
click(&mut harness, at, Timestamp::ORIGIN);
click(&mut harness, at, Timestamp::ORIGIN + Duration::from_millis(200)); // double_click firesFind elements and their boxes
A settled zgui::runtime::Window (from harness.app().windows()) can find elements and their
boxes. Use box_with_class to aim input without hard-coding coordinates. At the headless default
scale factor of 1, device pixels equal CSS pixels.
let window = &harness.app().windows()[0];
let step = window.box_with_class("counter__step").expect("the control has a box");
let centre = Point::new(
CssPx(step.origin.x.0 + step.size.width.0 / 2.0),
CssPx(step.origin.y.0 + step.size.height.0 / 2.0),
);
click(&mut harness, centre, Timestamp::ORIGIN);| Method | Gives |
|---|---|
nodes_with_class(class) | every element with that class, in document order |
box_with_class(class) | the first such element's border box in absolute device pixels, or None |
chain_at(point) | the elements under a device-pixel point, root first: the path an event would take |
pointer_capture(pointer) | the element holding that pointer's capture, if any |
has_pointer_capture() | whether any pointer is captured |
For any other geometry, read the fragment tree through window.layout(). Do not compute expected
positions from the style sheet; that tests your arithmetic, not the layout.
Drive the frame loop
| Method | Does |
|---|---|
deliver(surface, event) | one platform event to one surface |
deliver_all(surface, events) | a burst of events, handled in one turn |
deliver_to_first(event) | one event to the first surface |
pump() | one turn of the loop; returns the number of frames run |
settle(turns) | pump until nothing is pending; panics if work remains after turns |
advance(by) | move the clock |
run_for(total, step) | advance in steps, pumping each time |
suspend(), resume() | remove all surfaces, then recreate them and rebuild window views |
shut_down() | deliver application shutdown |
app(), app_mut() | the Runtime; windows() lists its windows |
platform() | the Headless platform; offscreens() lists its surfaces |
assert_park_invariant() | checks the loop resumed at most once more than it drew |
Real window systems deliver events in bursts. Use deliver_all to reproduce one; delivering the
same events one at a time tests a sequence that does not happen.
For several windows, take surface IDs from app().windows() or platform().offscreens() and pass
them to deliver. Each OffscreenSurface keeps the SurfaceAttributes it was created with
(requested_attributes()), so a test can check the requested title, size, decorations and so on.
Make text machine-independent
app() installs the production text engine and rasteriser, so text matches the shipped application
but depends on the installed fonts. There are two ways to avoid that:
app().with_fonts(Fonts::shipped_only())plusFonts::registerfor a bundled face. Real shaping, no system fonts.- Build with
zgui::runtime::Appand install the fixed test face, where every glyph is 8 × 16, so positions can be computed by hand. Addzgui-layoutto the dev-dependencies for this.
zgui::runtime::App::new()
// … title, size, sheet, renderer as above …
.with_text_engine(Box::new(|| {
Box::new(zgui_layout::Paragraphs::new(zgui_testkit_scene::MonoShaper::new()))
}))
.with_glyph_raster(Box::new(|| Arc::new(zgui_testkit_scene::MonoRaster::new())))
.into_handler(|cx: &mut BuildCx<'_>| -> Box<dyn Anchor> {
Box::new(view! { Counter() }.into_view().build(cx))
})
.expect("the reactive runtime installs");zgui::runtime::App::into_handler returns the Runtime directly and takes a build closure instead
of a view closure.
Test accessibility
In a component test, semantics(node) is what the element declares. This is where a missing role
or label shows up:
let step = window.dom.tree().children(root)[1];
let semantics = window.dom.tree().semantics(step).expect("the element has semantics");
assert_eq!(semantics.role, Role::Button);In a headless application test, the surface records the real updates each frame published:
fn published(harness: &Harness<Runtime>) -> zgui_a11y::TreeUpdate {
harness
.platform()
.offscreens()
.first()
.expect("a surface was created")
.last_a11y_update()
.expect("the frame published an accessibility update")
}
#[test]
fn the_step_control_is_announced() {
let harness = open();
assert!(zgui_a11y::dump(&published(&harness)).contains("Increment"));
}a11y_log() returns the retained updates, oldest first, and take_a11y_log() returns and clears
them; a11y_updates() counts every update ever published. Each update is a difference against the
earlier ones, so a claim about the whole tree must replay the log. The log keeps at most
A11Y_LOG_NODES (2²⁰) nodes in total and drops the oldest updates beyond that, so a long-running
test that needs every update should drain it as it goes.
zgui_a11y::dump prints an update as stable text for a golden file; add zgui-a11y as a
dev-dependency to use it. See Accessibility.
Test what was drawn
zgui-testkit-scene prints a finished scene (the display list) as stable text that does not depend
on drivers or installed fonts:
use zgui::bits::DamageSet;
#[test]
fn the_counter_draws_what_it_should() {
let harness = open();
let window = &harness.app().windows()[0];
let text = zgui_testkit_scene::transcript::of(window.scene(), &DamageSet::default());
zgui_testkit_scene::dump::golden::assert_matches(&golden("counter_scene.txt"), text.as_str());
}scene viewport=256x256
damage full
primitives 12 batches=12
quad order=2 bounds=rect(8, 8, 240, 96) fill=linear from=(0, 0) to=(256, 0) in oklab
mono_sprite order=3 bounds=rect(24, 24, 8, 16) tile=mono:0#0 texels=rect(0, 0, 8, 16)The same scene always prints the same bytes. Fields at their default value are omitted, so a diff
shows only what moved. transcript::of panics unless the scene is finished, which it is after a
frame.
The crate also exports CaptureRenderer (records the scene, draws nothing), MonoShaper,
MonoRaster and FixedMetrics (text without font files), and TreeDump/to_text (the interface
for tree dumpers).
Drive your own frame loop
zgui_testkit_scene::Harness drives a frame loop over a Fixture whose body is a closure taking
&mut FrameCx. It records damage and named subjects (cx.record_subject("#card", ink)), which the
test reads back with ink_of and damage_rects. This is mainly for framework work: checking what
one frame drew and what it cost. The harness holds the frame counters exclusively, so a second
harness on the same thread panics.
What to test
| Worth testing | Not worth testing |
|---|---|
| what the view builds for a state: classes, attributes, text, semantics | that a view compiles |
| what an input reaches, and what changed after the flush | exact pixels; assert on the display list |
| the order of operations, through the transcript | the cascade, layout and shaping themselves |
| what a listener asked for: focus, scroll, a focus trap | geometry the test declared with place |
| timing on the virtual clock | real elapsed time |
| geometry read from the window or the fragment tree | hand-written node numbers; let a golden hold them |
| what a screen reader is told | framework behaviour such as Enter activating a button |
| that unmounting removes what mounting added | frame counts in a component test |
Check CSS support
The unpublished zgui-conformance suite generates docs/parity.md in the zgui repository. Of 250
distinct longhands, 178 are implemented and 72 are parsed and cascaded but not yet implemented. A
property counts as implemented only when setting it visibly changes layout, hit testing, clipping or
paint. Check that file before relying on a property: a parsed-but-unimplemented one is accepted and
then ignored.
Reference
Test crates
zgui does not re-export these. Add them as dev-dependencies.
| Crate | Runs | Use it to check |
|---|---|---|
zgui-testkit-view | one component: its view, listeners and timers. No document, style, layout or window. | what the view built, what it asked the runtime for, what an input reached |
zgui-platform-headless | the whole application: document, cascade, layout, text, paint and the frame loop | geometry, the accessibility tree, the display list |
zgui-testkit-scene | golden files, scene transcripts, a frame loop you drive yourself, frame counters | what one frame drew and how much work it did |
zgui-testkit-view turns on the stub-backend feature of zgui-view for the test build. That
feature provides the in-memory tree; it is off in a normal build.
zgui_testkit_view::Window
Its public fields are transcript, dom (the RecordingDom), host (the ScriptedHost),
dom_handle, host_handle, scope, cx (the build context) and root.
| Method | Does |
|---|---|
Window::open() | opens a window and installs the reactive runtime on this thread |
Window::for_document(id) | the same, for a test that needs two documents |
place(node, x, y, width, height) | declares a node's box, so input can be aimed at it |
dispatcher() | a Dispatcher for the root's subtree |
click(x, y) | clicks at a point and returns Delivered |
frame() | runs the reactive flush, which is what a frame does at this level |
advance(by) | moves the virtual clock, fires due timers, then runs a frame |
now() | the virtual clock, as a Duration |
bounds_of(node) | the box the test declared for a node |