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    /// That the app announced this text to the screen reader during the run.
86    AssertAnnounced(String),
87    AssertValue(String, f64),
88    /// A toggle's state.
89    AssertOn(String, bool),
90    AssertFocused(String, bool),
91    AssertRoute(String),
92    A11yAudit(Option<String>),
93    /// The native widget's own state, as the platform reports it.
94    AssertNative(String, NativeExpect),
95    /// An element's frame, in Day's layout and natively.
96    AssertFrame(String, FrameExpect),
97    /// The color at a point of an element (fractions of its frame), `#rrggbb`.
98    SamplePixel(String, f64, f64, String),
99    /// A URL the app asked to open during the run.
100    AssertOpenedUrl(String),
101    /// Activate a list's row (a double click, Return, a tap on the phones), by position.
102    Activate(String, usize),
103    /// Move a list's row from one position to another, as a drag-to-reorder commits it.
104    Reorder(String, usize, usize),
105    /// Delete a list's row, as the platform's delete gesture commits it.
106    DeleteRow(String, usize),
107    /// Press a row's swipe action: the list, the row, the edge (`true` = leading) and the
108    /// action's position in that edge's offer.
109    SwipeRow(String, usize, bool, usize),
110    /// Scroll a scroll view or list to an edge (`"top"`, `"bottom"`, `"leading"`, `"trailing"`).
111    ScrollTo(String, String),
112    /// Expand or collapse a tree's row, named by its row id.
113    Expand(String, String, bool),
114    /// Go back one page in the innermost navigation stack.
115    NavBack,
116    /// Move a tree's row (by row id) under a parent (`None` = the root) at a position.
117    TreeMove(String, String, Option<String>, Option<usize>),
118    /// Choose an item, by label, from an element's context menu.
119    ContextMenu(String, String),
120    /// Choose an app-menu item by its id.
121    Menu(String),
122    /// Press a toolbar button, by item id.
123    ToolbarPress(String),
124    /// Set a toolbar toggle, by item id.
125    ToolbarToggle(String, bool),
126    /// Answer presentations natively (`false`) or hold them for `respond` (`true`).
127    DialogScripted(bool),
128    /// That a presentation is pending, with this title where one is given.
129    AssertPresented(Option<String>),
130    /// Answer the pending presentation: a button by position, or dismiss it (`None`).
131    Respond(Option<usize>),
132    /// Confirm a prompt with text (including an empty string).
133    RespondText(String),
134}
135
136/// What [`Drive::assert_frame`] expects of an element's frame, in points; only the fields set
137/// are checked. `x`/`y` are relative to `relative_to`'s origin, or the window content's.
138#[derive(Clone, Debug, Default, PartialEq)]
139pub struct FrameExpect {
140    pub width: Option<f64>,
141    pub height: Option<f64>,
142    pub x: Option<f64>,
143    pub y: Option<f64>,
144    /// The element whose origin `x`/`y` are measured from.
145    pub relative_to: Option<String>,
146    /// How far each value may be off (default 1 point).
147    pub tolerance: Option<f64>,
148}
149
150/// What [`Drive::assert_native`] expects the native widget to report; only the fields set are
151/// checked (docs/testing.md).
152#[derive(Clone, Debug, Default, PartialEq)]
153pub struct NativeExpect {
154    /// The text the widget displays.
155    pub text: Option<String>,
156    /// A slider's or progress indicator's value.
157    pub number: Option<f64>,
158    /// A toggle's state, or a button's selected state.
159    pub checked: Option<bool>,
160    /// Whether the widget takes input.
161    pub enabled: Option<bool>,
162    /// Whether the widget is shown.
163    pub visible: Option<bool>,
164}
165
166/// The future one drive op resolves to.
167pub type OpFuture = Pin<Box<dyn Future<Output = TestResult>>>;
168
169/// Executes [`DriveOp`]s. The engine's backend runs each as the matching dayscript step on the
170/// main thread and waits, asynchronously, through the step's retry window; the mock harness
171/// uses the same backend against the mock toolkit.
172pub trait DriveBackend {
173    fn run(&self, op: DriveOp) -> OpFuture;
174}
175
176/// The handle a test drives the app with. Every method awaits the op and fails the test with
177/// the step's own message when the op fails after its retry window.
178#[derive(Clone)]
179pub struct Drive {
180    backend: Rc<dyn DriveBackend>,
181}
182
183impl Drive {
184    /// A drive over `backend`; the engine and the mock harness build one per test.
185    pub fn new(backend: Rc<dyn DriveBackend>) -> Self {
186        Drive { backend }
187    }
188
189    fn op(&self, op: DriveOp) -> OpFuture {
190        self.backend.run(op)
191    }
192
193    pub fn tap(&self, id: &str) -> OpFuture {
194        self.op(DriveOp::Tap(id.into()))
195    }
196    /// Type `text` into the field, replacing what it holds.
197    pub fn input(&self, id: &str, text: &str) -> OpFuture {
198        self.op(DriveOp::Input(id.into(), text.into()))
199    }
200    pub fn toggle(&self, id: &str, on: bool) -> OpFuture {
201        self.op(DriveOp::Toggle(id.into(), on))
202    }
203    pub fn set_value(&self, id: &str, value: f64) -> OpFuture {
204        self.op(DriveOp::SetValue(id.into(), value))
205    }
206    pub fn select(&self, id: &str, index: usize) -> OpFuture {
207        self.op(DriveOp::Select(id.into(), index))
208    }
209    pub fn focus(&self, id: &str) -> OpFuture {
210        self.op(DriveOp::Focus(id.into()))
211    }
212    pub fn submit(&self, id: &str) -> OpFuture {
213        self.op(DriveOp::Submit(id.into()))
214    }
215    pub fn navigate(&self, route: &str) -> OpFuture {
216        self.op(DriveOp::Navigate(route.into()))
217    }
218    /// Let native transitions settle.
219    pub fn wait_idle(&self) -> OpFuture {
220        self.op(DriveOp::WaitIdle)
221    }
222    pub fn pause(&self, secs: f64) -> OpFuture {
223        self.op(DriveOp::Pause(secs))
224    }
225    /// Capture the window as `name`; the capture rides the test's record to the runner.
226    pub fn shot(&self, name: &str) -> OpFuture {
227        self.op(DriveOp::Shot(name.into()))
228    }
229    pub fn assert_text(&self, id: &str, text: &str) -> OpFuture {
230        self.op(DriveOp::AssertText(id.into(), text.into()))
231    }
232    pub fn assert_visible(&self, id: &str) -> OpFuture {
233        self.op(DriveOp::AssertVisible(id.into()))
234    }
235    pub fn assert_missing(&self, id: &str) -> OpFuture {
236        self.op(DriveOp::AssertMissing(id.into()))
237    }
238    /// The pointer entering `id` at (`x`, `y`) in its coordinates (its center for `None`).
239    pub fn hover(&self, id: &str, at: Option<(f64, f64)>) -> OpFuture {
240        self.op(DriveOp::Hover(id.into(), at))
241    }
242    /// The pointer leaving `id`.
243    pub fn hover_leave(&self, id: &str) -> OpFuture {
244        self.op(DriveOp::HoverLeave(id.into()))
245    }
246    /// A two-finger pan over `id` by (`dx`, `dy`) in total.
247    pub fn pan(&self, id: &str, dx: f64, dy: f64) -> OpFuture {
248        self.op(DriveOp::Pan(id.into(), dx, dy))
249    }
250    /// A pinch over `id` to `scale` (cumulative; 1 = unchanged).
251    pub fn pinch(&self, id: &str, scale: f64) -> OpFuture {
252        self.op(DriveOp::Pinch(id.into(), scale))
253    }
254    /// A two-finger rotation over `id` to `rotation` radians (cumulative; positive clockwise).
255    pub fn rotate(&self, id: &str, rotation: f64) -> OpFuture {
256        self.op(DriveOp::Rotate(id.into(), rotation))
257    }
258    /// A pointer drag over `id` from `from` to `to`, in its coordinates.
259    pub fn drag(&self, id: &str, from: (f64, f64), to: (f64, f64)) -> OpFuture {
260        self.op(DriveOp::Drag(id.into(), from, to))
261    }
262    /// A tap at (`x`, `y`) in `id`'s coordinates.
263    pub fn tap_at(&self, id: &str, x: f64, y: f64) -> OpFuture {
264        self.op(DriveOp::TapAt(id.into(), x, y))
265    }
266    /// A key press (web `KeyboardEvent.key` names: `"Enter"`, `"ArrowRight"`, `"a"`) to `id`,
267    /// or to whatever holds focus for `None`.
268    pub fn key(&self, id: Option<&str>, key: &str) -> OpFuture {
269        self.op(DriveOp::Key(id.map(str::to_owned), key.into()))
270    }
271    /// That the app announced `text` to the screen reader during the run.
272    pub fn assert_announced(&self, text: &str) -> OpFuture {
273        self.op(DriveOp::AssertAnnounced(text.into()))
274    }
275    /// That an element is not on screen: missing, with an empty frame, or hidden natively (a
276    /// collapsed pane a toolkit keeps built).
277    pub fn assert_hidden(&self, id: &str) -> OpFuture {
278        self.op(DriveOp::AssertHidden(id.into()))
279    }
280    pub fn assert_value(&self, id: &str, value: f64) -> OpFuture {
281        self.op(DriveOp::AssertValue(id.into(), value))
282    }
283    /// A toggle's on/off state.
284    pub fn assert_on(&self, id: &str, on: bool) -> OpFuture {
285        self.op(DriveOp::AssertOn(id.into(), on))
286    }
287    pub fn assert_focused(&self, id: &str, focused: bool) -> OpFuture {
288        self.op(DriveOp::AssertFocused(id.into(), focused))
289    }
290    pub fn assert_route(&self, route: &str) -> OpFuture {
291        self.op(DriveOp::AssertRoute(route.into()))
292    }
293    /// Diff the native accessibility tree against Day's expectation for `id` (all id'd
294    /// nodes when `None`), where the toolkit can read its tree back.
295    pub fn a11y_audit(&self, id: Option<&str>) -> OpFuture {
296        self.op(DriveOp::A11yAudit(id.map(str::to_owned)))
297    }
298
299    /// The native widget's own state, as the platform reports it (docs/testing.md). A field
300    /// the toolkit cannot read is recorded in the report as unread rather than failed. In a
301    /// conformance run `assert_text`, `assert_value` and `assert_on` check the native widget
302    /// too; this is for what they do not cover.
303    pub fn assert_native(&self, id: &str, expect: NativeExpect) -> OpFuture {
304        self.op(DriveOp::AssertNative(id.into(), expect))
305    }
306    /// The element's frame in Day's layout and, where the toolkit reads it back, natively.
307    pub fn assert_frame(&self, id: &str, expect: FrameExpect) -> OpFuture {
308        self.op(DriveOp::AssertFrame(id.into(), expect))
309    }
310    /// The element's size, the common case of [`Drive::assert_frame`].
311    pub fn assert_size(&self, id: &str, width: f64, height: f64) -> OpFuture {
312        self.assert_frame(
313            id,
314            FrameExpect {
315                width: Some(width),
316                height: Some(height),
317                ..Default::default()
318            },
319        )
320    }
321    /// The color drawn at (`x`, `y`), fractions of the element's frame, as `#rrggbb`. Passes as
322    /// unread where the toolkit has no capture.
323    pub fn sample_pixel(&self, id: &str, x: f64, y: f64, color: &str) -> OpFuture {
324        self.op(DriveOp::SamplePixel(id.into(), x, y, color.into()))
325    }
326    /// That the app asked to open `url` (a link, `day::open_url`) during the run; in a run
327    /// nothing actually opens.
328    pub fn assert_opened_url(&self, url: &str) -> OpFuture {
329        self.op(DriveOp::AssertOpenedUrl(url.into()))
330    }
331    /// Whether the element takes input, in Day's tree and in the native widget.
332    pub fn assert_enabled(&self, id: &str, enabled: bool) -> OpFuture {
333        self.assert_native(
334            id,
335            NativeExpect {
336                enabled: Some(enabled),
337                ..Default::default()
338            },
339        )
340    }
341
342    /// Activate a list's row by position: what a double click, Return or a phone's tap commits.
343    pub fn activate(&self, id: &str, index: usize) -> OpFuture {
344        self.op(DriveOp::Activate(id.into(), index))
345    }
346    /// Move a list's row from `from` to `to`, as a native drag-to-reorder commits it.
347    pub fn reorder(&self, id: &str, from: usize, to: usize) -> OpFuture {
348        self.op(DriveOp::Reorder(id.into(), from, to))
349    }
350    /// Delete a list's row, as the platform's delete gesture commits it.
351    pub fn delete_row(&self, id: &str, row: usize) -> OpFuture {
352        self.op(DriveOp::DeleteRow(id.into(), row))
353    }
354    /// Press the `action`th swipe action on a list row's leading or trailing edge.
355    pub fn swipe_row(&self, id: &str, row: usize, leading: bool, action: usize) -> OpFuture {
356        self.op(DriveOp::SwipeRow(id.into(), row, leading, action))
357    }
358    /// Scroll a scroll view or list to an edge: `"top"`, `"bottom"`, `"leading"`, `"trailing"`.
359    pub fn scroll_to(&self, id: &str, edge: &str) -> OpFuture {
360        self.op(DriveOp::ScrollTo(id.into(), edge.into()))
361    }
362    /// Expand or collapse a tree's row, named by its row id.
363    pub fn expand(&self, id: &str, row: &str, expanded: bool) -> OpFuture {
364        self.op(DriveOp::Expand(id.into(), row.into(), expanded))
365    }
366    /// Go back one page in the innermost navigation stack.
367    pub fn nav_back(&self) -> OpFuture {
368        self.op(DriveOp::NavBack)
369    }
370    /// Move a tree's row (by row id) under `parent` (`None` = the root level), at `index` among
371    /// its new siblings (`None` = last), as a native drag commits it.
372    pub fn tree_move(
373        &self,
374        id: &str,
375        row: &str,
376        parent: Option<&str>,
377        index: Option<usize>,
378    ) -> OpFuture {
379        self.op(DriveOp::TreeMove(
380            id.into(),
381            row.into(),
382            parent.map(str::to_owned),
383            index,
384        ))
385    }
386
387    /// Choose the item labeled `item` from `id`'s context menu, as a right click (or long
388    /// press) and a choice would.
389    pub fn context_menu(&self, id: &str, item: &str) -> OpFuture {
390        self.op(DriveOp::ContextMenu(id.into(), item.into()))
391    }
392    /// Choose an app-menu item by the id the app gave it (`MenuEntry::id`).
393    pub fn menu(&self, item_id: &str) -> OpFuture {
394        self.op(DriveOp::Menu(item_id.into()))
395    }
396    /// Press the toolbar button `item`.
397    pub fn toolbar_press(&self, item: &str) -> OpFuture {
398        self.op(DriveOp::ToolbarPress(item.into()))
399    }
400    /// Turn the toolbar toggle `item` on or off.
401    pub fn toolbar_toggle(&self, item: &str, on: bool) -> OpFuture {
402        self.op(DriveOp::ToolbarToggle(item.into(), on))
403    }
404    /// Show presentations natively (`false`, the default) or hold them for
405    /// [`Drive::respond`] without any native dialog (`true`). In native mode `respond` still
406    /// answers, and the toolkit dismisses the dialog it showed.
407    pub fn dialogs_scripted(&self, scripted: bool) -> OpFuture {
408        self.op(DriveOp::DialogScripted(scripted))
409    }
410    /// That a dialog or picker is pending, titled `title` where one is given.
411    pub fn assert_presented(&self, title: Option<&str>) -> OpFuture {
412        self.op(DriveOp::AssertPresented(title.map(str::to_owned)))
413    }
414    /// Answer the pending dialog with the button at `button` (presentation order), or dismiss
415    /// it for `None`.
416    pub fn respond(&self, button: Option<usize>) -> OpFuture {
417        self.op(DriveOp::Respond(button))
418    }
419
420    /// Confirm a pending text prompt.
421    pub fn respond_text(&self, text: &str) -> OpFuture {
422        self.op(DriveOp::RespondText(text.into()))
423    }
424
425    /// A plain assertion for a headless test: fails with `what` when `ok` is false.
426    pub fn check(&self, ok: bool, what: &str) -> TestResult {
427        if ok { Ok(()) } else { Err(Fail(what.into())) }
428    }
429    /// Equality for a headless test, naming both sides on a mismatch.
430    pub fn check_eq<T: PartialEq + std::fmt::Debug>(&self, got: T, want: T) -> TestResult {
431        if got == want {
432            Ok(())
433        } else {
434            Err(Fail(format!("{got:?} ≠ expected {want:?}")))
435        }
436    }
437}
438
439/// Whether a case shows a page and drives it, or runs with no page.
440#[derive(Clone, Copy, Debug, PartialEq, Eq)]
441pub enum TestKind {
442    Gui,
443    Headless,
444}
445
446type Body = Rc<dyn Fn(Drive) -> Pin<Box<dyn Future<Output = TestResult>>>>;
447
448/// One test: what it proves, what it needs, the page it shows and the body that drives it.
449/// Built by a `#[day::test]` function each time the test runs, so the signals a page and its
450/// drive share are fresh per run; the registry names it after that function.
451#[derive(Clone)]
452pub struct Case {
453    name: String,
454    kind: TestKind,
455    proves: Vec<String>,
456    requires: Vec<Cap>,
457    /// Supports the case needs beyond a `Cap`: a piece's own `support()` answer, named.
458    requires_support: Vec<(String, fn() -> day_spec::Support)>,
459    page: Option<Rc<dyn Fn() -> AnyPiece>>,
460    shots: Vec<String>,
461    body: Option<Body>,
462    timeout_secs: Option<f64>,
463}
464
465impl Default for Case {
466    fn default() -> Self {
467        Case::new()
468    }
469}
470
471impl Case {
472    /// A GUI case: a page the app's test host shows while the case runs, and a drive against it.
473    pub fn new() -> Self {
474        Case {
475            name: String::new(),
476            kind: TestKind::Gui,
477            proves: Vec::new(),
478            requires: Vec::new(),
479            requires_support: Vec::new(),
480            page: None,
481            shots: Vec::new(),
482            body: None,
483            timeout_secs: None,
484        }
485    }
486    /// A test with no page: app logic run inside the app's own environment.
487    pub fn headless() -> Self {
488        Case {
489            kind: TestKind::Headless,
490            ..Case::new()
491        }
492    }
493    /// How long the case may take, page and drive together, before it fails as timed out.
494    /// Unset, the run's default applies (30 s, or what `day test --case-timeout` says).
495    pub fn timeout(mut self, secs: f64) -> Self {
496        self.timeout_secs = Some(secs);
497        self
498    }
499    /// The piece kind this case is the proof of (`kinds::BUTTON`); a pass marks the kind
500    /// on this toolkit in the coverage tables.
501    pub fn proves(mut self, kind: &str) -> Self {
502        self.proves.push(format!("kind:{kind}"));
503        self
504    }
505    /// The capability this case proves.
506    pub fn proves_cap(mut self, cap: Cap) -> Self {
507        self.proves.push(format!("cap:{cap:?}"));
508        self
509    }
510    /// The `Decorate` modifier this case proves (`"padding"`).
511    pub fn proves_modifier(mut self, modifier: &str) -> Self {
512        self.proves.push(format!("modifier:{modifier}"));
513        self
514    }
515    /// The toolkit duty this case proves (`"set_input_traits"`).
516    pub fn proves_duty(mut self, duty: &str) -> Self {
517        self.proves.push(format!("duty:{duty}"));
518        self
519    }
520    /// A capability the case needs; where the toolkit answers `Unsupported` the case is
521    /// skipped with that reason rather than failed. The one way a case adapts to a toolkit.
522    pub fn requires(mut self, cap: Cap) -> Self {
523        self.requires.push(cap);
524        self
525    }
526    /// A piece's own support the case needs (`day_piece_map::support`), named for the skip
527    /// reason: where it answers `Unsupported` the case is skipped, as for [`Case::requires`].
528    /// For a piece realized only where its platform ships the widget.
529    pub fn requires_support(mut self, what: &str, support: fn() -> day_spec::Support) -> Self {
530        self.requires_support.push((what.to_owned(), support));
531        self
532    }
533    /// The first support this case needs that the running toolkit lacks, named.
534    pub fn missing_support(&self) -> Option<String> {
535        self.requires_support
536            .iter()
537            .find(|(_, f)| f() == day_spec::Support::Unsupported)
538            .map(|(what, _)| what.clone())
539    }
540    /// The page the app shows for this case; any piece.
541    pub fn page<P: crate::Piece>(mut self, page: impl Fn() -> P + 'static) -> Self {
542        self.page = Some(Rc::new(move || AnyPiece::new(page())));
543        self
544    }
545    /// A capture taken before the drive runs, once the page is shown.
546    pub fn shot(mut self, name: &str) -> Self {
547        self.shots.push(name.into());
548        self
549    }
550    /// The drive: an async body over a [`Drive`], awaiting each step so the app's main loop
551    /// runs between them (a transition settles, a capture paints) as it does between a
552    /// script's steps.
553    pub fn drive<F>(mut self, body: impl Fn(Drive) -> F + 'static) -> Self
554    where
555        F: Future<Output = TestResult> + 'static,
556    {
557        self.body = Some(Rc::new(move |d| Box::pin(body(d))));
558        self
559    }
560    /// [`Case::drive`] under the name a headless test reads better with.
561    pub fn run<F>(self, body: impl Fn(Drive) -> F + 'static) -> Self
562    where
563        F: Future<Output = TestResult> + 'static,
564    {
565        self.drive(body)
566    }
567
568    /// The name the registry gave the case: its function's, hyphenated. Empty for a case
569    /// built outside the registry.
570    pub fn name(&self) -> &str {
571        &self.name
572    }
573    /// The case's own time limit, if it set one.
574    pub fn timeout_secs(&self) -> Option<f64> {
575        self.timeout_secs
576    }
577    pub fn kind(&self) -> TestKind {
578        self.kind
579    }
580    /// The `kind:`, `cap:` and `duty:` keys this case proves, in the matrices' own spelling.
581    pub fn proves_keys(&self) -> &[String] {
582        &self.proves
583    }
584    pub fn requirements(&self) -> &[Cap] {
585        &self.requires
586    }
587    /// The captures to take before the drive.
588    pub fn shots(&self) -> &[String] {
589        &self.shots
590    }
591    /// Build the case's page, if it has one.
592    pub fn build_page(&self) -> Option<AnyPiece> {
593        self.page.as_ref().map(|p| p())
594    }
595    /// Run the body over `drive`; a case with no body passes once its page showed.
596    pub fn run_body(&self, drive: Drive) -> Pin<Box<dyn Future<Output = TestResult>>> {
597        match &self.body {
598            Some(body) => body(drive),
599            None => Box::pin(async { Ok(()) }),
600        }
601    }
602}
603
604/// A registered test: the function that builds its [`Case`], and that function's identifier,
605/// which is where the test's name comes from. Declared by `#[day::test]`.
606#[derive(Clone, Copy)]
607pub struct TestFn {
608    ident: &'static str,
609    build: fn() -> Case,
610}
611
612impl TestFn {
613    /// An entry for `build`, named by `ident` (`stringify!` of the function or its path).
614    pub const fn new(ident: &'static str, build: fn() -> Case) -> Self {
615        TestFn { ident, build }
616    }
617    /// The test's name: the identifier's last path segment, with hyphens for underscores.
618    pub fn name(&self) -> String {
619        let last = self.ident.rsplit("::").next().unwrap_or(self.ident);
620        last.trim().replace('_', "-")
621    }
622    /// A fresh case, named.
623    pub fn case(&self) -> Case {
624        let mut case = (self.build)();
625        case.name = self.name();
626        case
627    }
628}
629
630mod registry;
631pub use registry::validate_registry;
632#[cfg(target_arch = "wasm32")]
633pub use registry::{Registration, install_web_registry};
634
635/// Every native `#[day::test]`, collected without runtime constructors.
636#[cfg(not(target_arch = "wasm32"))]
637#[linkme::distributed_slice]
638pub static TESTS: [TestFn];
639
640/// What a test host does when the active case changes: rebuild its content.
641type HostNotify = Rc<dyn Fn()>;
642
643day_reactive::tls_slots! {
644    conformance;
645    static RUNTIME: RefCell<Vec<TestFn>> = const { RefCell::new(Vec::new()) };
646    /// The case the engine is driving, which the test host shows; its page shares its signals
647    /// with the drive.
648    static ACTIVE: RefCell<Option<Case>> = const { RefCell::new(None) };
649    /// The mounted test host's rebuild, when the app shows one (`day::test_host`).
650    static HOST: RefCell<Option<HostNotify>> = const { RefCell::new(None) };
651    /// A panic raised while the host built the active case's page, for the runner to report.
652    static PAGE_PANIC: RefCell<Option<String>> = const { RefCell::new(None) };
653    /// The URLs the app asked to open while a test run was going on, when one is.
654    static OPENED: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
655    /// What the app announced to the screen reader while a test run was going on, when one is.
656    static ANNOUNCED: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
657}
658
659/// Start or end a test run's interception of [`crate::open_url`]: while it is on, a URL the app
660/// asks to open is recorded instead of opened, so `assert_opened_url` can check it and no
661/// browser starts on the machine running the tests.
662pub fn set_intercepting_urls(on: bool) {
663    OPENED.with(|o| *o.borrow_mut() = on.then(Vec::new));
664    ANNOUNCED.with(|a| *a.borrow_mut() = on.then(Vec::new));
665}
666
667/// Record a screen-reader announcement if a test run is going on. Unlike a URL it still goes
668/// to the toolkit: announcing has no side effect a run must avoid, and the duty is what a case
669/// proves.
670pub fn note_announcement(text: &str) {
671    ANNOUNCED.with(|a| {
672        if let Some(list) = a.borrow_mut().as_mut() {
673            list.push(text.to_owned());
674        }
675    });
676}
677
678/// The announcements made since the run began.
679pub fn announcements() -> Vec<String> {
680    ANNOUNCED.with(|a| a.borrow().clone().unwrap_or_default())
681}
682
683/// Record `url` if a test run is intercepting; whether it did.
684pub fn intercept_open_url(url: &str) -> bool {
685    OPENED.with(|o| match o.borrow_mut().as_mut() {
686        Some(list) => {
687            list.push(url.to_owned());
688            true
689        }
690        None => false,
691    })
692}
693
694/// The URLs opened (and intercepted) since the run began.
695pub fn opened_urls() -> Vec<String> {
696    OPENED.with(|o| o.borrow().clone().unwrap_or_default())
697}
698
699/// Add a synthetic case in a test harness. Application tests use `#[day::test]`.
700pub fn register(test: TestFn) {
701    RUNTIME.with(|r| {
702        let mut r = r.borrow_mut();
703        if !r.iter().any(|t| std::ptr::fn_addr_eq(t.build, test.build)) {
704            r.push(test);
705        }
706    });
707}
708
709/// Every registered test, link-time and run-time ones together.
710pub fn tests() -> Vec<TestFn> {
711    let mut all: Vec<TestFn> = Vec::new();
712    all.extend(registry::compiled_tests());
713    RUNTIME.with(|r| {
714        for t in r.borrow().iter() {
715            if !all.iter().any(|a| std::ptr::fn_addr_eq(a.build, t.build)) {
716                all.push(*t);
717            }
718        }
719    });
720    all
721}
722
723/// Every registered test as a fresh, named [`Case`], sorted by name.
724pub fn cases() -> Vec<Case> {
725    let mut cases: Vec<Case> = tests().iter().map(TestFn::case).collect();
726    cases.sort_by(|a, b| a.name.cmp(&b.name));
727    cases
728}
729
730/// Show `case` in the app's test host, built fresh, until the next call or [`clear_active`].
731/// Answers false when the app mounts no test host, so the runner can say so.
732pub fn set_active(case: Case) -> bool {
733    ACTIVE.with(|a| *a.borrow_mut() = Some(case));
734    PAGE_PANIC.with(|p| *p.borrow_mut() = None);
735    notify_host()
736}
737
738/// Return the test host to the app's own content.
739pub fn clear_active() {
740    ACTIVE.with(|a| *a.borrow_mut() = None);
741    notify_host();
742}
743
744fn notify_host() -> bool {
745    let host = HOST.with(|h| h.borrow().clone());
746    match host {
747        Some(rebuild) => {
748            rebuild();
749            true
750        }
751        None => false,
752    }
753}
754
755/// The active case, for the test host to build.
756pub fn active() -> Option<Case> {
757    ACTIVE.with(|a| a.borrow().clone())
758}
759
760/// Install the mounted test host's rebuild (`day::test_host` does, for the life of its
761/// scope); `None` when it goes.
762pub fn set_host(rebuild: Option<Rc<dyn Fn()>>) {
763    HOST.with(|h| *h.borrow_mut() = rebuild);
764}
765
766/// Record a panic the test host caught while building the active case's page.
767pub fn note_page_panic(message: String) {
768    PAGE_PANIC.with(|p| *p.borrow_mut() = Some(message));
769}
770
771/// The panic, if any, the active case's page raised as it was built.
772pub fn take_page_panic() -> Option<String> {
773    PAGE_PANIC.with(|p| p.borrow_mut().take())
774}
775
776/// The sentence a caught panic's payload reads as.
777pub fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
778    if let Some(s) = payload.downcast_ref::<&str>() {
779        (*s).to_owned()
780    } else if let Some(s) = payload.downcast_ref::<String>() {
781        s.clone()
782    } else {
783        "a panic with no message".to_owned()
784    }
785}
786
787/// A fresh case for the test called `name`, for a person browsing an app's tests (the
788/// conformance app's navigation does).
789pub fn case_named(name: &str) -> Option<Case> {
790    tests()
791        .into_iter()
792        .find(|t| t.name() == name)
793        .map(|t| t.case())
794}