Skip to main content

day_core/
conformance.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Tests that run inside a built Day app (docs/testing.md): a [`Case`] is a page plus a drive,
5//! or a headless run, declared next to the code it tests with `#[day::test]` and collected in a
6//! registry. The dayscript engine runs them on a real toolkit under `day test`; the mock
7//! harness runs the same functions under `cargo test`. Nothing here knows how a step is
8//! executed: a [`DriveBackend`] does, and the engine supplies one.
9//!
10//! A test's name is its function's, with hyphens for underscores (`button_status` runs as
11//! `button-status`): the registry entry carries the identifier, so a tool reading the source
12//! (`day test --list`, an editor) and the app agree without either one running the other.
13
14use std::cell::RefCell;
15use std::future::Future;
16use std::pin::Pin;
17use std::rc::Rc;
18
19use day_spec::Cap;
20
21use crate::AnyPiece;
22
23/// A failed assertion, with the sentence the report shows.
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct Fail(pub String);
26
27impl std::fmt::Display for Fail {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        f.write_str(&self.0)
30    }
31}
32
33impl From<String> for Fail {
34    fn from(s: String) -> Self {
35        Fail(s)
36    }
37}
38
39impl From<&str> for Fail {
40    fn from(s: &str) -> Self {
41        Fail(s.to_owned())
42    }
43}
44
45/// What a test's body answers.
46pub type TestResult = Result<(), Fail>;
47
48/// What a drive asks of the app, in dayscript's vocabulary. The engine maps each to the step
49/// a script would send, so a drive and a script mean the same thing by the same words.
50#[derive(Clone, Debug, PartialEq)]
51pub enum DriveOp {
52    Tap(String),
53    Input(String, String),
54    Toggle(String, bool),
55    SetValue(String, f64),
56    Select(String, usize),
57    Focus(String),
58    Submit(String),
59    Navigate(String),
60    WaitIdle,
61    Pause(f64),
62    /// Capture the window under this name into the test's record.
63    Shot(String),
64    AssertText(String, String),
65    AssertVisible(String),
66    AssertMissing(String),
67    /// That an element is not on screen: missing, empty, or natively hidden.
68    AssertHidden(String),
69    /// A pointer entering an element, at a point in it or (for `None`) its center.
70    Hover(String, Option<(f64, f64)>),
71    /// The pointer leaving an element.
72    HoverLeave(String),
73    /// A two-finger pan over an element, by this much in total.
74    Pan(String, f64, f64),
75    /// A pinch over an element, to this cumulative scale.
76    Pinch(String, f64),
77    /// A two-finger rotation over an element, to this cumulative angle in radians.
78    Rotate(String, f64),
79    /// A drag over an element, from one point to another in its coordinates.
80    Drag(String, (f64, f64), (f64, f64)),
81    /// A tap at a point in an element's coordinates.
82    TapAt(String, f64, f64),
83    /// A key press, to an element or (for `None`) to whatever holds focus.
84    Key(Option<String>, String),
85    /// A key in a given phase (`"down"`, `"repeat"`, `"up"`), to an element or to focus.
86    KeyPhase(Option<String>, String, String),
87    /// A press going down on an element (`true`) or ending (`false`).
88    Press(String, bool),
89    /// A long press on an element.
90    LongPress(String),
91    /// A double tap on an element.
92    DoubleTap(String),
93    /// Contacts on an element, one per point, all in one phase (`"began"`, `"moved"`,
94    /// `"ended"`, `"cancelled"`).
95    Touches(String, Vec<(f64, f64)>, String),
96    /// A drag over an element that the platform's recognizer released at this velocity.
97    Fling(String, (f64, f64), (f64, f64), (f64, f64)),
98    /// The kind of pointer in use changing (`"touch"`, `"mouse"`, `"stylus"`).
99    Pointer(String),
100    /// A drag session over an element's drop target carrying text, in one phase (`"enter"`,
101    /// `"leave"`, `"drop"`).
102    DropText(String, String, String),
103    /// Files dropped on an element's drop target.
104    DropFiles(String, Vec<String>),
105    /// That the app announced this text to the screen reader during the run.
106    AssertAnnounced(String),
107    AssertValue(String, f64),
108    /// A toggle's state.
109    AssertOn(String, bool),
110    AssertFocused(String, bool),
111    AssertRoute(String),
112    A11yAudit(Option<String>),
113    /// The native widget's own state, as the platform reports it.
114    AssertNative(String, NativeExpect),
115    /// An element's frame, in Day's layout and natively.
116    AssertFrame(String, FrameExpect),
117    /// What an element shows at this moment, mid-animation included.
118    AssertDisplayed(String, DisplayedExpect),
119    /// The color at a point of an element (fractions of its frame), `#rrggbb`.
120    SamplePixel(String, f64, f64, String),
121    /// A URL the app asked to open during the run.
122    AssertOpenedUrl(String),
123    /// Activate a list's row (a double click, Return, a tap on the phones), by position.
124    Activate(String, usize),
125    /// Move a list's row from one position to another, as a drag-to-reorder commits it.
126    Reorder(String, usize, usize),
127    /// Delete a list's row, as the platform's delete gesture commits it.
128    DeleteRow(String, usize),
129    /// Press a row's swipe action: the list, the row, the edge (`true` = leading) and the
130    /// action's position in that edge's offer.
131    SwipeRow(String, usize, bool, usize),
132    /// Scroll a scroll view or list to an edge (`"top"`, `"bottom"`, `"leading"`, `"trailing"`).
133    ScrollTo(String, String),
134    /// Expand or collapse a tree's row, named by its row id.
135    Expand(String, String, bool),
136    /// Go back one page in the innermost navigation stack.
137    NavBack,
138    /// Move a tree's row (by row id) under a parent (`None` = the root) at a position.
139    TreeMove(String, String, Option<String>, Option<usize>),
140    /// Choose an item, by label, from an element's context menu.
141    ContextMenu(String, String),
142    /// Choose an app-menu item by its id.
143    Menu(String),
144    /// Press a toolbar button, by item id.
145    ToolbarPress(String),
146    /// Set a toolbar toggle, by item id.
147    ToolbarToggle(String, bool),
148    /// Answer presentations natively (`false`) or hold them for `respond` (`true`).
149    DialogScripted(bool),
150    /// That a presentation is pending, with this title where one is given.
151    AssertPresented(Option<String>),
152    /// Answer the pending presentation: a button by position, or dismiss it (`None`).
153    Respond(Option<usize>),
154    /// Confirm a prompt with text (including an empty string).
155    RespondText(String),
156}
157
158/// What [`Drive::assert_frame`] expects of an element's frame, in points; only the fields set
159/// are checked. `x`/`y` are relative to `relative_to`'s origin, or the window content's.
160#[derive(Clone, Debug, Default, PartialEq)]
161pub struct FrameExpect {
162    pub width: Option<f64>,
163    pub height: Option<f64>,
164    pub x: Option<f64>,
165    pub y: Option<f64>,
166    /// The element whose origin `x`/`y` are measured from.
167    pub relative_to: Option<String>,
168    /// How far each value may be off (default 1 point).
169    pub tolerance: Option<f64>,
170}
171
172/// What [`Drive::assert_native`] expects the native widget to report; only the fields set are
173/// checked (docs/testing.md).
174#[derive(Clone, Debug, Default, PartialEq)]
175pub struct NativeExpect {
176    /// The text the widget displays.
177    pub text: Option<String>,
178    /// A slider's or progress indicator's value.
179    pub number: Option<f64>,
180    /// A toggle's state, or a button's selected state.
181    pub checked: Option<bool>,
182    /// Whether the widget takes input.
183    pub enabled: Option<bool>,
184    /// Whether the widget is shown.
185    pub visible: Option<bool>,
186}
187
188/// What [`Drive::assert_displayed`] expects an element to show at this moment; only the fields
189/// set are checked (docs/testing.md). Unlike the other assertions this one is read once and
190/// not retried: a value in flight is only right at the moment it is asked for.
191#[derive(Clone, Debug, Default, PartialEq)]
192pub struct DisplayedExpect {
193    /// The opacity shown, the element's own times its ancestors'.
194    pub opacity: Option<f64>,
195    /// The translation shown, in points: the element's own plus its ancestors'.
196    pub translation: Option<day_spec::Point>,
197    /// The width of the frame shown, in points.
198    pub width: Option<f64>,
199    /// The height of the frame shown, in points.
200    pub height: Option<f64>,
201    /// The background color shown by the element or the nearest surface around it.
202    pub background: Option<day_spec::Color>,
203    /// How far each value may be off, in its own unit: opacity and color channels in `0..=1`
204    /// (default 0.05), lengths in points (default 1).
205    pub tolerance: Option<f64>,
206}
207
208/// The future one drive op resolves to.
209pub type OpFuture = Pin<Box<dyn Future<Output = TestResult>>>;
210
211/// Executes [`DriveOp`]s. The engine's backend runs each as the matching dayscript step on the
212/// main thread and waits, asynchronously, through the step's retry window; the mock harness
213/// uses the same backend against the mock toolkit.
214pub trait DriveBackend {
215    fn run(&self, op: DriveOp) -> OpFuture;
216}
217
218/// The handle a test drives the app with. Every method awaits the op and fails the test with
219/// the step's own message when the op fails after its retry window.
220#[derive(Clone)]
221pub struct Drive {
222    backend: Rc<dyn DriveBackend>,
223}
224
225impl Drive {
226    /// A drive over `backend`; the engine and the mock harness build one per test.
227    pub fn new(backend: Rc<dyn DriveBackend>) -> Self {
228        Drive { backend }
229    }
230
231    fn op(&self, op: DriveOp) -> OpFuture {
232        self.backend.run(op)
233    }
234
235    pub fn tap(&self, id: &str) -> OpFuture {
236        self.op(DriveOp::Tap(id.into()))
237    }
238    /// Type `text` into the field, replacing what it holds.
239    pub fn input(&self, id: &str, text: &str) -> OpFuture {
240        self.op(DriveOp::Input(id.into(), text.into()))
241    }
242    pub fn toggle(&self, id: &str, on: bool) -> OpFuture {
243        self.op(DriveOp::Toggle(id.into(), on))
244    }
245    pub fn set_value(&self, id: &str, value: f64) -> OpFuture {
246        self.op(DriveOp::SetValue(id.into(), value))
247    }
248    pub fn select(&self, id: &str, index: usize) -> OpFuture {
249        self.op(DriveOp::Select(id.into(), index))
250    }
251    pub fn focus(&self, id: &str) -> OpFuture {
252        self.op(DriveOp::Focus(id.into()))
253    }
254    pub fn submit(&self, id: &str) -> OpFuture {
255        self.op(DriveOp::Submit(id.into()))
256    }
257    pub fn navigate(&self, route: &str) -> OpFuture {
258        self.op(DriveOp::Navigate(route.into()))
259    }
260    /// Let native transitions settle.
261    pub fn wait_idle(&self) -> OpFuture {
262        self.op(DriveOp::WaitIdle)
263    }
264    pub fn pause(&self, secs: f64) -> OpFuture {
265        self.op(DriveOp::Pause(secs))
266    }
267    /// Capture the window as `name`; the capture rides the test's record to the runner.
268    pub fn shot(&self, name: &str) -> OpFuture {
269        self.op(DriveOp::Shot(name.into()))
270    }
271    pub fn assert_text(&self, id: &str, text: &str) -> OpFuture {
272        self.op(DriveOp::AssertText(id.into(), text.into()))
273    }
274    pub fn assert_visible(&self, id: &str) -> OpFuture {
275        self.op(DriveOp::AssertVisible(id.into()))
276    }
277    pub fn assert_missing(&self, id: &str) -> OpFuture {
278        self.op(DriveOp::AssertMissing(id.into()))
279    }
280    /// The pointer entering `id` at (`x`, `y`) in its coordinates (its center for `None`).
281    pub fn hover(&self, id: &str, at: Option<(f64, f64)>) -> OpFuture {
282        self.op(DriveOp::Hover(id.into(), at))
283    }
284    /// The pointer leaving `id`.
285    pub fn hover_leave(&self, id: &str) -> OpFuture {
286        self.op(DriveOp::HoverLeave(id.into()))
287    }
288    /// A two-finger pan over `id` by (`dx`, `dy`) in total.
289    pub fn pan(&self, id: &str, dx: f64, dy: f64) -> OpFuture {
290        self.op(DriveOp::Pan(id.into(), dx, dy))
291    }
292    /// A pinch over `id` to `scale` (cumulative; 1 = unchanged).
293    pub fn pinch(&self, id: &str, scale: f64) -> OpFuture {
294        self.op(DriveOp::Pinch(id.into(), scale))
295    }
296    /// A two-finger rotation over `id` to `rotation` radians (cumulative; positive clockwise).
297    pub fn rotate(&self, id: &str, rotation: f64) -> OpFuture {
298        self.op(DriveOp::Rotate(id.into(), rotation))
299    }
300    /// A pointer drag over `id` from `from` to `to`, in its coordinates.
301    pub fn drag(&self, id: &str, from: (f64, f64), to: (f64, f64)) -> OpFuture {
302        self.op(DriveOp::Drag(id.into(), from, to))
303    }
304    /// A tap at (`x`, `y`) in `id`'s coordinates.
305    pub fn tap_at(&self, id: &str, x: f64, y: f64) -> OpFuture {
306        self.op(DriveOp::TapAt(id.into(), x, y))
307    }
308    /// A key press (web `KeyboardEvent.key` names: `"Enter"`, `"ArrowRight"`, `"a"`) to `id`,
309    /// or to whatever holds focus for `None`.
310    pub fn key(&self, id: Option<&str>, key: &str) -> OpFuture {
311        self.op(DriveOp::Key(id.map(str::to_owned), key.into()))
312    }
313    /// A key in one phase of its press (`KeyPhase::Repeat` for auto-repeat, `KeyPhase::Up`
314    /// for the release) to `id`, or to whatever holds focus for `None`.
315    pub fn key_phase(&self, id: Option<&str>, key: &str, phase: day_spec::KeyPhase) -> OpFuture {
316        let phase = match phase {
317            day_spec::KeyPhase::Down => "down",
318            day_spec::KeyPhase::Repeat => "repeat",
319            day_spec::KeyPhase::Up => "up",
320        };
321        self.op(DriveOp::KeyPhase(
322            id.map(str::to_owned),
323            key.into(),
324            phase.into(),
325        ))
326    }
327    /// The pointer going down on `id` (`pressed: true`) or the press ending.
328    pub fn press(&self, id: &str, pressed: bool) -> OpFuture {
329        self.op(DriveOp::Press(id.into(), pressed))
330    }
331    /// A long press on `id`, at its center.
332    pub fn long_press(&self, id: &str) -> OpFuture {
333        self.op(DriveOp::LongPress(id.into()))
334    }
335    /// A double tap on `id`, at its center.
336    pub fn double_tap(&self, id: &str) -> OpFuture {
337        self.op(DriveOp::DoubleTap(id.into()))
338    }
339    /// Contacts on `id`, one per point (ids count from 0), all in `phase`.
340    pub fn touches(
341        &self,
342        id: &str,
343        points: &[(f64, f64)],
344        phase: day_spec::TouchPhase,
345    ) -> OpFuture {
346        let phase = match phase {
347            day_spec::TouchPhase::Began => "began",
348            day_spec::TouchPhase::Moved | day_spec::TouchPhase::Stationary => "moved",
349            day_spec::TouchPhase::Ended => "ended",
350            day_spec::TouchPhase::Cancelled => "cancelled",
351        };
352        self.op(DriveOp::Touches(id.into(), points.to_vec(), phase.into()))
353    }
354    /// A drag over `id` from `from` to `to` that the platform's recognizer released at
355    /// `velocity` points per second.
356    pub fn fling(
357        &self,
358        id: &str,
359        from: (f64, f64),
360        to: (f64, f64),
361        velocity: (f64, f64),
362    ) -> OpFuture {
363        self.op(DriveOp::Fling(id.into(), from, to, velocity))
364    }
365    /// The kind of pointer in use changing, as the platform reports it.
366    pub fn pointer(&self, kind: day_spec::PointerKind) -> OpFuture {
367        self.op(DriveOp::Pointer(kind.name().into()))
368    }
369    /// A drag carrying `text` coming over `id`'s drop target.
370    pub fn drag_enter(&self, id: &str, text: &str) -> OpFuture {
371        self.op(DriveOp::DropText(id.into(), text.into(), "enter".into()))
372    }
373    /// The drag leaving `id`'s drop target without dropping.
374    pub fn drag_leave(&self, id: &str) -> OpFuture {
375        self.op(DriveOp::DropText(id.into(), String::new(), "leave".into()))
376    }
377    /// `text` dropped on `id`'s drop target.
378    pub fn drop_text(&self, id: &str, text: &str) -> OpFuture {
379        self.op(DriveOp::DropText(id.into(), text.into(), "drop".into()))
380    }
381    /// Files (local paths) dropped on `id`'s drop target.
382    pub fn drop_files(&self, id: &str, paths: &[&str]) -> OpFuture {
383        self.op(DriveOp::DropFiles(
384            id.into(),
385            paths.iter().map(|p| (*p).to_owned()).collect(),
386        ))
387    }
388    /// That the app announced `text` to the screen reader during the run.
389    pub fn assert_announced(&self, text: &str) -> OpFuture {
390        self.op(DriveOp::AssertAnnounced(text.into()))
391    }
392    /// That an element is not on screen: missing, with an empty frame, or hidden natively (a
393    /// collapsed pane a toolkit keeps built).
394    pub fn assert_hidden(&self, id: &str) -> OpFuture {
395        self.op(DriveOp::AssertHidden(id.into()))
396    }
397    pub fn assert_value(&self, id: &str, value: f64) -> OpFuture {
398        self.op(DriveOp::AssertValue(id.into(), value))
399    }
400    /// A toggle's on/off state.
401    pub fn assert_on(&self, id: &str, on: bool) -> OpFuture {
402        self.op(DriveOp::AssertOn(id.into(), on))
403    }
404    pub fn assert_focused(&self, id: &str, focused: bool) -> OpFuture {
405        self.op(DriveOp::AssertFocused(id.into(), focused))
406    }
407    pub fn assert_route(&self, route: &str) -> OpFuture {
408        self.op(DriveOp::AssertRoute(route.into()))
409    }
410    /// Diff the native accessibility tree against Day's expectation for `id` (all id'd
411    /// nodes when `None`), where the toolkit can read its tree back.
412    pub fn a11y_audit(&self, id: Option<&str>) -> OpFuture {
413        self.op(DriveOp::A11yAudit(id.map(str::to_owned)))
414    }
415
416    /// The native widget's own state, as the platform reports it (docs/testing.md). A field
417    /// the toolkit cannot read is recorded in the report as unread rather than failed. In a
418    /// conformance run `assert_text`, `assert_value` and `assert_on` check the native widget
419    /// too; this is for what they do not cover.
420    pub fn assert_native(&self, id: &str, expect: NativeExpect) -> OpFuture {
421        self.op(DriveOp::AssertNative(id.into(), expect))
422    }
423    /// The element's frame in Day's layout and, where the toolkit reads it back, natively.
424    pub fn assert_frame(&self, id: &str, expect: FrameExpect) -> OpFuture {
425        self.op(DriveOp::AssertFrame(id.into(), expect))
426    }
427    /// What the element shows at this moment, an animation's in-between state included
428    /// (`Toolkit::read_displayed`, docs/testing.md). Read once, with no retry. A field the
429    /// toolkit cannot observe mid-flight is recorded in the report as unread rather than
430    /// failed.
431    pub fn assert_displayed(&self, id: &str, expect: DisplayedExpect) -> OpFuture {
432        self.op(DriveOp::AssertDisplayed(id.into(), expect))
433    }
434    /// The element's size, the common case of [`Drive::assert_frame`].
435    pub fn assert_size(&self, id: &str, width: f64, height: f64) -> OpFuture {
436        self.assert_frame(
437            id,
438            FrameExpect {
439                width: Some(width),
440                height: Some(height),
441                ..Default::default()
442            },
443        )
444    }
445    /// The color drawn at (`x`, `y`), fractions of the element's frame, as `#rrggbb`. Passes as
446    /// unread where the toolkit has no capture.
447    pub fn sample_pixel(&self, id: &str, x: f64, y: f64, color: &str) -> OpFuture {
448        self.op(DriveOp::SamplePixel(id.into(), x, y, color.into()))
449    }
450    /// That the app asked to open `url` (a link, `day::open_url`) during the run; in a run
451    /// nothing actually opens.
452    pub fn assert_opened_url(&self, url: &str) -> OpFuture {
453        self.op(DriveOp::AssertOpenedUrl(url.into()))
454    }
455    /// Whether the element takes input, in Day's tree and in the native widget.
456    pub fn assert_enabled(&self, id: &str, enabled: bool) -> OpFuture {
457        self.assert_native(
458            id,
459            NativeExpect {
460                enabled: Some(enabled),
461                ..Default::default()
462            },
463        )
464    }
465
466    /// Activate a list's row by position: what a double click, Return or a phone's tap commits.
467    pub fn activate(&self, id: &str, index: usize) -> OpFuture {
468        self.op(DriveOp::Activate(id.into(), index))
469    }
470    /// Move a list's row from `from` to `to`, as a native drag-to-reorder commits it.
471    pub fn reorder(&self, id: &str, from: usize, to: usize) -> OpFuture {
472        self.op(DriveOp::Reorder(id.into(), from, to))
473    }
474    /// Delete a list's row, as the platform's delete gesture commits it.
475    pub fn delete_row(&self, id: &str, row: usize) -> OpFuture {
476        self.op(DriveOp::DeleteRow(id.into(), row))
477    }
478    /// Press the `action`th swipe action on a list row's leading or trailing edge.
479    pub fn swipe_row(&self, id: &str, row: usize, leading: bool, action: usize) -> OpFuture {
480        self.op(DriveOp::SwipeRow(id.into(), row, leading, action))
481    }
482    /// Scroll a scroll view or list to an edge: `"top"`, `"bottom"`, `"leading"`, `"trailing"`.
483    pub fn scroll_to(&self, id: &str, edge: &str) -> OpFuture {
484        self.op(DriveOp::ScrollTo(id.into(), edge.into()))
485    }
486    /// Reveal element `id` in its nearest scroll, or the list row it sits in: the dayscript
487    /// `scroll_to` step with no edge.
488    pub fn reveal(&self, id: &str) -> OpFuture {
489        self.op(DriveOp::ScrollTo(id.into(), String::new()))
490    }
491    /// Expand or collapse a tree's row, named by its row id.
492    pub fn expand(&self, id: &str, row: &str, expanded: bool) -> OpFuture {
493        self.op(DriveOp::Expand(id.into(), row.into(), expanded))
494    }
495    /// Go back one page in the innermost navigation stack.
496    pub fn nav_back(&self) -> OpFuture {
497        self.op(DriveOp::NavBack)
498    }
499    /// Move a tree's row (by row id) under `parent` (`None` = the root level), at `index` among
500    /// its new siblings (`None` = last), as a native drag commits it.
501    pub fn tree_move(
502        &self,
503        id: &str,
504        row: &str,
505        parent: Option<&str>,
506        index: Option<usize>,
507    ) -> OpFuture {
508        self.op(DriveOp::TreeMove(
509            id.into(),
510            row.into(),
511            parent.map(str::to_owned),
512            index,
513        ))
514    }
515
516    /// Choose the item labeled `item` from `id`'s context menu, as a right click (or long
517    /// press) and a choice would.
518    pub fn context_menu(&self, id: &str, item: &str) -> OpFuture {
519        self.op(DriveOp::ContextMenu(id.into(), item.into()))
520    }
521    /// Choose an app-menu item by the id the app gave it (`MenuEntry::id`).
522    pub fn menu(&self, item_id: &str) -> OpFuture {
523        self.op(DriveOp::Menu(item_id.into()))
524    }
525    /// Press the toolbar button `item`.
526    pub fn toolbar_press(&self, item: &str) -> OpFuture {
527        self.op(DriveOp::ToolbarPress(item.into()))
528    }
529    /// Turn the toolbar toggle `item` on or off.
530    pub fn toolbar_toggle(&self, item: &str, on: bool) -> OpFuture {
531        self.op(DriveOp::ToolbarToggle(item.into(), on))
532    }
533    /// Show presentations natively (`false`, the default) or hold them for
534    /// [`Drive::respond`] without any native dialog (`true`). In native mode `respond` still
535    /// answers, and the toolkit dismisses the dialog it showed.
536    pub fn dialogs_scripted(&self, scripted: bool) -> OpFuture {
537        self.op(DriveOp::DialogScripted(scripted))
538    }
539    /// That a dialog or picker is pending, titled `title` where one is given.
540    pub fn assert_presented(&self, title: Option<&str>) -> OpFuture {
541        self.op(DriveOp::AssertPresented(title.map(str::to_owned)))
542    }
543    /// Answer the pending dialog with the button at `button` (presentation order), or dismiss
544    /// it for `None`.
545    pub fn respond(&self, button: Option<usize>) -> OpFuture {
546        self.op(DriveOp::Respond(button))
547    }
548
549    /// Confirm a pending text prompt.
550    pub fn respond_text(&self, text: &str) -> OpFuture {
551        self.op(DriveOp::RespondText(text.into()))
552    }
553
554    /// A plain assertion for a headless test: fails with `what` when `ok` is false.
555    ///
556    /// # Errors
557    ///
558    /// Returns a [`Fail`] carrying `what` when `ok` is false.
559    pub fn check(&self, ok: bool, what: &str) -> TestResult {
560        if ok { Ok(()) } else { Err(Fail(what.into())) }
561    }
562    /// Equality for a headless test, naming both sides on a mismatch.
563    ///
564    /// # Errors
565    ///
566    /// Returns a [`Fail`] naming both values when they differ.
567    #[expect(
568        clippy::needless_pass_by_value,
569        reason = "public test-helper signature; callers pass temporaries by value"
570    )]
571    pub fn check_eq<T: PartialEq + std::fmt::Debug>(&self, got: T, want: T) -> TestResult {
572        if got == want {
573            Ok(())
574        } else {
575            Err(Fail(format!("{got:?} ≠ expected {want:?}")))
576        }
577    }
578}
579
580/// Whether a case shows a page and drives it, or runs with no page.
581#[derive(Clone, Copy, Debug, PartialEq, Eq)]
582pub enum TestKind {
583    Gui,
584    Headless,
585}
586
587type Body = Rc<dyn Fn(Drive) -> Pin<Box<dyn Future<Output = TestResult>>>>;
588
589/// One test: what it proves, what it needs, the page it shows and the body that drives it.
590/// Built by a `#[day::test]` function each time the test runs, so the signals a page and its
591/// drive share are fresh per run; the registry names it after that function.
592#[derive(Clone)]
593pub struct Case {
594    name: String,
595    kind: TestKind,
596    proves: Vec<String>,
597    requires: Vec<Cap>,
598    /// Supports the case needs beyond a `Cap`: a piece's own `support()` answer, named.
599    requires_support: Vec<(String, fn() -> day_spec::Support)>,
600    page: Option<Rc<dyn Fn() -> AnyPiece>>,
601    shots: Vec<String>,
602    body: Option<Body>,
603    timeout_secs: Option<f64>,
604}
605
606impl Default for Case {
607    fn default() -> Self {
608        Case::new()
609    }
610}
611
612impl Case {
613    /// A GUI case: a page the app's test host shows while the case runs, and a drive against it.
614    pub fn new() -> Self {
615        Case {
616            name: String::new(),
617            kind: TestKind::Gui,
618            proves: Vec::new(),
619            requires: Vec::new(),
620            requires_support: Vec::new(),
621            page: None,
622            shots: Vec::new(),
623            body: None,
624            timeout_secs: None,
625        }
626    }
627    /// A test with no page: app logic run inside the app's own environment.
628    pub fn headless() -> Self {
629        Case {
630            kind: TestKind::Headless,
631            ..Case::new()
632        }
633    }
634    /// How long the case may take, page and drive together, before it fails as timed out.
635    /// Unset, the run's default applies (30 s, or what `day test --case-timeout` says).
636    #[must_use]
637    pub fn timeout(mut self, secs: f64) -> Self {
638        self.timeout_secs = Some(secs);
639        self
640    }
641    /// The piece kind this case is the proof of (`kinds::BUTTON`); a pass marks the kind
642    /// on this toolkit in the coverage tables.
643    #[must_use]
644    pub fn proves(mut self, kind: &str) -> Self {
645        self.proves.push(format!("kind:{kind}"));
646        self
647    }
648    /// The capability this case proves.
649    #[must_use]
650    pub fn proves_cap(mut self, cap: Cap) -> Self {
651        self.proves.push(format!("cap:{cap:?}"));
652        self
653    }
654    /// The `Decorate` modifier this case proves (`"padding"`).
655    #[must_use]
656    pub fn proves_modifier(mut self, modifier: &str) -> Self {
657        self.proves.push(format!("modifier:{modifier}"));
658        self
659    }
660    /// The toolkit duty this case proves (`"set_input_traits"`).
661    #[must_use]
662    pub fn proves_duty(mut self, duty: &str) -> Self {
663        self.proves.push(format!("duty:{duty}"));
664        self
665    }
666    /// A capability the case needs; where the toolkit answers `Unsupported` the case is
667    /// skipped with that reason rather than failed. The one way a case adapts to a toolkit.
668    #[must_use]
669    pub fn requires(mut self, cap: Cap) -> Self {
670        self.requires.push(cap);
671        self
672    }
673    /// A piece's own support the case needs (`day_piece_map::support`), named for the skip
674    /// reason: where it answers `Unsupported` the case is skipped, as for [`Case::requires`].
675    /// For a piece realized only where its platform ships the widget.
676    #[must_use]
677    pub fn requires_support(mut self, what: &str, support: fn() -> day_spec::Support) -> Self {
678        self.requires_support.push((what.to_owned(), support));
679        self
680    }
681    /// The first support this case needs that the running toolkit lacks, named.
682    #[must_use]
683    pub fn missing_support(&self) -> Option<String> {
684        self.requires_support
685            .iter()
686            .find(|(_, f)| f() == day_spec::Support::Unsupported)
687            .map(|(what, _)| what.clone())
688    }
689    /// The page the app shows for this case; any piece.
690    #[must_use]
691    pub fn page<P: crate::Piece>(mut self, page: impl Fn() -> P + 'static) -> Self {
692        self.page = Some(Rc::new(move || AnyPiece::new(page())));
693        self
694    }
695    /// A capture taken before the drive runs, once the page is shown.
696    #[must_use]
697    pub fn shot(mut self, name: &str) -> Self {
698        self.shots.push(name.into());
699        self
700    }
701    /// The drive: an async body over a [`Drive`], awaiting each step so the app's main loop
702    /// runs between them (a transition settles, a capture paints) as it does between a
703    /// script's steps.
704    #[must_use]
705    pub fn drive<F>(mut self, body: impl Fn(Drive) -> F + 'static) -> Self
706    where
707        F: Future<Output = TestResult> + 'static,
708    {
709        self.body = Some(Rc::new(move |d| Box::pin(body(d))));
710        self
711    }
712    /// [`Case::drive`] under the name a headless test reads better with.
713    #[must_use]
714    pub fn run<F>(self, body: impl Fn(Drive) -> F + 'static) -> Self
715    where
716        F: Future<Output = TestResult> + 'static,
717    {
718        self.drive(body)
719    }
720
721    /// The name the registry gave the case: its function's, hyphenated. Empty for a case
722    /// built outside the registry.
723    #[must_use]
724    pub fn name(&self) -> &str {
725        &self.name
726    }
727    /// The case's own time limit, if it set one.
728    #[must_use]
729    pub fn timeout_secs(&self) -> Option<f64> {
730        self.timeout_secs
731    }
732    #[must_use]
733    pub fn kind(&self) -> TestKind {
734        self.kind
735    }
736    /// The `kind:`, `cap:` and `duty:` keys this case proves, in the matrices' own spelling.
737    #[must_use]
738    pub fn proves_keys(&self) -> &[String] {
739        &self.proves
740    }
741    #[must_use]
742    pub fn requirements(&self) -> &[Cap] {
743        &self.requires
744    }
745    /// The captures to take before the drive.
746    #[must_use]
747    pub fn shots(&self) -> &[String] {
748        &self.shots
749    }
750    /// Build the case's page, if it has one.
751    #[must_use]
752    pub fn build_page(&self) -> Option<AnyPiece> {
753        self.page.as_ref().map(|p| p())
754    }
755    /// Run the body over `drive`; a case with no body passes once its page showed.
756    pub fn run_body(&self, drive: Drive) -> Pin<Box<dyn Future<Output = TestResult>>> {
757        match &self.body {
758            Some(body) => body(drive),
759            None => Box::pin(async { Ok(()) }),
760        }
761    }
762}
763
764/// A registered test: the function that builds its [`Case`], and that function's identifier,
765/// which is where the test's name comes from. Declared by `#[day::test]`.
766#[derive(Clone, Copy)]
767pub struct TestFn {
768    ident: &'static str,
769    build: fn() -> Case,
770}
771
772impl TestFn {
773    /// An entry for `build`, named by `ident` (`stringify!` of the function or its path).
774    pub const fn new(ident: &'static str, build: fn() -> Case) -> Self {
775        TestFn { ident, build }
776    }
777    /// The test's name: the identifier's last path segment, with hyphens for underscores.
778    #[must_use]
779    pub fn name(&self) -> String {
780        let last = self.ident.rsplit("::").next().unwrap_or(self.ident);
781        last.trim().replace('_', "-")
782    }
783    /// A fresh case, named.
784    pub fn case(&self) -> Case {
785        let mut case = (self.build)();
786        case.name = self.name();
787        case
788    }
789}
790
791mod registry;
792pub use registry::validate_registry;
793#[cfg(target_arch = "wasm32")]
794pub use registry::{Registration, install_web_registry};
795
796/// Every native `#[day::test]`, collected without runtime constructors.
797#[cfg(not(target_arch = "wasm32"))]
798#[linkme::distributed_slice]
799pub static TESTS: [TestFn];
800
801/// What a test host does when the active case changes: rebuild its content.
802type HostNotify = Rc<dyn Fn()>;
803
804day_reactive::tls_slots! {
805    conformance;
806    static RUNTIME: RefCell<Vec<TestFn>> = const { RefCell::new(Vec::new()) };
807    /// The case the engine is driving, which the test host shows; its page shares its signals
808    /// with the drive.
809    static ACTIVE: RefCell<Option<Case>> = const { RefCell::new(None) };
810    /// The mounted test host's rebuild, when the app shows one (`day::test_host`).
811    static HOST: RefCell<Option<HostNotify>> = const { RefCell::new(None) };
812    /// A panic raised while the host built the active case's page, for the runner to report.
813    static PAGE_PANIC: RefCell<Option<String>> = const { RefCell::new(None) };
814    /// The URLs the app asked to open while a test run was going on, when one is.
815    static OPENED: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
816    /// What the app announced to the screen reader while a test run was going on, when one is.
817    static ANNOUNCED: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
818}
819
820/// Start or end a test run's interception of [`crate::open_url`]: while it is on, a URL the app
821/// asks to open is recorded instead of opened, so `assert_opened_url` can check it and no
822/// browser starts on the machine running the tests.
823pub fn set_intercepting_urls(on: bool) {
824    OPENED.with(|o| *o.borrow_mut() = on.then(Vec::new));
825    ANNOUNCED.with(|a| *a.borrow_mut() = on.then(Vec::new));
826}
827
828/// Record a screen-reader announcement if a test run is going on. Unlike a URL it still goes
829/// to the toolkit: announcing has no side effect a run must avoid, and the duty is what a case
830/// proves.
831pub fn note_announcement(text: &str) {
832    ANNOUNCED.with(|a| {
833        if let Some(list) = a.borrow_mut().as_mut() {
834            list.push(text.to_owned());
835        }
836    });
837}
838
839/// The announcements made since the run began.
840#[must_use]
841pub fn announcements() -> Vec<String> {
842    ANNOUNCED.with(|a| a.borrow().clone().unwrap_or_default())
843}
844
845/// Record `url` if a test run is intercepting; whether it did.
846#[must_use]
847pub fn intercept_open_url(url: &str) -> bool {
848    OPENED.with(|o| match o.borrow_mut().as_mut() {
849        Some(list) => {
850            list.push(url.to_owned());
851            true
852        }
853        None => false,
854    })
855}
856
857/// The URLs opened (and intercepted) since the run began.
858#[must_use]
859pub fn opened_urls() -> Vec<String> {
860    OPENED.with(|o| o.borrow().clone().unwrap_or_default())
861}
862
863/// Add a synthetic case in a test harness. Application tests use `#[day::test]`.
864pub fn register(test: TestFn) {
865    RUNTIME.with(|r| {
866        let mut r = r.borrow_mut();
867        if !r.iter().any(|t| std::ptr::fn_addr_eq(t.build, test.build)) {
868            r.push(test);
869        }
870    });
871}
872
873/// Every registered test, link-time and run-time ones together.
874#[must_use]
875pub fn tests() -> Vec<TestFn> {
876    let mut all: Vec<TestFn> = Vec::new();
877    all.extend(registry::compiled_tests());
878    RUNTIME.with(|r| {
879        for t in r.borrow().iter() {
880            if !all.iter().any(|a| std::ptr::fn_addr_eq(a.build, t.build)) {
881                all.push(*t);
882            }
883        }
884    });
885    all
886}
887
888/// Every registered test as a fresh, named [`Case`], sorted by name.
889pub fn cases() -> Vec<Case> {
890    let mut cases: Vec<Case> = tests().iter().map(TestFn::case).collect();
891    cases.sort_by(|a, b| a.name.cmp(&b.name));
892    cases
893}
894
895/// Show `case` in the app's test host, built fresh, until the next call or [`clear_active`].
896/// Answers false when the app mounts no test host, so the runner can say so.
897#[must_use]
898pub fn set_active(case: Case) -> bool {
899    ACTIVE.with(|a| *a.borrow_mut() = Some(case));
900    PAGE_PANIC.with(|p| *p.borrow_mut() = None);
901    notify_host()
902}
903
904/// Return the test host to the app's own content.
905pub fn clear_active() {
906    ACTIVE.with(|a| *a.borrow_mut() = None);
907    notify_host();
908}
909
910fn notify_host() -> bool {
911    let host = HOST.with(|h| h.borrow().clone());
912    match host {
913        Some(rebuild) => {
914            rebuild();
915            true
916        }
917        None => false,
918    }
919}
920
921/// The active case, for the test host to build.
922#[must_use]
923pub fn active() -> Option<Case> {
924    ACTIVE.with(|a| a.borrow().clone())
925}
926
927/// Install the mounted test host's rebuild (`day::test_host` does, for the life of its
928/// scope); `None` when it goes.
929pub fn set_host(rebuild: Option<Rc<dyn Fn()>>) {
930    HOST.with(|h| *h.borrow_mut() = rebuild);
931}
932
933/// Record a panic the test host caught while building the active case's page.
934pub fn note_page_panic(message: String) {
935    PAGE_PANIC.with(|p| *p.borrow_mut() = Some(message));
936}
937
938/// The panic, if any, the active case's page raised as it was built.
939#[must_use]
940pub fn take_page_panic() -> Option<String> {
941    PAGE_PANIC.with(|p| p.borrow_mut().take())
942}
943
944/// The sentence a caught panic's payload reads as.
945pub fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
946    if let Some(s) = payload.downcast_ref::<&str>() {
947        (*s).to_owned()
948    } else if let Some(s) = payload.downcast_ref::<String>() {
949        s.clone()
950    } else {
951        "a panic with no message".to_owned()
952    }
953}
954
955/// A fresh case for the test called `name`, for a person browsing an app's tests (the
956/// conformance app's navigation does).
957#[must_use]
958pub fn case_named(name: &str) -> Option<Case> {
959    tests()
960        .into_iter()
961        .find(|t| t.name() == name)
962        .map(|t| t.case())
963}