Skip to main content

sui_testing/
lib.rs

1#![forbid(unsafe_code)]
2
3mod app;
4mod diagnostics;
5mod expect;
6mod harness;
7mod locator;
8mod screenshot;
9mod selector;
10mod snapshot;
11mod window;
12
13pub use app::{IntoTestRuntime, TestApp};
14pub use expect::Expectation;
15pub use locator::Locator;
16pub use screenshot::{
17    ArtifactBundle, Screenshot, hdr_clip_mask, hdr_headroom_heatmap, hdr_luminance_heatmap,
18    write_hdr_avif, write_hdr_exr,
19};
20pub use selector::Selector;
21pub use snapshot::{SceneSummary, WindowSnapshot};
22pub use window::TestWindow;
23
24pub mod prelude {
25    pub use crate::{
26        ArtifactBundle, Expectation, IntoTestRuntime, Locator, SceneSummary, Screenshot, Selector,
27        TestApp, TestWindow, hdr_clip_mask, hdr_headroom_heatmap, hdr_luminance_heatmap,
28        write_hdr_avif, write_hdr_exr,
29    };
30}
31
32#[cfg(test)]
33mod tests {
34    use std::{
35        cell::RefCell,
36        fs,
37        path::PathBuf,
38        rc::Rc,
39        time::{SystemTime, UNIX_EPOCH},
40    };
41
42    use crate::TestApp;
43    use sui_core::{
44        Color, Event, ImeEvent, KeyState, PointerEventKind, Result, SemanticsAction, SemanticsNode,
45        SemanticsRole, SemanticsValue, Size, TimerToken, Vector, WakeEvent, WindowEvent,
46    };
47    use sui_layout::Constraints;
48    use sui_runtime::{
49        Application, ArrangeCtx, EventCtx, MeasureCtx, PaintCtx, SemanticsCtx, SingleChild, Widget,
50        WidgetChildren, WidgetPodVisitor, WindowBuilder,
51    };
52    use sui_scene::StrokeStyle;
53
54    #[derive(Debug, Default)]
55    struct AppState {
56        button_hovered: bool,
57        button_clicks: usize,
58        save_timer: Option<TimerToken>,
59        status: String,
60        input_value: String,
61    }
62
63    struct HarnessRoot {
64        children: WidgetChildren,
65    }
66
67    impl HarnessRoot {
68        fn new(state: Rc<RefCell<AppState>>) -> Self {
69            let mut children = WidgetChildren::new();
70            children.push(StatusButton::new(Rc::clone(&state)));
71            children.push(TestInput::new(state));
72            Self { children }
73        }
74    }
75
76    impl Widget for HarnessRoot {
77        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
78            let viewport = constraints.clamp(Size::new(480.0, 240.0));
79            let child_constraints = Constraints::tight(Size::new(180.0, 44.0));
80            self.children.measure_child(0, ctx, child_constraints);
81            self.children.measure_child(1, ctx, child_constraints);
82            viewport
83        }
84
85        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: sui_core::Rect) {
86            self.children.arrange_child(
87                0,
88                ctx,
89                sui_core::Rect::new(bounds.x() + 24.0, bounds.y() + 24.0, 180.0, 44.0),
90            );
91            self.children.arrange_child(
92                1,
93                ctx,
94                sui_core::Rect::new(bounds.x() + 24.0, bounds.y() + 92.0, 180.0, 44.0),
95            );
96        }
97
98        fn paint(&self, ctx: &mut PaintCtx) {
99            ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
100            self.children.paint(ctx);
101        }
102
103        fn semantics(&self, ctx: &mut SemanticsCtx) {
104            let mut root = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Window, ctx.bounds());
105            root.name = Some("Harness Window".to_string());
106            ctx.push(root);
107            self.children.semantics(ctx);
108        }
109
110        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
111            self.children.visit_children(visitor);
112        }
113
114        fn visit_children_mut(&mut self, visitor: &mut dyn sui_runtime::WidgetPodMutVisitor) {
115            self.children.visit_children_mut(visitor);
116        }
117    }
118
119    struct StatusButton {
120        state: Rc<RefCell<AppState>>,
121    }
122
123    impl StatusButton {
124        fn new(state: Rc<RefCell<AppState>>) -> Self {
125            Self { state }
126        }
127    }
128
129    impl Widget for StatusButton {
130        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
131            match event {
132                Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
133                    let hovered = ctx.bounds().contains(pointer.position);
134                    let mut state = self.state.borrow_mut();
135                    if state.button_hovered != hovered {
136                        state.button_hovered = hovered;
137                        ctx.request_paint();
138                        ctx.request_semantics();
139                    }
140                }
141                Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
142                    let mut state = self.state.borrow_mut();
143                    state.button_clicks += 1;
144                    state.status = "Saving".to_string();
145                    state.save_timer = Some(ctx.schedule_timer_after(2.0));
146                    ctx.request_focus();
147                    ctx.request_paint();
148                    ctx.request_semantics();
149                    ctx.set_handled();
150                }
151                Event::Keyboard(key)
152                    if key.state == KeyState::Pressed
153                        && ctx.is_focused()
154                        && matches!(key.key.as_str(), "Enter" | " ") =>
155                {
156                    let mut state = self.state.borrow_mut();
157                    state.status = "Activated".to_string();
158                    state.save_timer = None;
159                    ctx.request_paint();
160                    ctx.request_semantics();
161                    ctx.set_handled();
162                }
163                Event::Wake(WakeEvent::Timer { token, .. }) => {
164                    let mut state = self.state.borrow_mut();
165                    if state.save_timer == Some(*token) {
166                        state.status = "Saved".to_string();
167                        state.save_timer = None;
168                        ctx.request_paint();
169                        ctx.request_semantics();
170                        ctx.set_handled();
171                    }
172                }
173                _ => {}
174            }
175        }
176
177        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
178            constraints.clamp(Size::new(180.0, 44.0))
179        }
180
181        fn paint(&self, ctx: &mut PaintCtx) {
182            let state = self.state.borrow();
183            let color = if ctx.is_focused() {
184                Color::rgba(0.25, 0.52, 0.88, 1.0)
185            } else if state.button_hovered {
186                Color::rgba(0.21, 0.38, 0.66, 1.0)
187            } else {
188                Color::rgba(0.17, 0.24, 0.37, 1.0)
189            };
190            ctx.fill_bounds(color);
191            ctx.label(
192                ctx.bounds(),
193                format!("Save ({})", state.button_clicks),
194                Color::rgba(0.95, 0.96, 0.98, 1.0),
195            );
196        }
197
198        fn semantics(&self, ctx: &mut SemanticsCtx) {
199            let state = self.state.borrow();
200            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
201            node.name = Some("Save".to_string());
202            node.description = Some(state.status.clone());
203            node.state.hovered = state.button_hovered;
204            node.actions = vec![SemanticsAction::Focus, SemanticsAction::Activate];
205            ctx.push(node);
206
207            let mut status = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
208            status.parent = Some(ctx.root_widget_id());
209            status.name = Some(state.status.clone());
210            ctx.push(status);
211        }
212
213        fn accepts_focus(&self) -> bool {
214            true
215        }
216
217        fn focus_changed(&mut self, ctx: &mut EventCtx, _focused: bool) {
218            ctx.request_paint();
219            ctx.request_semantics();
220        }
221    }
222
223    struct TestInput {
224        state: Rc<RefCell<AppState>>,
225    }
226
227    impl TestInput {
228        fn new(state: Rc<RefCell<AppState>>) -> Self {
229            Self { state }
230        }
231    }
232
233    impl Widget for TestInput {
234        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
235            match event {
236                Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
237                    ctx.request_focus();
238                    ctx.request_paint();
239                    ctx.request_semantics();
240                    ctx.set_handled();
241                }
242                Event::Ime(ImeEvent::CompositionCommit { text }) if ctx.is_focused() => {
243                    self.state.borrow_mut().input_value = text.clone();
244                    ctx.request_paint();
245                    ctx.request_semantics();
246                    ctx.set_handled();
247                }
248                _ => {}
249            }
250        }
251
252        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
253            constraints.clamp(Size::new(180.0, 44.0))
254        }
255
256        fn paint(&self, ctx: &mut PaintCtx) {
257            let border = if ctx.is_focused() {
258                Color::rgba(0.66, 0.74, 0.93, 1.0)
259            } else {
260                Color::rgba(0.38, 0.43, 0.52, 1.0)
261            };
262            ctx.fill_bounds(Color::rgba(0.13, 0.15, 0.20, 1.0));
263            ctx.stroke_rect(ctx.bounds(), border, StrokeStyle::new(1.0));
264            ctx.label(
265                ctx.bounds(),
266                self.state.borrow().input_value.clone(),
267                Color::rgba(0.95, 0.96, 0.98, 1.0),
268            );
269        }
270
271        fn semantics(&self, ctx: &mut SemanticsCtx) {
272            let mut node =
273                SemanticsNode::new(ctx.widget_id(), SemanticsRole::TextInput, ctx.bounds());
274            node.name = Some("Name".to_string());
275            node.value = Some(SemanticsValue::Text(
276                self.state.borrow().input_value.clone(),
277            ));
278            node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
279            ctx.push(node);
280        }
281
282        fn accepts_focus(&self) -> bool {
283            true
284        }
285
286        fn focus_changed(&mut self, ctx: &mut EventCtx, _focused: bool) {
287            ctx.request_paint();
288            ctx.request_semantics();
289        }
290    }
291
292    fn build_app() -> Result<TestApp> {
293        TestApp::new(|| {
294            let state = Rc::new(RefCell::new(AppState::default()));
295            Application::new().window(
296                WindowBuilder::new()
297                    .title("Harness")
298                    .root(HarnessRoot::new(state)),
299            )
300        })
301    }
302
303    #[derive(Debug, Default)]
304    struct ListState {
305        selected: String,
306    }
307
308    struct ListRoot {
309        state: Rc<RefCell<ListState>>,
310        children: WidgetChildren,
311    }
312
313    impl ListRoot {
314        fn new(state: Rc<RefCell<ListState>>) -> Self {
315            let mut children = WidgetChildren::new();
316            children.push(StatusLabel::new(Rc::clone(&state)));
317            children.push(ContactRow::new(
318                "Ada",
319                sui_core::Point::new(320.0, 6.0),
320                Rc::clone(&state),
321            ));
322            children.push(ContactRow::new(
323                "Grace",
324                sui_core::Point::new(320.0, 6.0),
325                Rc::clone(&state),
326            ));
327            Self { state, children }
328        }
329    }
330
331    impl Widget for ListRoot {
332        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
333            let viewport = constraints.clamp(Size::new(480.0, 260.0));
334            let width = viewport.width - 48.0;
335
336            self.children
337                .measure_child(0, ctx, Constraints::tight(Size::new(width, 32.0)));
338            self.children
339                .measure_child(1, ctx, Constraints::tight(Size::new(width, 44.0)));
340            self.children
341                .measure_child(2, ctx, Constraints::tight(Size::new(width, 44.0)));
342
343            viewport
344        }
345
346        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: sui_core::Rect) {
347            let width = bounds.width() - 48.0;
348            self.children.arrange_child(
349                0,
350                ctx,
351                sui_core::Rect::new(bounds.x() + 24.0, bounds.y() + 20.0, width, 32.0),
352            );
353            self.children.arrange_child(
354                1,
355                ctx,
356                sui_core::Rect::new(bounds.x() + 24.0, bounds.y() + 72.0, width, 44.0),
357            );
358            self.children.arrange_child(
359                2,
360                ctx,
361                sui_core::Rect::new(bounds.x() + 24.0, bounds.y() + 128.0, width, 44.0),
362            );
363        }
364
365        fn paint(&self, ctx: &mut PaintCtx) {
366            let _ = &self.state;
367            ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
368            self.children.paint(ctx);
369        }
370
371        fn semantics(&self, ctx: &mut SemanticsCtx) {
372            let mut root = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Window, ctx.bounds());
373            root.name = Some("List Harness Window".to_string());
374            ctx.push(root);
375            self.children.semantics(ctx);
376        }
377
378        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
379            self.children.visit_children(visitor);
380        }
381
382        fn visit_children_mut(&mut self, visitor: &mut dyn sui_runtime::WidgetPodMutVisitor) {
383            self.children.visit_children_mut(visitor);
384        }
385    }
386
387    struct StatusLabel {
388        state: Rc<RefCell<ListState>>,
389    }
390
391    impl StatusLabel {
392        fn new(state: Rc<RefCell<ListState>>) -> Self {
393            Self { state }
394        }
395    }
396
397    impl Widget for StatusLabel {
398        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
399            constraints.clamp(Size::new(320.0, 32.0))
400        }
401
402        fn paint(&self, ctx: &mut PaintCtx) {
403            ctx.label(
404                ctx.bounds(),
405                format!("Selected: {}", self.state.borrow().selected),
406                Color::rgba(0.95, 0.96, 0.98, 1.0),
407            );
408        }
409
410        fn semantics(&self, ctx: &mut SemanticsCtx) {
411            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
412            node.name = Some(format!("Selected: {}", self.state.borrow().selected));
413            ctx.push(node);
414        }
415    }
416
417    struct ContactRow {
418        name: String,
419        button_origin: sui_core::Point,
420        children: WidgetChildren,
421    }
422
423    impl ContactRow {
424        fn new(name: &str, button_origin: sui_core::Point, state: Rc<RefCell<ListState>>) -> Self {
425            let mut children = WidgetChildren::new();
426            children.push(RowButton::new(name.to_string(), state));
427            Self {
428                name: name.to_string(),
429                button_origin,
430                children,
431            }
432        }
433    }
434
435    impl Widget for ContactRow {
436        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
437            let size = constraints.clamp(Size::new(360.0, 44.0));
438            self.children
439                .measure_child(0, ctx, Constraints::tight(Size::new(120.0, 32.0)));
440            size
441        }
442
443        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: sui_core::Rect) {
444            self.children.arrange_child(
445                0,
446                ctx,
447                sui_core::Rect::new(
448                    bounds.x() + self.button_origin.x,
449                    bounds.y() + self.button_origin.y,
450                    120.0,
451                    32.0,
452                ),
453            );
454        }
455
456        fn paint(&self, ctx: &mut PaintCtx) {
457            ctx.fill_bounds(Color::rgba(0.13, 0.15, 0.20, 1.0));
458            ctx.label(
459                sui_core::Rect::new(ctx.bounds().x() + 12.0, ctx.bounds().y() + 8.0, 140.0, 24.0),
460                &self.name,
461                Color::rgba(0.95, 0.96, 0.98, 1.0),
462            );
463            self.children.paint(ctx);
464        }
465
466        fn semantics(&self, ctx: &mut SemanticsCtx) {
467            let mut node = SemanticsNode::new(
468                ctx.widget_id(),
469                SemanticsRole::GenericContainer,
470                ctx.bounds(),
471            );
472            node.description = Some(self.name.clone());
473            ctx.push(node);
474            self.children.semantics(ctx);
475        }
476
477        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
478            self.children.visit_children(visitor);
479        }
480
481        fn visit_children_mut(&mut self, visitor: &mut dyn sui_runtime::WidgetPodMutVisitor) {
482            self.children.visit_children_mut(visitor);
483        }
484    }
485
486    struct RowButton {
487        label: String,
488        state: Rc<RefCell<ListState>>,
489    }
490
491    impl RowButton {
492        fn new(label: String, state: Rc<RefCell<ListState>>) -> Self {
493            Self { label, state }
494        }
495    }
496
497    impl Widget for RowButton {
498        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
499            match event {
500                Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
501                    self.state.borrow_mut().selected = self.label.clone();
502                    ctx.request_focus();
503                    ctx.request_paint();
504                    ctx.request_semantics();
505                    ctx.set_handled();
506                }
507                _ => {}
508            }
509        }
510
511        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
512            constraints.clamp(Size::new(120.0, 32.0))
513        }
514
515        fn paint(&self, ctx: &mut PaintCtx) {
516            let color = if ctx.is_focused() {
517                Color::rgba(0.25, 0.52, 0.88, 1.0)
518            } else {
519                Color::rgba(0.17, 0.24, 0.37, 1.0)
520            };
521            ctx.fill_bounds(color);
522            ctx.label(ctx.bounds(), "Select", Color::rgba(0.95, 0.96, 0.98, 1.0));
523        }
524
525        fn semantics(&self, ctx: &mut SemanticsCtx) {
526            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
527            node.name = Some("Select".to_string());
528            node.actions = vec![SemanticsAction::Focus, SemanticsAction::Activate];
529            ctx.push(node);
530        }
531
532        fn accepts_focus(&self) -> bool {
533            true
534        }
535
536        fn focus_changed(&mut self, ctx: &mut EventCtx, _focused: bool) {
537            ctx.request_paint();
538            ctx.request_semantics();
539        }
540    }
541
542    fn build_list_app() -> Result<TestApp> {
543        TestApp::new(|| {
544            let state = Rc::new(RefCell::new(ListState::default()));
545            Application::new().window(
546                WindowBuilder::new()
547                    .title("List Harness")
548                    .root(ListRoot::new(state)),
549            )
550        })
551    }
552
553    struct ScrollHarness {
554        offset_y: f32,
555        child: SingleChild,
556    }
557
558    impl ScrollHarness {
559        fn new() -> Self {
560            Self {
561                offset_y: 0.0,
562                child: SingleChild::new(ScrollContent),
563            }
564        }
565    }
566
567    impl Widget for ScrollHarness {
568        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
569            match event {
570                Event::Pointer(pointer)
571                    if pointer.kind == PointerEventKind::Scroll
572                        && ctx.bounds().contains(pointer.position) =>
573                {
574                    let delta = pointer
575                        .scroll_delta
576                        .map(|delta| match delta {
577                            sui_core::ScrollDelta::Lines(delta) => {
578                                Vector::new(delta.x * 40.0, delta.y * 40.0)
579                            }
580                            sui_core::ScrollDelta::Pixels(delta) => delta,
581                        })
582                        .unwrap_or(pointer.delta);
583                    let next = (self.offset_y - delta.y).clamp(0.0, 120.0);
584                    if (next - self.offset_y).abs() > f32::EPSILON {
585                        self.offset_y = next;
586                        ctx.request_arrange();
587                        ctx.request_paint();
588                        ctx.request_semantics();
589                        ctx.set_handled();
590                    }
591                }
592                Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
593                    ctx.request_focus();
594                    ctx.request_semantics();
595                }
596                _ => {}
597            }
598        }
599
600        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
601            let viewport = constraints.clamp(Size::new(160.0, 80.0));
602            self.child
603                .measure(ctx, Constraints::tight(Size::new(160.0, 200.0)));
604            viewport
605        }
606
607        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: sui_core::Rect) {
608            self.child.arrange(
609                ctx,
610                sui_core::Rect::new(bounds.x(), bounds.y() - self.offset_y, 160.0, 200.0),
611            );
612        }
613
614        fn paint(&self, ctx: &mut PaintCtx) {
615            ctx.clear(Color::rgba(0.05, 0.06, 0.08, 1.0));
616            ctx.push_clip_rect(ctx.bounds());
617            self.child.paint(ctx);
618            ctx.pop_clip();
619        }
620
621        fn semantics(&self, ctx: &mut SemanticsCtx) {
622            let mut node =
623                SemanticsNode::new(ctx.widget_id(), SemanticsRole::ScrollView, ctx.bounds());
624            node.name = Some("Scroll Harness".to_string());
625            node.actions = vec![SemanticsAction::Focus];
626            node.state.focused = ctx.is_focused();
627            ctx.push(node);
628            self.child.semantics(ctx);
629        }
630
631        fn accepts_focus(&self) -> bool {
632            true
633        }
634
635        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
636            self.child.visit_children(visitor);
637        }
638
639        fn visit_children_mut(&mut self, visitor: &mut dyn sui_runtime::WidgetPodMutVisitor) {
640            self.child.visit_children_mut(visitor);
641        }
642    }
643
644    struct ScrollContent;
645
646    impl Widget for ScrollContent {
647        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
648            constraints.clamp(Size::new(160.0, 200.0))
649        }
650
651        fn paint(&self, ctx: &mut PaintCtx) {
652            ctx.fill_rect(
653                sui_core::Rect::new(ctx.bounds().x(), ctx.bounds().y(), 160.0, 100.0),
654                Color::rgba(0.18, 0.32, 0.68, 1.0),
655            );
656            ctx.fill_rect(
657                sui_core::Rect::new(ctx.bounds().x(), ctx.bounds().y() + 100.0, 160.0, 100.0),
658                Color::rgba(0.78, 0.32, 0.18, 1.0),
659            );
660        }
661
662        fn semantics(&self, ctx: &mut SemanticsCtx) {
663            let mut node = SemanticsNode::new(
664                ctx.widget_id(),
665                SemanticsRole::GenericContainer,
666                ctx.bounds(),
667            );
668            node.name = Some("Scroll Content".to_string());
669            ctx.push(node);
670        }
671    }
672
673    #[derive(Default)]
674    struct NonIdleWidget {
675        timer: Option<TimerToken>,
676    }
677
678    impl Widget for NonIdleWidget {
679        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
680            match event {
681                Event::Window(WindowEvent::RedrawRequested) if self.timer.is_none() => {
682                    self.timer = Some(ctx.schedule_timer_after(0.0));
683                }
684                Event::Wake(WakeEvent::Timer { token, .. }) if self.timer == Some(*token) => {
685                    self.timer = Some(ctx.schedule_timer_after(0.0));
686                    ctx.request_paint();
687                    ctx.set_handled();
688                }
689                _ => {}
690            }
691        }
692
693        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
694            constraints.clamp(Size::new(48.0, 48.0))
695        }
696
697        fn paint(&self, ctx: &mut PaintCtx) {
698            ctx.fill_rect(ctx.bounds(), Color::rgba(0.8, 0.2, 0.2, 1.0));
699        }
700
701        fn semantics(&self, ctx: &mut SemanticsCtx) {
702            let mut node = SemanticsNode::new(
703                ctx.widget_id(),
704                SemanticsRole::GenericContainer,
705                ctx.bounds(),
706            );
707            node.name = Some("Non-idle".to_string());
708            ctx.push(node);
709        }
710    }
711
712    fn build_scroll_app() -> Result<TestApp> {
713        TestApp::new(|| {
714            Application::new().window(
715                WindowBuilder::new()
716                    .title("Scroll Harness")
717                    .root(ScrollHarness::new()),
718            )
719        })
720    }
721
722    fn build_non_idle_app() -> Result<TestApp> {
723        let runtime = Application::new()
724            .window(
725                WindowBuilder::new()
726                    .title("Non-idle Harness")
727                    .root(NonIdleWidget::default()),
728            )
729            .build()?;
730        TestApp::from_runtime_with_frame_budget(runtime, 2)
731    }
732
733    #[test]
734    fn locators_actions_and_focus_work_end_to_end() -> Result<()> {
735        let app = build_app()?;
736        let window = app.main_window()?;
737        let save = window.get_by_role(SemanticsRole::Button).with_name("Save");
738
739        save.expect().to_be_visible()?;
740        save.hover()?;
741        save.click()?;
742        save.expect().to_be_focused()?;
743        save.press("Enter")?;
744
745        let focused = window.focused().with_name("Save");
746        focused.expect().to_have_count(1)?;
747        window.get_by_text("Activated").expect().to_be_visible()?;
748
749        Ok(())
750    }
751
752    #[test]
753    fn fill_and_virtual_time_waiting_work() -> Result<()> {
754        let app = build_app()?;
755        let window = app.main_window()?;
756
757        window
758            .get_by_role(SemanticsRole::TextInput)
759            .with_name("Name")
760            .fill("Ada")?;
761        window
762            .get_by_role(SemanticsRole::TextInput)
763            .with_name("Name")
764            .expect()
765            .to_have_value("Ada")?;
766
767        window
768            .get_by_role(SemanticsRole::Button)
769            .with_name("Save")
770            .click()?;
771        window.get_by_text("Saved").expect().to_be_visible()?;
772
773        Ok(())
774    }
775
776    #[test]
777    fn locator_scroll_updates_child_layout_and_screenshot() -> Result<()> {
778        let app = build_scroll_app()?;
779        let window = app.main_window()?;
780        let scroll = window
781            .get_by_role(SemanticsRole::ScrollView)
782            .with_name("Scroll Harness");
783
784        let before = scroll.capture_screenshot()?;
785        let before_snapshot = window.snapshot()?;
786        let before_child = before_snapshot
787            .widget_graph
788            .nodes
789            .iter()
790            .find(|node| node.bounds.width() == 160.0 && node.bounds.height() == 200.0)
791            .expect("scroll content node present");
792
793        scroll.scroll_pixels(Vector::new(0.0, -80.0))?;
794
795        let after = scroll.capture_screenshot()?;
796        let after_snapshot = window.snapshot()?;
797        let after_child = after_snapshot
798            .widget_graph
799            .nodes
800            .iter()
801            .find(|node| node.bounds.width() == 160.0 && node.bounds.height() == 200.0)
802            .expect("scroll content node present after scroll");
803
804        assert_ne!(before, after);
805        assert!(after_child.bounds.y() < before_child.bounds.y());
806
807        Ok(())
808    }
809
810    #[test]
811    fn failures_include_semantics_and_graph_diagnostics() {
812        let app = build_app().unwrap();
813        let window = app.main_window().unwrap();
814        let error = window
815            .get_by_text("missing")
816            .expect()
817            .with_timeout(0.0)
818            .to_be_visible()
819            .unwrap_err();
820
821        assert!(error.message().contains("selector: text=\"missing\""));
822        assert!(error.message().contains("Semantics snapshot:"));
823        assert!(error.message().contains("Widget graph:"));
824    }
825
826    #[test]
827    fn run_until_idle_times_out_when_headless_work_never_settles() -> Result<()> {
828        let app = build_non_idle_app()?;
829        app.set_default_timeout(0.01)?;
830        let window = app.main_window()?;
831
832        let error = window.run_until_idle().unwrap_err();
833        assert!(
834            error
835                .message()
836                .contains("headless harness idle did not complete within"),
837            "{error}"
838        );
839
840        Ok(())
841    }
842
843    #[test]
844    fn scoped_descendant_locators_target_repeated_widgets() -> Result<()> {
845        let app = build_list_app()?;
846        let window = app.main_window()?;
847
848        window
849            .get_by_role(SemanticsRole::Button)
850            .with_name("Select")
851            .expect()
852            .to_have_count(2)?;
853
854        let grace_row = window
855            .get_by_role(SemanticsRole::GenericContainer)
856            .with_description("Grace");
857
858        grace_row
859            .get_by_role(SemanticsRole::Button)
860            .with_name("Select")
861            .click()?;
862
863        window
864            .get_by_text("Selected: Grace")
865            .expect()
866            .to_be_visible()?;
867
868        Ok(())
869    }
870
871    #[test]
872    fn screenshot_capture_and_artifact_bundles_work() -> Result<()> {
873        let app = build_app()?;
874        let window = app.main_window()?;
875
876        let screenshot = window.capture_screenshot()?;
877        assert!(screenshot.width() > 0);
878        assert!(screenshot.height() > 0);
879
880        let artifacts = window.capture_artifacts()?;
881        assert!(artifacts.screenshot.is_some());
882        assert!(artifacts.semantics_overlay.is_some());
883        assert!(artifacts.widget_overlay.is_some());
884        assert!(artifacts.snapshot.scene_summary.is_some());
885
886        let dir = unique_temp_path("artifacts");
887        artifacts.write_to_dir(&dir)?;
888
889        assert!(dir.join("summary.txt").exists());
890        assert!(dir.join("semantics.txt").exists());
891        assert!(dir.join("widget-graph.txt").exists());
892        assert!(dir.join("scene.txt").exists());
893        assert!(dir.join("screenshot.png").exists());
894        assert!(dir.join("semantics-overlay.png").exists());
895        assert!(dir.join("widget-overlay.png").exists());
896
897        Ok(())
898    }
899
900    #[test]
901    fn screenshot_expectations_compare_against_png_baselines() -> Result<()> {
902        let app = build_app()?;
903        let window = app.main_window()?;
904        let save = window.get_by_role(SemanticsRole::Button).with_name("Save");
905        let baseline = unique_temp_path("save-button.png");
906
907        save.capture_screenshot()?.write_png(&baseline)?;
908        save.expect().to_match_screenshot(&baseline)?;
909
910        save.click()?;
911
912        let error = save
913            .expect()
914            .with_timeout(0.0)
915            .to_match_screenshot(&baseline)
916            .unwrap_err();
917        let actual = baseline.with_file_name("save-button.actual.png");
918        let diff = baseline.with_file_name("save-button.diff.png");
919
920        assert!(actual.exists());
921        assert!(diff.exists());
922        assert!(error.message().contains("screenshot assertion failed"));
923
924        Ok(())
925    }
926
927    fn unique_temp_path(name: &str) -> PathBuf {
928        let nonce = SystemTime::now()
929            .duration_since(UNIX_EPOCH)
930            .expect("system time is after unix epoch")
931            .as_nanos();
932        let dir =
933            std::env::temp_dir().join(format!("sui-testing-{}-{}", std::process::id(), nonce));
934        fs::create_dir_all(&dir).expect("temporary screenshot directory created");
935        dir.join(name)
936    }
937}