Skip to main content

gpui_material_foundation/
test.rs

1//! Headless UI integration testing helpers for GPUI Material components and applications.
2//!
3//! Enable `test-support` under `[dev-dependencies]` so production builds carry
4//! zero observation overhead. Render views inside a headless window opened via
5//! [`crate::MaterialRoot::open_window`], drive interactions through
6//! [`TestWindowExt`] / [`TestEventExt`] / [`TestInput`], and assert both native
7//! accessibility [`ElementSnapshot`] properties and application state.
8//!
9//! [`ElementSnapshot`] values are immutable. Call [`TestWindowExt::render_frame`]
10//! after external state changes, or use [`TestAppContextExt::wait_for`] outside
11//! `update_window` for asynchronous and deferred updates.
12
13use std::future::Future;
14use std::time::Duration;
15
16use gpui::{
17    AnyWindowHandle, App, AppContext, Corners, Edges, ElementId, InputEvent, KeyDownEvent,
18    KeyUpEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent,
19    MouseMoveEvent, MouseUpEvent, Pixels, Point, Quad, ScrollDelta, ScrollEvent, TestAppContext,
20    Window, point, px,
21};
22use gpui_base::test_support as observation;
23
24mod events;
25mod input;
26mod query;
27
28pub use events::TestEventExt;
29pub use gpui_base::TestSupportExt;
30pub use gpui_base::test_support::{ElementSnapshot, TextSnapshot};
31pub use input::TestInput;
32pub use query::TestQueryExt;
33
34/// Returns painted quads from the last frame with split border/background slices
35/// sharing identical bounds and paint properties merged back together.
36pub fn painted_quads(window: &Window) -> Vec<Quad> {
37    let mut merged: Vec<Quad> = Vec::new();
38    for quad in window.painted_quads() {
39        if let Some(last) = merged.last_mut()
40            && last.bounds == quad.bounds
41            && last.background == quad.background
42            && last.border_color == quad.border_color
43            && last.border_style == quad.border_style
44        {
45            if last.corner_radii == Corners::default() {
46                last.corner_radii = quad.corner_radii;
47            }
48            if last.border_widths == Edges::default() {
49                last.border_widths = quad.border_widths;
50            }
51            last.content_mask.bounds = last.content_mask.bounds.union(&quad.content_mask.bounds);
52            continue;
53        }
54        merged.push(quad);
55    }
56    merged
57}
58
59/// High-level query and native event dispatch operations on a GPUI [`Window`].
60pub trait TestWindowExt {
61    /// Returns the uniquely matching observed element from the last completed frame.
62    ///
63    /// Panics with all registered element paths if the target is missing or ambiguous.
64    fn find(&self, id: impl Into<ElementId>) -> ElementSnapshot;
65
66    /// Returns the uniquely matching observed element if present, or `None` when absent.
67    ///
68    /// Still panics if multiple registered paths match `id` in this scope.
69    fn try_find(&self, id: impl Into<ElementId>) -> Option<ElementSnapshot>;
70
71    /// Returns all observed matches for `id` from the last completed frame, including
72    /// invisible elements, ordered by bounds origin `(y, x)`.
73    fn find_all(&self, id: impl Into<ElementId>) -> Vec<ElementSnapshot>;
74
75    /// Narrows subsequent queries and interactions to a GPUI [`ElementId`] scope
76    /// without requiring an extra layout container.
77    fn within(&mut self, id: impl Into<ElementId>) -> ScopedWindow<'_>;
78
79    /// Refreshes and draws one frame so snapshots reflect external state changes.
80    fn render_frame(&mut self, cx: &mut App);
81
82    /// Moves the pointer to the target center and dispatches a left click.
83    fn click(&mut self, id: impl Into<ElementId>, cx: &mut App);
84
85    /// Clicks at a pixel offset relative to the target's top-left corner.
86    fn click_at(&mut self, id: impl Into<ElementId>, offset: Point<Pixels>, cx: &mut App);
87
88    /// Dispatches a configurable click sequence, temporarily applying and then
89    /// restoring window modifiers while preserving Caps Lock.
90    fn click_with_options(&mut self, id: impl Into<ElementId>, options: ClickOptions, cx: &mut App);
91
92    /// Dispatches a centered left click with temporary modifiers, restoring previous
93    /// modifiers afterward.
94    fn click_with_modifiers(
95        &mut self,
96        id: impl Into<ElementId>,
97        modifiers: Modifiers,
98        cx: &mut App,
99    ) {
100        self.click_with_options(id, ClickOptions::new().with_modifiers(modifiers), cx);
101    }
102
103    /// Dispatches a centered right click on `id`.
104    fn right_click(&mut self, id: impl Into<ElementId>, cx: &mut App);
105
106    /// Dispatches a centered left double-click on `id`.
107    fn double_click(&mut self, id: impl Into<ElementId>, cx: &mut App);
108
109    /// Moves the pointer to the center of `id` without pressing a mouse button.
110    fn hover(&mut self, id: impl Into<ElementId>, cx: &mut App);
111
112    /// Moves the pointer to `id` and dispatches a native wheel scroll event.
113    fn scroll(&mut self, id: impl Into<ElementId>, delta: ScrollDelta, cx: &mut App);
114
115    /// Drags with the left mouse button between two window-local positions using
116    /// interpolated pointer moves and native hit testing.
117    fn drag(&mut self, from: Point<Pixels>, to: Point<Pixels>, cx: &mut App);
118
119    /// Drags from the center of `from` to the center of `to` using native hit testing.
120    fn drag_to(&mut self, from: impl Into<ElementId>, to: impl Into<ElementId>, cx: &mut App);
121
122    /// Dispatches native key-down and key-up events for a GPUI keystroke string
123    /// (such as `"backspace"`, `"enter"`, `"tab"`, or `"secondary-c"`).
124    ///
125    /// `"enter"` and `"tab"` invoke key bindings without synthesizing IME text.
126    fn press(&mut self, key: &str, cx: &mut App);
127
128    /// Types Unicode text character-by-character into the current keyboard focus.
129    fn input(&mut self, text: &str, cx: &mut App);
130}
131
132/// Configuration for [`TestWindowExt::click_with_options`].
133///
134/// Defaults to a single centered left click with no modifiers.
135#[derive(Clone, Copy, Debug)]
136pub struct ClickOptions {
137    offset: Option<Point<Pixels>>,
138    button: MouseButton,
139    count: usize,
140    modifiers: Modifiers,
141}
142
143impl Default for ClickOptions {
144    fn default() -> Self {
145        Self {
146            offset: None,
147            button: MouseButton::Left,
148            count: 1,
149            modifiers: Modifiers::default(),
150        }
151    }
152}
153
154impl ClickOptions {
155    /// Creates options for a single centered left click without modifiers.
156    pub fn new() -> Self {
157        Self::default()
158    }
159
160    /// Sets an offset relative to the target's top-left corner.
161    pub fn with_offset(mut self, offset: Point<Pixels>) -> Self {
162        self.offset = Some(offset);
163        self
164    }
165
166    /// Returns the configured local offset, or `None` for the element center.
167    pub fn offset(&self) -> Option<Point<Pixels>> {
168        self.offset
169    }
170
171    /// Sets the mouse button used for the click sequence.
172    pub fn with_button(mut self, button: MouseButton) -> Self {
173        self.button = button;
174        self
175    }
176
177    /// Returns the configured mouse button.
178    pub fn button(&self) -> MouseButton {
179        self.button
180    }
181
182    /// Sets the number of clicks. Panics if `count == 0`.
183    pub fn with_count(mut self, count: usize) -> Self {
184        assert!(count > 0, "click count must be positive");
185        self.count = count;
186        self
187    }
188
189    /// Returns the positive click count.
190    pub fn count(&self) -> usize {
191        self.count
192    }
193
194    /// Sets temporary keyboard modifiers applied for the duration of the click.
195    pub fn with_modifiers(mut self, modifiers: Modifiers) -> Self {
196        self.modifiers = modifiers;
197        self
198    }
199
200    /// Returns the configured modifier flags.
201    pub fn modifiers(&self) -> Modifiers {
202        self.modifiers
203    }
204}
205
206fn require(window: &Window, scope: &[ElementId], id: &ElementId) -> ElementSnapshot {
207    observation::find(window, scope, id).unwrap_or_else(|| {
208        panic!(
209            "missing ElementId {id:?} in scope {scope:?}. Registered paths: {}. \
210             Check the ID, .test_support() registration, and completed frame.",
211            observation::registered_paths(window)
212        )
213    })
214}
215
216fn target_position(
217    window: &Window,
218    scope: &[ElementId],
219    id: &ElementId,
220    offset: Option<Point<Pixels>>,
221) -> Point<Pixels> {
222    let target = require(window, scope, id);
223    assert!(
224        target.visible(),
225        "ElementId {id:?} is not visible (path {:?})",
226        target.path()
227    );
228    if let Some(offset) = offset {
229        let size = target.bounds().size;
230        assert!(
231            offset.x >= px(0.)
232                && offset.y >= px(0.)
233                && offset.x < size.width
234                && offset.y < size.height,
235            "click offset {offset:?} is outside ElementId {id:?} bounds {:?}",
236            target.bounds()
237        );
238        target.bounds().origin + offset
239    } else {
240        target.bounds().center()
241    }
242}
243
244pub(crate) fn move_pointer(
245    window: &mut Window,
246    position: Point<Pixels>,
247    pressed_button: Option<MouseButton>,
248    modifiers: Modifiers,
249    cx: &mut App,
250) {
251    window.dispatch_event(
252        MouseMoveEvent {
253            position,
254            pressed_button,
255            modifiers,
256        }
257        .to_platform_input(),
258        cx,
259    );
260    window.render_frame(cx);
261}
262
263pub(crate) fn mouse_down(
264    window: &mut Window,
265    position: Point<Pixels>,
266    button: MouseButton,
267    click_count: usize,
268    modifiers: Modifiers,
269    cx: &mut App,
270) {
271    window.dispatch_event(
272        MouseDownEvent {
273            button,
274            position,
275            modifiers,
276            click_count,
277            first_mouse: false,
278        }
279        .to_platform_input(),
280        cx,
281    );
282    window.render_frame(cx);
283}
284
285pub(crate) fn mouse_up(
286    window: &mut Window,
287    position: Point<Pixels>,
288    button: MouseButton,
289    click_count: usize,
290    modifiers: Modifiers,
291    cx: &mut App,
292) {
293    window.dispatch_event(
294        MouseUpEvent {
295            button,
296            position,
297            modifiers,
298            click_count,
299        }
300        .to_platform_input(),
301        cx,
302    );
303    window.render_frame(cx);
304}
305
306pub(crate) fn change_modifiers(window: &mut Window, modifiers: Modifiers, cx: &mut App) {
307    if window.modifiers() != modifiers {
308        window.dispatch_event(
309            ModifiersChangedEvent {
310                modifiers,
311                capslock: window.capslock(),
312            }
313            .to_platform_input(),
314            cx,
315        );
316        window.render_frame(cx);
317    }
318}
319
320fn click_target(
321    window: &mut Window,
322    scope: &[ElementId],
323    id: ElementId,
324    options: ClickOptions,
325    cx: &mut App,
326) {
327    let ClickOptions {
328        offset,
329        button,
330        count,
331        modifiers: _,
332    } = options;
333    window.render_frame(cx);
334    let modifiers = window.modifiers();
335    let position = target_position(window, scope, &id, offset);
336    move_pointer(window, position, None, modifiers, cx);
337    for click_count in 1..=count {
338        mouse_down(window, position, button, click_count, modifiers, cx);
339        mouse_up(window, position, button, click_count, modifiers, cx);
340    }
341}
342
343fn click_with_options_target(
344    window: &mut Window,
345    scope: &[ElementId],
346    id: ElementId,
347    options: ClickOptions,
348    cx: &mut App,
349) {
350    window.render_frame(cx);
351    target_position(window, scope, &id, options.offset);
352    let previous = window.modifiers();
353    change_modifiers(window, options.modifiers, cx);
354    click_target(window, scope, id, options, cx);
355    change_modifiers(window, previous, cx);
356}
357
358fn hover_target(window: &mut Window, scope: &[ElementId], id: ElementId, cx: &mut App) {
359    window.render_frame(cx);
360    let position = target_position(window, scope, &id, None);
361    move_pointer(window, position, None, window.modifiers(), cx);
362}
363
364fn scroll_target(
365    window: &mut Window,
366    scope: &[ElementId],
367    id: ElementId,
368    delta: ScrollDelta,
369    cx: &mut App,
370) {
371    window.render_frame(cx);
372    let position = target_position(window, scope, &id, None);
373    move_pointer(window, position, None, window.modifiers(), cx);
374    window.dispatch_event(
375        ScrollEvent {
376            position,
377            delta,
378            modifiers: window.modifiers(),
379            ..Default::default()
380        }
381        .to_platform_input(),
382        cx,
383    );
384    window.render_frame(cx);
385}
386
387fn drag_targets(
388    window: &mut Window,
389    scope: &[ElementId],
390    from: ElementId,
391    to: ElementId,
392    cx: &mut App,
393) {
394    window.render_frame(cx);
395    let from = target_position(window, scope, &from, None);
396    let to = target_position(window, scope, &to, None);
397    window.drag(from, to, cx);
398}
399
400impl TestWindowExt for Window {
401    fn find(&self, id: impl Into<ElementId>) -> ElementSnapshot {
402        require(self, &[], &id.into())
403    }
404
405    fn try_find(&self, id: impl Into<ElementId>) -> Option<ElementSnapshot> {
406        observation::find(self, &[], &id.into())
407    }
408
409    fn find_all(&self, id: impl Into<ElementId>) -> Vec<ElementSnapshot> {
410        observation::find_all(self, &[], &id.into())
411    }
412
413    fn within(&mut self, id: impl Into<ElementId>) -> ScopedWindow<'_> {
414        let scope = observation::scope(self, &[], &id.into());
415        ScopedWindow {
416            window: self,
417            scope,
418        }
419    }
420
421    fn render_frame(&mut self, cx: &mut App) {
422        self.refresh();
423        self.draw(cx).clear(cx);
424    }
425
426    fn click(&mut self, id: impl Into<ElementId>, cx: &mut App) {
427        click_target(self, &[], id.into(), ClickOptions::new(), cx);
428    }
429
430    fn click_at(&mut self, id: impl Into<ElementId>, offset: Point<Pixels>, cx: &mut App) {
431        click_target(
432            self,
433            &[],
434            id.into(),
435            ClickOptions::new().with_offset(offset),
436            cx,
437        );
438    }
439
440    fn click_with_options(
441        &mut self,
442        id: impl Into<ElementId>,
443        options: ClickOptions,
444        cx: &mut App,
445    ) {
446        click_with_options_target(self, &[], id.into(), options, cx);
447    }
448
449    fn right_click(&mut self, id: impl Into<ElementId>, cx: &mut App) {
450        click_target(
451            self,
452            &[],
453            id.into(),
454            ClickOptions::new().with_button(MouseButton::Right),
455            cx,
456        );
457    }
458
459    fn double_click(&mut self, id: impl Into<ElementId>, cx: &mut App) {
460        click_target(self, &[], id.into(), ClickOptions::new().with_count(2), cx);
461    }
462
463    fn hover(&mut self, id: impl Into<ElementId>, cx: &mut App) {
464        hover_target(self, &[], id.into(), cx);
465    }
466
467    fn scroll(&mut self, id: impl Into<ElementId>, delta: ScrollDelta, cx: &mut App) {
468        scroll_target(self, &[], id.into(), delta, cx);
469    }
470
471    fn drag_to(&mut self, from: impl Into<ElementId>, to: impl Into<ElementId>, cx: &mut App) {
472        drag_targets(self, &[], from.into(), to.into(), cx);
473    }
474
475    fn drag(&mut self, from: Point<Pixels>, to: Point<Pixels>, cx: &mut App) {
476        self.render_frame(cx);
477        let modifiers = self.modifiers();
478        move_pointer(self, from, None, modifiers, cx);
479        mouse_down(self, from, MouseButton::Left, 1, modifiers, cx);
480        for step in 1..=8 {
481            let fraction = step as f32 / 8.;
482            move_pointer(
483                self,
484                point(
485                    from.x + (to.x - from.x) * fraction,
486                    from.y + (to.y - from.y) * fraction,
487                ),
488                Some(MouseButton::Left),
489                modifiers,
490                cx,
491            );
492        }
493        mouse_up(self, to, MouseButton::Left, 1, modifiers, cx);
494    }
495
496    fn press(&mut self, key: &str, cx: &mut App) {
497        let key = Keystroke::parse_with_os(key, cx.platform_info().os)
498            .unwrap_or_else(|error| panic!("invalid test keystroke: {error}"));
499        self.render_frame(cx);
500        press_key(self, key, cx);
501        self.render_frame(cx);
502    }
503
504    fn input(&mut self, text: &str, cx: &mut App) {
505        input_text(self, text, None, cx);
506    }
507}
508
509/// A borrowed GPUI [`ElementId`] scope returned by [`TestWindowExt::within`].
510///
511/// Restricts descendant queries and scoped keyboard checks without inserting any
512/// extra layout wrapper into the element tree.
513pub struct ScopedWindow<'a> {
514    pub(crate) window: &'a mut Window,
515    pub(crate) scope: Vec<ElementId>,
516}
517
518impl ScopedWindow<'_> {
519    /// Returns the uniquely matching observed descendant in this scope.
520    pub fn find(&self, id: impl Into<ElementId>) -> ElementSnapshot {
521        require(self.window, &self.scope, &id.into())
522    }
523
524    /// Returns the uniquely matching observed descendant in this scope, if present.
525    pub fn try_find(&self, id: impl Into<ElementId>) -> Option<ElementSnapshot> {
526        observation::find(self.window, &self.scope, &id.into())
527    }
528
529    /// Returns all observed descendants matching `id` in this scope, ordered by `(y, x)`.
530    pub fn find_all(&self, id: impl Into<ElementId>) -> Vec<ElementSnapshot> {
531        observation::find_all(self.window, &self.scope, &id.into())
532    }
533
534    /// Narrows further to a nested [`ElementId`] scope.
535    pub fn within(&mut self, id: impl Into<ElementId>) -> ScopedWindow<'_> {
536        let scope = observation::scope(self.window, &self.scope, &id.into());
537        ScopedWindow {
538            window: self.window,
539            scope,
540        }
541    }
542
543    /// Dispatches a centered left click on a descendant in this scope.
544    pub fn click(&mut self, id: impl Into<ElementId>, cx: &mut App) {
545        click_target(self.window, &self.scope, id.into(), ClickOptions::new(), cx);
546    }
547
548    /// Clicks a descendant at a local pixel offset from its top-left corner.
549    pub fn click_at(&mut self, id: impl Into<ElementId>, offset: Point<Pixels>, cx: &mut App) {
550        click_target(
551            self.window,
552            &self.scope,
553            id.into(),
554            ClickOptions::new().with_offset(offset),
555            cx,
556        );
557    }
558
559    /// Dispatches a configurable click inside this scope, restoring prior modifiers.
560    pub fn click_with_options(
561        &mut self,
562        id: impl Into<ElementId>,
563        options: ClickOptions,
564        cx: &mut App,
565    ) {
566        click_with_options_target(self.window, &self.scope, id.into(), options, cx);
567    }
568
569    /// Dispatches a centered left click with temporary modifiers inside this scope.
570    pub fn click_with_modifiers(
571        &mut self,
572        id: impl Into<ElementId>,
573        modifiers: Modifiers,
574        cx: &mut App,
575    ) {
576        self.click_with_options(id, ClickOptions::new().with_modifiers(modifiers), cx);
577    }
578
579    /// Dispatches a centered right click on a descendant in this scope.
580    pub fn right_click(&mut self, id: impl Into<ElementId>, cx: &mut App) {
581        click_target(
582            self.window,
583            &self.scope,
584            id.into(),
585            ClickOptions::new().with_button(MouseButton::Right),
586            cx,
587        );
588    }
589
590    /// Dispatches a centered left double-click on a descendant in this scope.
591    pub fn double_click(&mut self, id: impl Into<ElementId>, cx: &mut App) {
592        click_target(
593            self.window,
594            &self.scope,
595            id.into(),
596            ClickOptions::new().with_count(2),
597            cx,
598        );
599    }
600
601    /// Moves the pointer to the center of a descendant in this scope.
602    pub fn hover(&mut self, id: impl Into<ElementId>, cx: &mut App) {
603        hover_target(self.window, &self.scope, id.into(), cx);
604    }
605
606    /// Dispatches a wheel scroll event over a descendant in this scope.
607    pub fn scroll(&mut self, id: impl Into<ElementId>, delta: ScrollDelta, cx: &mut App) {
608        scroll_target(self.window, &self.scope, id.into(), delta, cx);
609    }
610
611    /// Drags between two descendants resolved within this scope.
612    pub fn drag_to(&mut self, from: impl Into<ElementId>, to: impl Into<ElementId>, cx: &mut App) {
613        drag_targets(self.window, &self.scope, from.into(), to.into(), cx);
614    }
615
616    /// Dispatches a keystroke to current focus, requiring an observed focus binding
617    /// inside this scope.
618    pub fn press(&mut self, key: &str, cx: &mut App) {
619        let key = Keystroke::parse_with_os(key, cx.platform_info().os)
620            .unwrap_or_else(|error| panic!("invalid test keystroke: {error}"));
621        self.window.render_frame(cx);
622        require_scope_focus(self.window, &self.scope);
623        press_key(self.window, key, cx);
624        self.window.render_frame(cx);
625    }
626
627    /// Types text into current focus, checking observed focus membership inside this
628    /// scope before every character.
629    pub fn input(&mut self, text: &str, cx: &mut App) {
630        input_text(self.window, text, Some(&self.scope), cx);
631    }
632}
633
634fn require_scope_focus(window: &Window, scope: &[ElementId]) {
635    assert!(
636        observation::has_observed_focus(window, scope),
637        "no observed keyboard focus inside scope {scope:?}; register the focused control \
638         with .test_support().track_focus(&handle) inside this scope before press/input"
639    );
640}
641
642fn press_key(window: &mut Window, key: Keystroke, cx: &mut App) {
643    let key = if matches!(key.key.as_str(), "enter" | "tab") {
644        window.dispatch_event(
645            KeyDownEvent {
646                keystroke: key.clone(),
647                is_held: false,
648                prefer_character_input: false,
649            }
650            .to_platform_input(),
651            cx,
652        );
653        key
654    } else {
655        let key = key.with_simulated_ime();
656        window.dispatch_keystroke(key.clone(), cx);
657        key
658    };
659    window.dispatch_event(KeyUpEvent { keystroke: key }.to_platform_input(), cx);
660}
661
662fn input_text(window: &mut Window, text: &str, scope: Option<&[ElementId]>, cx: &mut App) {
663    window.render_frame(cx);
664    for character in text.chars() {
665        if let Some(scope) = scope {
666            require_scope_focus(window, scope);
667        }
668        let text = character.to_string();
669        let mut key = Keystroke::parse_with_os(&text, cx.platform_info().os)
670            .expect("a Unicode character is a valid GPUI keystroke");
671        key.key_char = Some(text);
672        window.dispatch_keystroke(key, cx);
673        window.render_frame(cx);
674    }
675}
676
677/// Executor-aware asynchronous helpers on [`TestAppContext`] that run outside
678/// a borrowed window update.
679pub trait TestAppContextExt {
680    /// Repeatedly refreshes frames on the GPUI test clock (every 10 ms) until
681    /// `predicate` returns `true`, or panics with all registered element paths
682    /// once `timeout` elapses.
683    fn wait_for(
684        &mut self,
685        window: AnyWindowHandle,
686        timeout: Duration,
687        predicate: impl FnMut(&mut Window, &mut App) -> bool,
688    ) -> impl Future<Output = ()>;
689}
690
691impl TestAppContextExt for TestAppContext {
692    async fn wait_for(
693        &mut self,
694        handle: AnyWindowHandle,
695        timeout: Duration,
696        mut predicate: impl FnMut(&mut Window, &mut App) -> bool,
697    ) {
698        let mut elapsed = Duration::ZERO;
699        loop {
700            let (ready, paths) = self
701                .update_window(handle, |_, window, cx| {
702                    window.render_frame(cx);
703                    let ready = predicate(window, cx);
704                    let paths = if !ready && elapsed >= timeout {
705                        observation::registered_paths(window)
706                    } else {
707                        String::new()
708                    };
709                    (ready, paths)
710                })
711                .expect("test window closed while waiting");
712            if ready {
713                return;
714            }
715            assert!(
716                elapsed < timeout,
717                "UI condition timed out after {timeout:?}. Registered paths: {paths}"
718            );
719            let interval = Duration::from_millis(10).min(timeout - elapsed);
720            self.executor().timer(interval).await;
721            elapsed += interval;
722        }
723    }
724}