1use 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#[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
45pub type TestResult = Result<(), Fail>;
47
48#[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 Shot(String),
64 AssertText(String, String),
65 AssertVisible(String),
66 AssertMissing(String),
67 AssertHidden(String),
69 Hover(String, Option<(f64, f64)>),
71 HoverLeave(String),
73 Pan(String, f64, f64),
75 Pinch(String, f64),
77 Rotate(String, f64),
79 Drag(String, (f64, f64), (f64, f64)),
81 TapAt(String, f64, f64),
83 Key(Option<String>, String),
85 AssertAnnounced(String),
87 AssertValue(String, f64),
88 AssertOn(String, bool),
90 AssertFocused(String, bool),
91 AssertRoute(String),
92 A11yAudit(Option<String>),
93 AssertNative(String, NativeExpect),
95 AssertFrame(String, FrameExpect),
97 SamplePixel(String, f64, f64, String),
99 AssertOpenedUrl(String),
101 Activate(String, usize),
103 Reorder(String, usize, usize),
105 DeleteRow(String, usize),
107 SwipeRow(String, usize, bool, usize),
110 ScrollTo(String, String),
112 Expand(String, String, bool),
114 NavBack,
116 TreeMove(String, String, Option<String>, Option<usize>),
118 ContextMenu(String, String),
120 Menu(String),
122 ToolbarPress(String),
124 ToolbarToggle(String, bool),
126 DialogScripted(bool),
128 AssertPresented(Option<String>),
130 Respond(Option<usize>),
132 RespondText(String),
134}
135
136#[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 pub relative_to: Option<String>,
146 pub tolerance: Option<f64>,
148}
149
150#[derive(Clone, Debug, Default, PartialEq)]
153pub struct NativeExpect {
154 pub text: Option<String>,
156 pub number: Option<f64>,
158 pub checked: Option<bool>,
160 pub enabled: Option<bool>,
162 pub visible: Option<bool>,
164}
165
166pub type OpFuture = Pin<Box<dyn Future<Output = TestResult>>>;
168
169pub trait DriveBackend {
173 fn run(&self, op: DriveOp) -> OpFuture;
174}
175
176#[derive(Clone)]
179pub struct Drive {
180 backend: Rc<dyn DriveBackend>,
181}
182
183impl Drive {
184 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 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 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 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 pub fn hover(&self, id: &str, at: Option<(f64, f64)>) -> OpFuture {
240 self.op(DriveOp::Hover(id.into(), at))
241 }
242 pub fn hover_leave(&self, id: &str) -> OpFuture {
244 self.op(DriveOp::HoverLeave(id.into()))
245 }
246 pub fn pan(&self, id: &str, dx: f64, dy: f64) -> OpFuture {
248 self.op(DriveOp::Pan(id.into(), dx, dy))
249 }
250 pub fn pinch(&self, id: &str, scale: f64) -> OpFuture {
252 self.op(DriveOp::Pinch(id.into(), scale))
253 }
254 pub fn rotate(&self, id: &str, rotation: f64) -> OpFuture {
256 self.op(DriveOp::Rotate(id.into(), rotation))
257 }
258 pub fn drag(&self, id: &str, from: (f64, f64), to: (f64, f64)) -> OpFuture {
260 self.op(DriveOp::Drag(id.into(), from, to))
261 }
262 pub fn tap_at(&self, id: &str, x: f64, y: f64) -> OpFuture {
264 self.op(DriveOp::TapAt(id.into(), x, y))
265 }
266 pub fn key(&self, id: Option<&str>, key: &str) -> OpFuture {
269 self.op(DriveOp::Key(id.map(str::to_owned), key.into()))
270 }
271 pub fn assert_announced(&self, text: &str) -> OpFuture {
273 self.op(DriveOp::AssertAnnounced(text.into()))
274 }
275 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 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 pub fn a11y_audit(&self, id: Option<&str>) -> OpFuture {
296 self.op(DriveOp::A11yAudit(id.map(str::to_owned)))
297 }
298
299 pub fn assert_native(&self, id: &str, expect: NativeExpect) -> OpFuture {
304 self.op(DriveOp::AssertNative(id.into(), expect))
305 }
306 pub fn assert_frame(&self, id: &str, expect: FrameExpect) -> OpFuture {
308 self.op(DriveOp::AssertFrame(id.into(), expect))
309 }
310 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 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 pub fn assert_opened_url(&self, url: &str) -> OpFuture {
329 self.op(DriveOp::AssertOpenedUrl(url.into()))
330 }
331 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 pub fn activate(&self, id: &str, index: usize) -> OpFuture {
344 self.op(DriveOp::Activate(id.into(), index))
345 }
346 pub fn reorder(&self, id: &str, from: usize, to: usize) -> OpFuture {
348 self.op(DriveOp::Reorder(id.into(), from, to))
349 }
350 pub fn delete_row(&self, id: &str, row: usize) -> OpFuture {
352 self.op(DriveOp::DeleteRow(id.into(), row))
353 }
354 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 pub fn scroll_to(&self, id: &str, edge: &str) -> OpFuture {
360 self.op(DriveOp::ScrollTo(id.into(), edge.into()))
361 }
362 pub fn expand(&self, id: &str, row: &str, expanded: bool) -> OpFuture {
364 self.op(DriveOp::Expand(id.into(), row.into(), expanded))
365 }
366 pub fn nav_back(&self) -> OpFuture {
368 self.op(DriveOp::NavBack)
369 }
370 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 pub fn context_menu(&self, id: &str, item: &str) -> OpFuture {
390 self.op(DriveOp::ContextMenu(id.into(), item.into()))
391 }
392 pub fn menu(&self, item_id: &str) -> OpFuture {
394 self.op(DriveOp::Menu(item_id.into()))
395 }
396 pub fn toolbar_press(&self, item: &str) -> OpFuture {
398 self.op(DriveOp::ToolbarPress(item.into()))
399 }
400 pub fn toolbar_toggle(&self, item: &str, on: bool) -> OpFuture {
402 self.op(DriveOp::ToolbarToggle(item.into(), on))
403 }
404 pub fn dialogs_scripted(&self, scripted: bool) -> OpFuture {
408 self.op(DriveOp::DialogScripted(scripted))
409 }
410 pub fn assert_presented(&self, title: Option<&str>) -> OpFuture {
412 self.op(DriveOp::AssertPresented(title.map(str::to_owned)))
413 }
414 pub fn respond(&self, button: Option<usize>) -> OpFuture {
417 self.op(DriveOp::Respond(button))
418 }
419
420 pub fn respond_text(&self, text: &str) -> OpFuture {
422 self.op(DriveOp::RespondText(text.into()))
423 }
424
425 pub fn check(&self, ok: bool, what: &str) -> TestResult {
431 if ok { Ok(()) } else { Err(Fail(what.into())) }
432 }
433 #[expect(
439 clippy::needless_pass_by_value,
440 reason = "public test-helper signature; callers pass temporaries by value"
441 )]
442 pub fn check_eq<T: PartialEq + std::fmt::Debug>(&self, got: T, want: T) -> TestResult {
443 if got == want {
444 Ok(())
445 } else {
446 Err(Fail(format!("{got:?} ≠ expected {want:?}")))
447 }
448 }
449}
450
451#[derive(Clone, Copy, Debug, PartialEq, Eq)]
453pub enum TestKind {
454 Gui,
455 Headless,
456}
457
458type Body = Rc<dyn Fn(Drive) -> Pin<Box<dyn Future<Output = TestResult>>>>;
459
460#[derive(Clone)]
464pub struct Case {
465 name: String,
466 kind: TestKind,
467 proves: Vec<String>,
468 requires: Vec<Cap>,
469 requires_support: Vec<(String, fn() -> day_spec::Support)>,
471 page: Option<Rc<dyn Fn() -> AnyPiece>>,
472 shots: Vec<String>,
473 body: Option<Body>,
474 timeout_secs: Option<f64>,
475}
476
477impl Default for Case {
478 fn default() -> Self {
479 Case::new()
480 }
481}
482
483impl Case {
484 pub fn new() -> Self {
486 Case {
487 name: String::new(),
488 kind: TestKind::Gui,
489 proves: Vec::new(),
490 requires: Vec::new(),
491 requires_support: Vec::new(),
492 page: None,
493 shots: Vec::new(),
494 body: None,
495 timeout_secs: None,
496 }
497 }
498 pub fn headless() -> Self {
500 Case {
501 kind: TestKind::Headless,
502 ..Case::new()
503 }
504 }
505 #[must_use]
508 pub fn timeout(mut self, secs: f64) -> Self {
509 self.timeout_secs = Some(secs);
510 self
511 }
512 #[must_use]
515 pub fn proves(mut self, kind: &str) -> Self {
516 self.proves.push(format!("kind:{kind}"));
517 self
518 }
519 #[must_use]
521 pub fn proves_cap(mut self, cap: Cap) -> Self {
522 self.proves.push(format!("cap:{cap:?}"));
523 self
524 }
525 #[must_use]
527 pub fn proves_modifier(mut self, modifier: &str) -> Self {
528 self.proves.push(format!("modifier:{modifier}"));
529 self
530 }
531 #[must_use]
533 pub fn proves_duty(mut self, duty: &str) -> Self {
534 self.proves.push(format!("duty:{duty}"));
535 self
536 }
537 #[must_use]
540 pub fn requires(mut self, cap: Cap) -> Self {
541 self.requires.push(cap);
542 self
543 }
544 #[must_use]
548 pub fn requires_support(mut self, what: &str, support: fn() -> day_spec::Support) -> Self {
549 self.requires_support.push((what.to_owned(), support));
550 self
551 }
552 #[must_use]
554 pub fn missing_support(&self) -> Option<String> {
555 self.requires_support
556 .iter()
557 .find(|(_, f)| f() == day_spec::Support::Unsupported)
558 .map(|(what, _)| what.clone())
559 }
560 #[must_use]
562 pub fn page<P: crate::Piece>(mut self, page: impl Fn() -> P + 'static) -> Self {
563 self.page = Some(Rc::new(move || AnyPiece::new(page())));
564 self
565 }
566 #[must_use]
568 pub fn shot(mut self, name: &str) -> Self {
569 self.shots.push(name.into());
570 self
571 }
572 #[must_use]
576 pub fn drive<F>(mut self, body: impl Fn(Drive) -> F + 'static) -> Self
577 where
578 F: Future<Output = TestResult> + 'static,
579 {
580 self.body = Some(Rc::new(move |d| Box::pin(body(d))));
581 self
582 }
583 #[must_use]
585 pub fn run<F>(self, body: impl Fn(Drive) -> F + 'static) -> Self
586 where
587 F: Future<Output = TestResult> + 'static,
588 {
589 self.drive(body)
590 }
591
592 #[must_use]
595 pub fn name(&self) -> &str {
596 &self.name
597 }
598 #[must_use]
600 pub fn timeout_secs(&self) -> Option<f64> {
601 self.timeout_secs
602 }
603 #[must_use]
604 pub fn kind(&self) -> TestKind {
605 self.kind
606 }
607 #[must_use]
609 pub fn proves_keys(&self) -> &[String] {
610 &self.proves
611 }
612 #[must_use]
613 pub fn requirements(&self) -> &[Cap] {
614 &self.requires
615 }
616 #[must_use]
618 pub fn shots(&self) -> &[String] {
619 &self.shots
620 }
621 #[must_use]
623 pub fn build_page(&self) -> Option<AnyPiece> {
624 self.page.as_ref().map(|p| p())
625 }
626 pub fn run_body(&self, drive: Drive) -> Pin<Box<dyn Future<Output = TestResult>>> {
628 match &self.body {
629 Some(body) => body(drive),
630 None => Box::pin(async { Ok(()) }),
631 }
632 }
633}
634
635#[derive(Clone, Copy)]
638pub struct TestFn {
639 ident: &'static str,
640 build: fn() -> Case,
641}
642
643impl TestFn {
644 pub const fn new(ident: &'static str, build: fn() -> Case) -> Self {
646 TestFn { ident, build }
647 }
648 #[must_use]
650 pub fn name(&self) -> String {
651 let last = self.ident.rsplit("::").next().unwrap_or(self.ident);
652 last.trim().replace('_', "-")
653 }
654 pub fn case(&self) -> Case {
656 let mut case = (self.build)();
657 case.name = self.name();
658 case
659 }
660}
661
662mod registry;
663pub use registry::validate_registry;
664#[cfg(target_arch = "wasm32")]
665pub use registry::{Registration, install_web_registry};
666
667#[cfg(not(target_arch = "wasm32"))]
669#[linkme::distributed_slice]
670pub static TESTS: [TestFn];
671
672type HostNotify = Rc<dyn Fn()>;
674
675day_reactive::tls_slots! {
676 conformance;
677 static RUNTIME: RefCell<Vec<TestFn>> = const { RefCell::new(Vec::new()) };
678 static ACTIVE: RefCell<Option<Case>> = const { RefCell::new(None) };
681 static HOST: RefCell<Option<HostNotify>> = const { RefCell::new(None) };
683 static PAGE_PANIC: RefCell<Option<String>> = const { RefCell::new(None) };
685 static OPENED: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
687 static ANNOUNCED: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
689}
690
691pub fn set_intercepting_urls(on: bool) {
695 OPENED.with(|o| *o.borrow_mut() = on.then(Vec::new));
696 ANNOUNCED.with(|a| *a.borrow_mut() = on.then(Vec::new));
697}
698
699pub fn note_announcement(text: &str) {
703 ANNOUNCED.with(|a| {
704 if let Some(list) = a.borrow_mut().as_mut() {
705 list.push(text.to_owned());
706 }
707 });
708}
709
710#[must_use]
712pub fn announcements() -> Vec<String> {
713 ANNOUNCED.with(|a| a.borrow().clone().unwrap_or_default())
714}
715
716#[must_use]
718pub fn intercept_open_url(url: &str) -> bool {
719 OPENED.with(|o| match o.borrow_mut().as_mut() {
720 Some(list) => {
721 list.push(url.to_owned());
722 true
723 }
724 None => false,
725 })
726}
727
728#[must_use]
730pub fn opened_urls() -> Vec<String> {
731 OPENED.with(|o| o.borrow().clone().unwrap_or_default())
732}
733
734pub fn register(test: TestFn) {
736 RUNTIME.with(|r| {
737 let mut r = r.borrow_mut();
738 if !r.iter().any(|t| std::ptr::fn_addr_eq(t.build, test.build)) {
739 r.push(test);
740 }
741 });
742}
743
744#[must_use]
746pub fn tests() -> Vec<TestFn> {
747 let mut all: Vec<TestFn> = Vec::new();
748 all.extend(registry::compiled_tests());
749 RUNTIME.with(|r| {
750 for t in r.borrow().iter() {
751 if !all.iter().any(|a| std::ptr::fn_addr_eq(a.build, t.build)) {
752 all.push(*t);
753 }
754 }
755 });
756 all
757}
758
759pub fn cases() -> Vec<Case> {
761 let mut cases: Vec<Case> = tests().iter().map(TestFn::case).collect();
762 cases.sort_by(|a, b| a.name.cmp(&b.name));
763 cases
764}
765
766#[must_use]
769pub fn set_active(case: Case) -> bool {
770 ACTIVE.with(|a| *a.borrow_mut() = Some(case));
771 PAGE_PANIC.with(|p| *p.borrow_mut() = None);
772 notify_host()
773}
774
775pub fn clear_active() {
777 ACTIVE.with(|a| *a.borrow_mut() = None);
778 notify_host();
779}
780
781fn notify_host() -> bool {
782 let host = HOST.with(|h| h.borrow().clone());
783 match host {
784 Some(rebuild) => {
785 rebuild();
786 true
787 }
788 None => false,
789 }
790}
791
792#[must_use]
794pub fn active() -> Option<Case> {
795 ACTIVE.with(|a| a.borrow().clone())
796}
797
798pub fn set_host(rebuild: Option<Rc<dyn Fn()>>) {
801 HOST.with(|h| *h.borrow_mut() = rebuild);
802}
803
804pub fn note_page_panic(message: String) {
806 PAGE_PANIC.with(|p| *p.borrow_mut() = Some(message));
807}
808
809#[must_use]
811pub fn take_page_panic() -> Option<String> {
812 PAGE_PANIC.with(|p| p.borrow_mut().take())
813}
814
815pub fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
817 if let Some(s) = payload.downcast_ref::<&str>() {
818 (*s).to_owned()
819 } else if let Some(s) = payload.downcast_ref::<String>() {
820 s.clone()
821 } else {
822 "a panic with no message".to_owned()
823 }
824}
825
826#[must_use]
829pub fn case_named(name: &str) -> Option<Case> {
830 tests()
831 .into_iter()
832 .find(|t| t.name() == name)
833 .map(|t| t.case())
834}