Host test utility #
Burokku::builder().with_backend::<TestBackend>() runs an application with
in-memory windows that present into memory layer surfaces. It uses the normal
application bootstrap, LLRT/QuickJS runtime, UI bindings, layout, scene building,
input routing, tree features such as the resize observer, and shutdown
handling.
Use it for application and host behavior tests. Build fixtures in Rust with
with_fixture and the UI tree macro, or supply an application
script when testing JavaScript behavior; send input with pointer() and
keyboard(), and call settle() before asserting on what the app shows.
Tests that deliberately corrupt private host state or control individual
graphics task completions still use focused internal fixtures.
Enable test support #
For an example crate under example/, add:
[dev-dependencies]
burokku = { path = "../../crates/burokku", features = ["test-support"] }
Adjust the path for another location. If the application disables Burokku's
default features, also set default-features = false on this development
dependency; its normal dependency can continue selecting the application's
features. See the counter manifest.
Unit tests inside Burokku already compile the utility. External integration tests
need test-support: compiling a dependent crate's tests does not set
cfg(test) on the Burokku library. The feature also enables native/test-support.
The public entry points are burokku::{TestBackend, TestApp}. The
burokku::test module also exports these types; Fixture and
FixtureError; the ui_tree! macro; the input handles Pointer, Keyboard, and Target; the
window events, IDs, physical coordinates/sizes, the layer tree types
(LayerTree, Layer, LayerKey, LayerRect, LayerShape, Rgba8,
Viewport), PresentationOutcome, HeadlessWindow, and TestRenderer.
No OS window is created and nothing touches the GPU. Each headless window presents through the real compositor reconciler into a memory layer surface, which checks every changeset and keeps the layer tree it shows. Tests assert on that tree rather than on pixels. Timers use real time; this utility does not provide a virtual clock.
Rust tree fixtures #
An application script is optional. with_fixture gives a synchronous closure
a Fixture over the same tree used by the host and JavaScript bindings. A
Fixture builds as script does, and no more: each of its methods does what
one script call does. The app root already exists; ui_tree! appends the
declared window beneath it. burokku::test exports the macro; see the
macro documentation.
use burokku::{
test::{ui_tree, Rgba8},
Burokku, BurokkuError, TestBackend,
};
const RED: Rgba8 = Rgba8 { red: 255, green: 0, blue: 0, alpha: 255 };
const GREEN: Rgba8 = Rgba8 { red: 0, green: 255, blue: 0, alpha: 255 };
#[test]
fn rust_fixture_renders() -> Result<(), BurokkuError> {
Burokku::builder()
.with_backend::<TestBackend>()
.run_test(|mut app| async move {
let panel = app.with_fixture(|tree| {
ui_tree!(tree,
<window width="64" height="64">
<div var=panel style:width="20px" style:height="20px" style:background-color="#ff0000" />
</window>
);
panel
});
app.settle().await?;
assert_eq!(app.presented_backgrounds()?, [RED]);
app.with_fixture(|tree| tree.set_style_property(panel, "background-color", "#00ff00"))
.unwrap();
app.settle().await?;
assert_eq!(app.presented_backgrounds()?, [GREEN]);
Ok(())
})
}
with_fixture<R>(&mut self, f: impl FnOnce(&mut Fixture<'_>) -> R) -> R #
Returns the closure's result, including node IDs or owned values. The
Fixture cannot escape the closure, and the closure cannot hold the borrow
across an await. Macro var bindings are local to the closure; return them
explicitly when needed later.
Fixture method |
Does what script's call does |
|---|---|
root() |
app |
create_element(tag) |
app.createElement(tag); fails for a tag no extension registered |
create_text(text) |
app.createTextNode(text) |
append_child(parent, child) |
parent.appendChild(child) |
set_attribute(node, name, value) |
node.setAttribute(name, value) |
set_style_property(node, name, value) |
node.style.setProperty(name, value) |
Each fails with a FixtureError holding what the script call would throw.
Mutations use the normal tree operations and revision tracking. They do not
run a host turn or render immediately: call settle(), run_host_turn(), or
present() afterward. A returned NodeId does not keep a detached node alive
across host maintenance; attach fixtures before returning. Build the tree
before script holds the nodes it moves: script objects already made for them
do not learn of the move. This API does not disable the JS runtime; the runner
still uses normal application startup with an empty default script.
Core's own unit tests, which need the engine's structure, borrow the
UITree itself through the crate-private with_ui_tree; no other test can.
Reading state #
| Function | Result |
|---|---|
with_view(f) |
Lends f the read-only TreeView a feature slot's take reads: nodes, their boxes in the presented and the last layout, where scrolling places them, focus, hover, pointer capture, and the pointer grab. |
read_slot::<T>(node, f) |
Lends f node's feature slot of type T, read-only, as the slot's own take reads it. None when the node holds none. |
read_instance::<T>(node, f) |
Lends f the instance of the element node when it is a T, read-only. None otherwise. |
None of them can change anything. A test reads through them what an
extension can already read of its own state; eval reads what script sees.
JavaScript application example #
Use a synchronous Rust #[test]. run_test owns a Tokio runtime and must be
called outside an existing Tokio runtime, including one created by
#[tokio::test].
use burokku::{Burokku, BurokkuError, TestBackend};
#[test]
fn clicking_changes_the_window_title() -> Result<(), BurokkuError> {
Burokku::builder()
.with_backend::<TestBackend>()
.script(r#"
const win = app.createElement('window');
win.setAttribute('width', '64');
win.setAttribute('height', '64');
win.setAttribute('title', 'before');
const button = app.createElement('div');
button.style.setProperty('width', '32px');
button.style.setProperty('height', '32px');
button.addEventListener('click', () => win.setAttribute('title', 'after'));
win.appendChild(button);
app.appendChild(win);
"#)
.run_test(|mut app| async move {
app.settle().await?;
app.pointer().click((10.0, 10.0)).await?;
app.settle().await?;
assert_eq!(app.window_title().as_deref(), Some("after"));
Ok(())
})
}
A shipped application can use the same builder options. The counter integration test loads the real example script and embedded font, injects clicks at computed button coordinates, and checks the resulting text and native window title.
Builder and runner functions #
| Function | What it does |
|---|---|
Burokku::builder() |
Creates the default native application builder, with Burokku's own extensions registered: the UI tree, text, scrolling, ResizeObserver, and, with the llrt feature, LLRT's globals. |
BurokkuBuilder::core() |
With test-support only: a builder with the engine's own extensions alone, the UI tree and text, without LLRT's globals. A test adds the features it tests with extension, so a feature's tests run without the others. |
with_backend::<TestBackend>() |
Changes the builder's backend type while retaining the script and extensions already supplied. It does not start the application. |
script(source) |
Sets the application JavaScript source. A later call replaces the earlier source; it does not append it. |
extension(extension) |
Adds an extension. A closure taking &mut Registry is one: registry.install adds a runtime plugin, such as a closure taking &Ctx that sets test globals; registry.script adds a script; registry.font adds font data to load before layout, which tests that render text need; and registry.on_shutdown adds a hook that runs before the runtime stops. Invalid font data or a missing requirement prevents startup. |
without_system_fonts() |
On BurokkuBuilder<TestBackend>: text lays out in the fonts the extensions register through registry.font alone, never the machine's, so what a test measures is alike on every machine. |
BurokkuBuilder<TestBackend>::run_test(body) |
Starts the application, runs the async callback with a TestApp, shuts down the host/runtime, and returns Result<(), BurokkuError>. |
run() on the native builder |
Runs the actual native application loop. Host tests use run_test instead. |
NativeBackend is the default. Backend is currently sealed to the built-in
native and test implementations. TestBackend is a selection type; it has no
public constructor or configuration methods of its own.
Extensions register after Burokku's own, unless they name one in
Extension::before, so their plugins install after LLRT's globals, the UI tree,
and Burokku's features. Every extension's scripts run after
every plugin is installed and before the application script. Use extensions to
install test globals; use the application script to work with the app tree.
run_test lifecycle #
The callback has the shape FnOnce(TestApp) -> Future<Output = Result<(), BurokkuError>>. Both the closure and future must be 'static; they do
not need to be Send. Use move to transfer captured test data into the closure.
The runner:
- Uses shared application assembly to create a persistent
LocalSet, register extensions, load fonts, and prepare the host and runtime bootstrap task. - Creates a current-thread Tokio runtime and polls the local tasks to install the extensions' plugins, run their scripts, start the JavaScript driver, and evaluate the application script.
- Waits for successful script startup, then starts the callback. Startup does
not guarantee that a renderer or presented frame is ready; call
present()when the test needs one. - When the callback completes, returns an error, or panics, requests host shutdown, closes the active window, cancels pending graphics work, and waits for the runtime bootstrap task, including the extensions' shutdown hooks, such as LLRT's cleanup, and driver join.
- Resumes a callback panic after cleanup. Otherwise it returns the callback error, a cleanup error, or the final application result, in that priority.
Startup, the entire callback, and shutdown each have a ten-second timeout.
present() also has a ten-second presentation wait, within the callback's
budget. Timeout handling aborts and awaits the relevant task. These are
cooperative Tokio deadlines; they cannot interrupt synchronous code that blocks
the runtime thread, such as a non-yielding JS loop.
A fatal host error remains fatal even if the callback catches the error from an individual operation. The runner checks the host and runtime result before returning success.
Driving the host and JavaScript #
The client controls when Rust host work runs. Sending input, evaluating JS, and presenting a frame are separate operations.
| Needed result | Function |
|---|---|
| Run JavaScript or read listener results | eval |
| Let the app go idle and show the tree as it is | settle |
| Point, press, drag, or turn the wheel, as a user does | pointer |
| Press keys, type, send an editing command, or compose with an IME | keyboard |
| Process one host turn, including observer work, without requiring a frame | run_host_turn |
| Wait for a usable frame for the current tree revision | present |
| Inject an event originating from a native window | send_window_event |
| Send keyboard input to a specific UI-tree node | send_keyboard_event |
| Force a garbage-collection pass before checking wrapper lifetime | run_gc |
eval<T>(&self, source) -> Result<T, BurokkuError> #
An async evaluation submitted to the runtime's normal FIFO macrotask queue. It
checks for an existing host/runtime failure, enqueues the evaluation, and waits
for its result. Earlier queued input callbacks run before the evaluation:
native input runs one task per input, each queuing the next, so eval first
waits until none is left queued. The runtime performs a QuickJS microtask
checkpoint after each macrotask.
T must implement FromJs for any JS lifetime and be Send + 'static. Typical
results are (), bool, numbers, String, and supported Rust collections.
Raw context-bound JavaScript values should stay inside the JS context.
Use eval::<()>(source) for mutations. Evaluation does not itself reconcile the
host or publish new geometry. It also does not automatically await a returned
JavaScript promise.
JavaScript conversion/evaluation failures become BurokkuError::JavaScript.
Queue submission failures become Host errors; a lost result channel becomes
MainRuntimeStopped. Existing host/runtime failures are reported as Host
errors before submitting work.
settle(&mut self) -> Result<(), BurokkuError> #
Runs host turns, presenting after each when there is a window, until a turn
finds the frame it presented still current: queued input, script tasks, and
their microtasks are done, observers have delivered, and the window shows the
tree as it is. Timers not yet due do not count, so an app with a
setInterval settles. Without a window it runs the turns alone.
It fails after 32 turns in which what the app shows kept changing, as it does
while an animation runs or a callback changes the tree after every layout.
Use run_host_turn and present to test turns and frames themselves.
pointer(&mut self) -> Pointer<'_> #
The pointer of the app's window. Each call returns once the input it sent is
dispatched, with the listeners and their microtasks run, and does not
present; call settle() to see the frame that follows.
Pointer method |
Sends |
|---|---|
move_to(target) |
a move, with the buttons held |
press(target, button) / release(target, button) |
a press or release of button |
click(target) |
a primary press and release; clicks close together count as a double or triple click |
drag(from, to) |
a primary press at from, a move to to, and a release there |
wheel(target, delta_x, delta_y) |
a precise wheel outside a trackpad gesture; a positive delta scrolls right or down, as WheelEvent.deltaY reads it |
The pointer holds its buttons between calls, so a move after a press drags.
A Target is a point (x, y) in logical pixels from the window's top-left
corner, or a NodeId: the middle of the node's box in the presented frame,
where the scroll containers around it show it. A node target needs a
presented frame. Wheels with a trackpad phase or line deltas are
send_input_event calls.
keyboard(&mut self) -> Keyboard<'_> #
The keyboard and text system of the app's window. Each call returns once its input is dispatched, as the pointer's do.
Keyboard method |
Sends |
|---|---|
hold(modifiers) |
the modifiers held from now on, which each later key carries |
key_down(key) / key_up(key) / press(key) |
a key by its DOM key value, such as "a" or "Enter" |
type_text(text) |
text the text system commits at the selection |
command(command) |
an EditCommand, such as moving the caret or focus |
compose(text, selection) |
the open IME composition; empty text closes it |
The test backend binds no keys, as a platform's text system does, so a test
that needs the command a key is bound to sends it with command after the
key. Events the platform delivers in one callback, such as a key and its
text, are send_input_event calls when a test is about what was queued
together.
run_host_turn(&mut self) -> Result<(), BurokkuError> #
Runs one Rust host turn between two JavaScript macrotask barriers:
eval::<()>("")enqueues an empty JS task. This waits for JS tasks already ahead of it and their microtask checkpoints.- The host reconciles tree/window changes, processes ready graphics results, measures requested layouts, delivers observer work, and dispatches queued headless window events, including requested redraws.
- Another empty JS evaluation waits behind callbacks queued by that turn.
A barrier marks a position in the queue. It does not drain all future work: callbacks can enqueue more tasks behind it, and timers may run later. Mutations made by callbacks from this turn are reconciled on a subsequent host turn.
This method can run with no window or a zero-sized window. It does not wait for pending graphics initialization or require a presentation. If the turn requests shutdown, it skips the final JS barrier because the queue is closing.
Recoverable frame failures stay recorded in the host; run_host_turn reports
fatal host/runtime failures. Use present() when the assertion needs a frame or
an error for the candidate frame.
present(&mut self) -> Result<u64, BurokkuError> #
First performs a JS queue barrier and records the resulting UI-tree revision. It then runs host turns and waits for notifications until a usable frame has that revision or a later one. It returns the presented revision.
A usable frame must match the active window, physical size, surface generation, and renderer presentation revision. The method can return an existing matching frame; it does not promise a new presentation on every call.
It reports a recorded candidate failure for the requested revision, fatal
host/runtime errors, a missing window, or a presentation timeout. A recoverable
failure can leave the previous frame available through presented_tree().
A recoverable window-sync failure, such as a rejected native resize, is
superseded when the same revision then presents at the unchanged native size:
present() returns that frame's revision and no longer reports the failure.
Assert the native state (window_size, window_title) for that case, as
rejected_native_resize_keeps_committed_window_until_update_succeeds does.
A minimized window cannot produce a usable frame. Use run_host_turn() for its
measurement/observer work instead of waiting on present(). There is no final
JS barrier after a successful presentation: use eval to inspect callbacks
queued by that frame, or another host turn to process their UI mutations.
send_window_event(&mut self, id, event) -> Result<(), BurokkuError> #
Synchronously sends a WindowEvent, a change to the window's own life such
as Resized, RedrawRequested, Focused, or CloseRequested, through the
normal host event handler. For a known test window, it first applies
size/scale changes to its native state. The host then checks the window
identity and routes the event. IDs that do not identify the active window
are ignored by that handler.
This takes a native WindowId, not a UI-tree NodeId. A <window> node has a
NodeId; the host separately maps it to a native window instance. Keeping the
native ID lets tests inject events from an old window after replacement.
A CloseRequested event fires the window element's cancelable close event,
as the close button does. Unless a listener cancels it, the window closes on
a later host turn while its element stays, so the app keeps running and
open() can reopen it.
send_input_event(&mut self, id, event) -> Result<(), BurokkuError> #
Synchronously sends an InputEvent, what the user gave the window with the
pointer, the wheel, or the keyboard, through the normal host input handler,
which queues it for the dispatch pipeline. It takes the same native
WindowId as send_window_event, and an ID that does not identify the
active window is ignored.
Pointer positions are physical coordinates. The host converts them using the
presented scene's scale, performs hit testing, and selects the target node.
Button masks describe the state after the event: left 1, right 2, middle 4,
and the corresponding bits for additional buttons. A KeyboardInput carries
the DOM key and code names the platform would have made, such as Tab
or ArrowDown; the test backend binds no keys, so a test that needs the
command a platform would bind to a key sends that Command itself, after
the key.
The call does not wait for queued JS listeners. Follow it with eval() to
inspect listener results, present() to render changes, or run_host_turn()
for one turn of host work. Before a usable frame exists, pointer targeting is
unavailable.
send_keyboard_event(&mut self, target: NodeId, event: KeyEvent) -> Result<(), BurokkuError> #
Queues keyboard input for a node in this application's tree using the normal
key translation and JavaScript event dispatch. Obtain its NodeId from
with_fixture; KeyEvent is exported by burokku::test. For example:
let target = app.with_fixture(|tree| {
ui_tree!(tree, <window><div var=target /></window>);
target
});
app.send_keyboard_event(target, burokku::test::KeyEvent {
state: ElementState::Pressed,
key: "A".into(),
code: "KeyA".into(),
key_code: 0,
repeat: false,
modifiers: Default::default(),
})?;
app.eval::<()>("").await?;
The event goes to the focused element when one has focus, as native keyboard
input does, and otherwise to the selected node, as event.target; it bubbles
through the target's ancestors. No native window or presented frame is
required, and this does not move focus. Missing or disconnected targets are
ignored at dispatch time. IDs must belong to this application's tree.
Like native input, it waits in the input queue for its turn, and a full
runtime queue delays it rather than dropping it; a closed one drops it with
a warning. Follow the call with eval() to inspect listeners and their
microtasks. Use send_input_event(..., InputEvent::KeyboardInput(...)) to test
native window routing, which targets the window node, and so the focused
element, or the window when nothing has focus.
text_input_context(&self) -> Option<TextInputContext> #
What the platform's text system was last told of the focused editable
element through the current window, as the host applied it at the end of
its turn: None while nothing editable has focus. The caret and
composition bounds are scaled to the window's physical pixels.
set_clipboard_text(&self, text: Option<&str>) #
Puts text on the memory clipboard, as another app would, or empties it,
for a Paste command to read.
run_gc(&self) -> Result<(), BurokkuError> #
Runs one QuickJS garbage-collection pass on the runtime thread and waits for
it. Use it before run_host_turn() when a test must prove that a detached
node survives, or is reclaimed, once JavaScript keeps or drops its wrapper.
It does not reclaim nodes itself; idle maintenance on the next host turn does.
Reference counting already frees a wrapper when its last reference drops, so the
pass matters only for wrappers that a reference cycle keeps alive, such as a
listener that captures its own node.
Inspecting windows and frames #
| Function | Result and behavior |
|---|---|
window_id() -> Option<WindowId> |
ID of the current committed native window. It can exist before graphics is ready. Returns None when no window is active. |
window_title() -> Option<String> |
Copy of the current native window title. A JS attribute change becomes visible here after host reconciliation. |
window_size() -> Option<PhysicalSize<u32>> |
Current native physical dimensions, including zero dimensions when minimized. It does not report logical CSS dimensions. |
window_state(id) -> Option<Rc<HeadlessWindow>> |
Shared state of a window created by this backend, including an old or closed one. Returns None for an unknown ID. |
renderer_mut() -> Result<RefMut<TestRenderer>, BurokkuError> |
Mutable access to the installed renderer. Returns Host("renderer is not ready") if none exists. Drop the borrow before calling another client operation or awaiting work. |
presented_tree() -> Result<LayerTree, BurokkuError> |
The layer tree that the current window's layer surface shows for the currently usable frame. Returns a host error if no usable frame exists. It does not render or change the presented revision. |
presented_viewport() -> Option<Viewport> |
The logical size and scale factor of the current window's last presentation. |
presented_backgrounds() -> Result<Vec<Rgba8>, BurokkuError> |
The background colors of presented_tree()'s layers, back to front. A quick check of which boxes paint, in which order. |
presented_tree() rebuilds the tree from the changesets the surface applied,
so it is what a platform compositor would show. Layers are in logical units,
back to front. Each scroll container becomes a clipping layer holding one
content layer that the scroll offset moves; text draws as an image layer
whose contents holds the paragraph's pixels at the window's scale. Find a
node's layers by key: the key's id is the node's slot-map key, and its
part names the background, border, text, custom layer, thumb, scroll
group, or an item an element's instance painted (see
crates/core/src/ui/scene/layers.rs). A custom layer is attached with a
NativeLayer::Headless host, so tests check its placement and its attach and
detach calls, not what it draws.
HeadlessWindow state and functions #
window_state exposes the same fixture used by native tests:
| Field | Meaning |
|---|---|
size: Cell<PhysicalSize<u32>> |
Current physical size. |
scale: Cell<f64> |
Current display scale; initially 1.0. |
closed: Cell<bool> |
Whether the window has been closed. |
close_calls: Cell<usize> |
Number of close calls, including repeated calls. Used to check candidate cleanup happens exactly once. |
reject_resize: Cell<bool> |
While true, native set_inner_size returns an injected error before changing size or requesting redraw. This is separate from renderer resize failure. |
redraws: Cell<usize> |
Count of redraw requests, not rendered frames. Multiple requests can coalesce into one queued redraw event. |
Direct field mutations do not dispatch host events. They are useful for injecting
invalid native state. For normal resize/scale scenarios, use
send_window_event so the state update and host notification stay together.
| Function | Behavior |
|---|---|
HeadlessWindow::create(attributes, wake) |
Creates a Window plus its shared headless state, with a unique native ID, requested title, rounded initial size, and one pending redraw. The redraw-request counter starts at zero. The backend normally calls this. |
id() |
Returns this window's native ID. |
title() |
Returns a copy of its current title. |
apply_event(event) |
Updates size for Resized, and size plus scale for ScaleFactorChanged. Other events leave these fields unchanged. Does not dispatch to the host. |
take_events() |
Drains a pending resize and redraw, in that order. Returns no events for a closed window. The test driver normally calls it; calling it manually consumes those notifications. |
layers() |
The MemoryLayers its layer surfaces present into: tree(), viewport(), commits(), image_count(), and fail_next(error) to fail the next changeset. |
Its WindowBackend implementation supplies inner_size() and scale_factor()
from the cells. request_redraw() increments the counter, sets a pending redraw,
and wakes the driver. set_title() changes the stored title.
set_inner_size() rejects the request when reject_resize is set; otherwise it
converts logical dimensions using the scale, queues a resize, and requests a redraw. close() marks the state closed and wakes the driver.
window_handle() and display_handle() return HandleError::Unavailable.
layer_surface() returns a MemorySurface over layers(); it panics when a
changeset breaks the order or invariants that native::compositor::Changeset
documents.
Normal Window::set_inner_size() validates positive finite logical dimensions
before invoking the backend.
Failure controls #
The client exposes three one-shot controls:
| Function | Effect |
|---|---|
fail_next_window_creation() |
Rejects the next window creation with a native window-creation error. Existing windows are unaffected until the host processes the next requested change. |
fail_next_graphics_initialization() |
Makes the next spawned graphics initialization return a GraphicsError::Surface failure. It does not modify a task already spawned. Arm it before creating or replacing a window. |
fail_next_presentation() -> Result<(), BurokkuError> |
Arms the installed renderer's next presentation failure. Returns an error if the renderer is not ready. |
For an initial-creation failure, start with a windowless script, arm the control,
and create the window with eval. For replacement failures, arm the control
before changing the UI tree's window declaration.
renderer_mut() exposes the existing renderer controls directly:
| Field | Effect |
|---|---|
fail_next_resize |
The next renderer resize returns TargetTooLarge with a reported limit of 32, then clears the flag. This is a recoverable candidate error once the renderer has presented a frame, at any size. |
fail_next_present |
The next renderer presentation returns TestRenderer::injected_present_error(), then clears the flag. An active presentation failure is fatal to the host. |
next_outcome |
Returns an injected outcome once, without presenting. Use Timeout, Occluded, or Reconfigure; the last also makes the compositor forget its layers, as a lost surface does, and invalidates its presentation identity. |
presentations |
Number of presentation attempts, including failed and skipped attempts. |
Leave next_outcome as None for actual successful rendering. Injecting
Presented { revision } does not render or record that revision and therefore
cannot establish the host's normal presentation invariant.
The following example shares the imports from the JavaScript application example above:
#[test]
fn timeout_keeps_the_previous_frame() -> Result<(), BurokkuError> {
Burokku::builder()
.with_backend::<TestBackend>()
.script("app.appendChild(app.createElement('window'))")
.run_test(|mut app| async move {
app.present().await?;
let id = app.window_id().unwrap();
let window = app.window_state(id).unwrap();
let presented = app.presented_tree()?;
let redraws = window.redraws.get();
app.renderer_mut()?.next_outcome =
Some(burokku::test::PresentationOutcome::Timeout);
app.send_window_event(id, WindowEvent::RedrawRequested)?;
assert!(window.redraws.get() > redraws);
assert_eq!(app.presented_tree()?, presented);
app.present().await?;
Ok(())
})
}
Use send_window_event(..., RedrawRequested) to observe one attempted redraw
before automatic retries are processed. present() may process several turns
and retries before returning.
Test renderer functions #
burokku::test::TestRenderer wraps a real native::compositor::WindowCompositor
with the failure controls above. For application behavior, normally let
TestApp drive it through the host. Calling it directly bypasses host
reconciliation and geometry publication.
| Function | Behavior |
|---|---|
for_window(window).await |
Attaches a compositor to an existing Rc<Window> through its layer surface. Returns UnsupportedSurface for a window that cannot host one. |
injected_present_error() |
The error that an armed fail_next_present returns. |
Its RendererBackend implementation, with Context = (), applies the one-shot
controls and otherwise delegates to the compositor: resize records the new
size and keeps the presented layers, and present diffs the layer tree into a
changeset for the window's surface and records the revision on success.
The native fixture module also provides native::test::window(backend) to wrap
a custom WindowBackend with a unique ID, and window_without_handles(size) to
create a headless window with a no-op wake callback. These helpers are used by
lower-level tests; they do not start an application or JavaScript runtime.
Internal host test functions #
These are crate-internal implementation details, not extra public client APIs.
They reuse the native fixtures described above. Their fields and behavior do not
change between unit-test and feature-enabled builds. create_calls counts window
creation attempts, and first_window_closed_at_spawn records whether the first
window was already closed when each graphics task started, preserving close-before-spawn
ordering checks.
| Function | Responsibility |
|---|---|
TestEffects::new(manual_graphics) |
Creates the host effects. The application client passes false; focused lifecycle tests can pass true to control completion explicitly. |
TestEffects::create_window(attributes) |
Consumes a pending creation failure or creates and records a shared HeadlessWindow with the driver's wake callback. |
TestEffects::create_renderer(context, window) |
Returns an injected renderer error if armed; otherwise returns UnsupportedSurface to select asynchronous initialization for the new test renderer. |
TestEffects::spawn_graphics(window) |
Records the window and returns a result receiver plus an abort-on-drop task. Normally it initializes a test renderer and notifies the driver. In manual mode it retains the sender and leaves completion to the test. |
TestEffects::wake_callback() |
Returns an observer wake callback that increments wakes and notifies the driver. |
TestEffects::exit() |
Increments the exit count and notifies the driver. |
TestDriver::check() |
Converts an existing fatal host error or failed runtime status into BurokkuError::Host. |
TestDriver::tick() |
Calls prepare_to_wait, drains each headless window's queued events through the host handler, then checks for failure. It is the Rust host portion of run_host_turn and present. |
In the native fixtures, next_id() allocates unique test window IDs from an
atomic counter. It does not duplicate application policy.
When tests use lower-level fixtures #
Use TestApp for normal application behavior and with_fixture for Rust
fixture construction. Focused tests still drive internal operations when they
must:
- Hold graphics completion pending, inject stale results, or inspect cancellation:
use shared
TestEffects::new(true)and its result senders. - Exercise synchronous renderer reuse: the reconciliation fixture supplies a
minimal compatible renderer, delegates window creation to
TestEffects, and rejects unexpected asynchronous initialization. - Observe renderer destruction before window closure: keep the dedicated drop
probes; a later
closedflag cannot establish destruction order. - Force queue saturation, conflicting tree borrows, or inconsistent renderer identities: retain direct control over that internal boundary.
JavaScript input, observer, plugin, and cleanup tests still run JavaScript for the behavior they verify. Pure tree construction and mutation can use Rust even when the assertions inspect JS-visible geometry or event delivery.
Running tests and locating examples #
cargo test -p burokku-core --lib ui::host::
cargo test -p burokku-example-counter --test counter
cargo test --workspace
The counter's development dependency enables test-support automatically for
its integration test. Other consumers must enable it in their own manifest.
Source and behavior examples: