test_context.rs

  1use crate::{
  2    Action, AnyView, AnyWindowHandle, AppCell, AppContext, AsyncAppContext, AvailableSpace,
  3    BackgroundExecutor, BorrowAppContext, Bounds, ClipboardItem, Context, DrawPhase, Drawable,
  4    Element, Empty, Entity, EventEmitter, ForegroundExecutor, Global, InputEvent, Keystroke, Model,
  5    ModelContext, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent,
  6    MouseUpEvent, Pixels, Platform, Point, Render, Result, Size, Task, TestDispatcher,
  7    TestPlatform, TestWindow, TextSystem, View, ViewContext, VisualContext, WindowContext,
  8    WindowHandle, WindowOptions,
  9};
 10use anyhow::{anyhow, bail};
 11use futures::{channel::oneshot, Stream, StreamExt};
 12use std::{cell::RefCell, future::Future, ops::Deref, rc::Rc, sync::Arc, time::Duration};
 13
 14/// A TestAppContext is provided to tests created with `#[gpui::test]`, it provides
 15/// an implementation of `Context` with additional methods that are useful in tests.
 16#[derive(Clone)]
 17pub struct TestAppContext {
 18    #[doc(hidden)]
 19    pub app: Rc<AppCell>,
 20    #[doc(hidden)]
 21    pub background_executor: BackgroundExecutor,
 22    #[doc(hidden)]
 23    pub foreground_executor: ForegroundExecutor,
 24    #[doc(hidden)]
 25    pub dispatcher: TestDispatcher,
 26    test_platform: Rc<TestPlatform>,
 27    text_system: Arc<TextSystem>,
 28    fn_name: Option<&'static str>,
 29    on_quit: Rc<RefCell<Vec<Box<dyn FnOnce() + 'static>>>>,
 30}
 31
 32impl Context for TestAppContext {
 33    type Result<T> = T;
 34
 35    fn new_model<T: 'static>(
 36        &mut self,
 37        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
 38    ) -> Self::Result<Model<T>>
 39    where
 40        T: 'static,
 41    {
 42        let mut app = self.app.borrow_mut();
 43        app.new_model(build_model)
 44    }
 45
 46    fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
 47        let mut app = self.app.borrow_mut();
 48        app.reserve_model()
 49    }
 50
 51    fn insert_model<T: 'static>(
 52        &mut self,
 53        reservation: crate::Reservation<T>,
 54        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
 55    ) -> Self::Result<Model<T>> {
 56        let mut app = self.app.borrow_mut();
 57        app.insert_model(reservation, build_model)
 58    }
 59
 60    fn update_model<T: 'static, R>(
 61        &mut self,
 62        handle: &Model<T>,
 63        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
 64    ) -> Self::Result<R> {
 65        let mut app = self.app.borrow_mut();
 66        app.update_model(handle, update)
 67    }
 68
 69    fn read_model<T, R>(
 70        &self,
 71        handle: &Model<T>,
 72        read: impl FnOnce(&T, &AppContext) -> R,
 73    ) -> Self::Result<R>
 74    where
 75        T: 'static,
 76    {
 77        let app = self.app.borrow();
 78        app.read_model(handle, read)
 79    }
 80
 81    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
 82    where
 83        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
 84    {
 85        let mut lock = self.app.borrow_mut();
 86        lock.update_window(window, f)
 87    }
 88
 89    fn read_window<T, R>(
 90        &self,
 91        window: &WindowHandle<T>,
 92        read: impl FnOnce(View<T>, &AppContext) -> R,
 93    ) -> Result<R>
 94    where
 95        T: 'static,
 96    {
 97        let app = self.app.borrow();
 98        app.read_window(window, read)
 99    }
100}
101
102impl TestAppContext {
103    /// Creates a new `TestAppContext`. Usually you can rely on `#[gpui::test]` to do this for you.
104    pub fn new(dispatcher: TestDispatcher, fn_name: Option<&'static str>) -> Self {
105        let arc_dispatcher = Arc::new(dispatcher.clone());
106        let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
107        let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
108        let platform = TestPlatform::new(background_executor.clone(), foreground_executor.clone());
109        let asset_source = Arc::new(());
110        let http_client = util::http::FakeHttpClient::with_404_response();
111        let text_system = Arc::new(TextSystem::new(platform.text_system()));
112
113        Self {
114            app: AppContext::new(platform.clone(), asset_source, http_client),
115            background_executor,
116            foreground_executor,
117            dispatcher: dispatcher.clone(),
118            test_platform: platform,
119            text_system,
120            fn_name,
121            on_quit: Rc::new(RefCell::new(Vec::default())),
122        }
123    }
124
125    /// The name of the test function that created this `TestAppContext`
126    pub fn test_function_name(&self) -> Option<&'static str> {
127        self.fn_name
128    }
129
130    /// Checks whether there have been any new path prompts received by the platform.
131    pub fn did_prompt_for_new_path(&self) -> bool {
132        self.test_platform.did_prompt_for_new_path()
133    }
134
135    /// returns a new `TestAppContext` re-using the same executors to interleave tasks.
136    pub fn new_app(&self) -> TestAppContext {
137        Self::new(self.dispatcher.clone(), self.fn_name)
138    }
139
140    /// Called by the test helper to end the test.
141    /// public so the macro can call it.
142    pub fn quit(&self) {
143        self.on_quit.borrow_mut().drain(..).for_each(|f| f());
144        self.app.borrow_mut().shutdown();
145    }
146
147    /// Register cleanup to run when the test ends.
148    pub fn on_quit(&mut self, f: impl FnOnce() + 'static) {
149        self.on_quit.borrow_mut().push(Box::new(f));
150    }
151
152    /// Schedules all windows to be redrawn on the next effect cycle.
153    pub fn refresh(&mut self) -> Result<()> {
154        let mut app = self.app.borrow_mut();
155        app.refresh();
156        Ok(())
157    }
158
159    /// Returns an executor (for running tasks in the background)
160    pub fn executor(&self) -> BackgroundExecutor {
161        self.background_executor.clone()
162    }
163
164    /// Returns an executor (for running tasks on the main thread)
165    pub fn foreground_executor(&self) -> &ForegroundExecutor {
166        &self.foreground_executor
167    }
168
169    /// Gives you an `&mut AppContext` for the duration of the closure
170    pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> R {
171        let mut cx = self.app.borrow_mut();
172        cx.update(f)
173    }
174
175    /// Gives you an `&AppContext` for the duration of the closure
176    pub fn read<R>(&self, f: impl FnOnce(&AppContext) -> R) -> R {
177        let cx = self.app.borrow();
178        f(&cx)
179    }
180
181    /// Adds a new window. The Window will always be backed by a `TestWindow` which
182    /// can be retrieved with `self.test_window(handle)`
183    pub fn add_window<F, V>(&mut self, build_window: F) -> WindowHandle<V>
184    where
185        F: FnOnce(&mut ViewContext<V>) -> V,
186        V: 'static + Render,
187    {
188        let mut cx = self.app.borrow_mut();
189
190        // Some tests rely on the window size matching the bounds of the test display
191        let bounds = Bounds::maximized(None, &mut cx);
192        cx.open_window(
193            WindowOptions {
194                bounds: Some(bounds),
195                ..Default::default()
196            },
197            |cx| cx.new_view(build_window),
198        )
199    }
200
201    /// Adds a new window with no content.
202    pub fn add_empty_window(&mut self) -> &mut VisualTestContext {
203        let mut cx = self.app.borrow_mut();
204        let bounds = Bounds::maximized(None, &mut cx);
205        let window = cx.open_window(
206            WindowOptions {
207                bounds: Some(bounds),
208                ..Default::default()
209            },
210            |cx| cx.new_view(|_| Empty),
211        );
212        drop(cx);
213        let cx = VisualTestContext::from_window(*window.deref(), self).as_mut();
214        cx.run_until_parked();
215        cx
216    }
217
218    /// Adds a new window, and returns its root view and a `VisualTestContext` which can be used
219    /// as a `WindowContext` for the rest of the test. Typically you would shadow this context with
220    /// the returned one. `let (view, cx) = cx.add_window_view(...);`
221    pub fn add_window_view<F, V>(&mut self, build_root_view: F) -> (View<V>, &mut VisualTestContext)
222    where
223        F: FnOnce(&mut ViewContext<V>) -> V,
224        V: 'static + Render,
225    {
226        let mut cx = self.app.borrow_mut();
227        let bounds = Bounds::maximized(None, &mut cx);
228        let window = cx.open_window(
229            WindowOptions {
230                bounds: Some(bounds),
231                ..Default::default()
232            },
233            |cx| cx.new_view(build_root_view),
234        );
235        drop(cx);
236        let view = window.root_view(self).unwrap();
237        let cx = VisualTestContext::from_window(*window.deref(), self).as_mut();
238        cx.run_until_parked();
239
240        // it might be nice to try and cleanup these at the end of each test.
241        (view, cx)
242    }
243
244    /// returns the TextSystem
245    pub fn text_system(&self) -> &Arc<TextSystem> {
246        &self.text_system
247    }
248
249    /// Simulates writing to the platform clipboard
250    pub fn write_to_clipboard(&self, item: ClipboardItem) {
251        self.test_platform.write_to_clipboard(item)
252    }
253
254    /// Simulates reading from the platform clipboard.
255    /// This will return the most recent value from `write_to_clipboard`.
256    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
257        self.test_platform.read_from_clipboard()
258    }
259
260    /// Simulates choosing a File in the platform's "Open" dialog.
261    pub fn simulate_new_path_selection(
262        &self,
263        select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
264    ) {
265        self.test_platform.simulate_new_path_selection(select_path);
266    }
267
268    /// Simulates clicking a button in an platform-level alert dialog.
269    pub fn simulate_prompt_answer(&self, button_ix: usize) {
270        self.test_platform.simulate_prompt_answer(button_ix);
271    }
272
273    /// Returns true if there's an alert dialog open.
274    pub fn has_pending_prompt(&self) -> bool {
275        self.test_platform.has_pending_prompt()
276    }
277
278    /// All the urls that have been opened with cx.open_url() during this test.
279    pub fn opened_url(&self) -> Option<String> {
280        self.test_platform.opened_url.borrow().clone()
281    }
282
283    /// Simulates the user resizing the window to the new size.
284    pub fn simulate_window_resize(&self, window_handle: AnyWindowHandle, size: Size<Pixels>) {
285        self.test_window(window_handle).simulate_resize(size);
286    }
287
288    /// Returns all windows open in the test.
289    pub fn windows(&self) -> Vec<AnyWindowHandle> {
290        self.app.borrow().windows().clone()
291    }
292
293    /// Run the given task on the main thread.
294    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
295    where
296        Fut: Future<Output = R> + 'static,
297        R: 'static,
298    {
299        self.foreground_executor.spawn(f(self.to_async()))
300    }
301
302    /// true if the given global is defined
303    pub fn has_global<G: Global>(&self) -> bool {
304        let app = self.app.borrow();
305        app.has_global::<G>()
306    }
307
308    /// runs the given closure with a reference to the global
309    /// panics if `has_global` would return false.
310    pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> R {
311        let app = self.app.borrow();
312        read(app.global(), &app)
313    }
314
315    /// runs the given closure with a reference to the global (if set)
316    pub fn try_read_global<G: Global, R>(
317        &self,
318        read: impl FnOnce(&G, &AppContext) -> R,
319    ) -> Option<R> {
320        let lock = self.app.borrow();
321        Some(read(lock.try_global()?, &lock))
322    }
323
324    /// sets the global in this context.
325    pub fn set_global<G: Global>(&mut self, global: G) {
326        let mut lock = self.app.borrow_mut();
327        lock.update(|cx| cx.set_global(global))
328    }
329
330    /// updates the global in this context. (panics if `has_global` would return false)
331    pub fn update_global<G: Global, R>(
332        &mut self,
333        update: impl FnOnce(&mut G, &mut AppContext) -> R,
334    ) -> R {
335        let mut lock = self.app.borrow_mut();
336        lock.update(|cx| cx.update_global(update))
337    }
338
339    /// Returns an `AsyncAppContext` which can be used to run tasks that expect to be on a background
340    /// thread on the current thread in tests.
341    pub fn to_async(&self) -> AsyncAppContext {
342        AsyncAppContext {
343            app: Rc::downgrade(&self.app),
344            background_executor: self.background_executor.clone(),
345            foreground_executor: self.foreground_executor.clone(),
346        }
347    }
348
349    /// Wait until there are no more pending tasks.
350    pub fn run_until_parked(&mut self) {
351        self.background_executor.run_until_parked()
352    }
353
354    /// Simulate dispatching an action to the currently focused node in the window.
355    pub fn dispatch_action<A>(&mut self, window: AnyWindowHandle, action: A)
356    where
357        A: Action,
358    {
359        window
360            .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
361            .unwrap();
362
363        self.background_executor.run_until_parked()
364    }
365
366    /// simulate_keystrokes takes a space-separated list of keys to type.
367    /// cx.simulate_keystrokes("cmd-shift-p b k s p enter")
368    /// in Zed, this will run backspace on the current editor through the command palette.
369    /// This will also run the background executor until it's parked.
370    pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
371        for keystroke in keystrokes
372            .split(' ')
373            .map(Keystroke::parse)
374            .map(Result::unwrap)
375        {
376            self.dispatch_keystroke(window, keystroke);
377        }
378
379        self.background_executor.run_until_parked()
380    }
381
382    /// simulate_input takes a string of text to type.
383    /// cx.simulate_input("abc")
384    /// will type abc into your current editor
385    /// This will also run the background executor until it's parked.
386    pub fn simulate_input(&mut self, window: AnyWindowHandle, input: &str) {
387        for keystroke in input.split("").map(Keystroke::parse).map(Result::unwrap) {
388            self.dispatch_keystroke(window, keystroke);
389        }
390
391        self.background_executor.run_until_parked()
392    }
393
394    /// dispatches a single Keystroke (see also `simulate_keystrokes` and `simulate_input`)
395    pub fn dispatch_keystroke(&mut self, window: AnyWindowHandle, keystroke: Keystroke) {
396        self.update_window(window, |_, cx| cx.dispatch_keystroke(keystroke))
397            .unwrap();
398    }
399
400    /// Returns the `TestWindow` backing the given handle.
401    pub(crate) fn test_window(&self, window: AnyWindowHandle) -> TestWindow {
402        self.app
403            .borrow_mut()
404            .windows
405            .get_mut(window.id)
406            .unwrap()
407            .as_mut()
408            .unwrap()
409            .platform_window
410            .as_test()
411            .unwrap()
412            .clone()
413    }
414
415    /// Returns a stream of notifications whenever the View or Model is updated.
416    pub fn notifications<T: 'static>(&mut self, entity: &impl Entity<T>) -> impl Stream<Item = ()> {
417        let (tx, rx) = futures::channel::mpsc::unbounded();
418        self.update(|cx| {
419            cx.observe(entity, {
420                let tx = tx.clone();
421                move |_, _| {
422                    let _ = tx.unbounded_send(());
423                }
424            })
425            .detach();
426            cx.observe_release(entity, move |_, _| tx.close_channel())
427                .detach()
428        });
429        rx
430    }
431
432    /// Retuens a stream of events emitted by the given Model.
433    pub fn events<Evt, T: 'static + EventEmitter<Evt>>(
434        &mut self,
435        entity: &Model<T>,
436    ) -> futures::channel::mpsc::UnboundedReceiver<Evt>
437    where
438        Evt: 'static + Clone,
439    {
440        let (tx, rx) = futures::channel::mpsc::unbounded();
441        entity
442            .update(self, |_, cx: &mut ModelContext<T>| {
443                cx.subscribe(entity, move |_model, _handle, event, _cx| {
444                    let _ = tx.unbounded_send(event.clone());
445                })
446            })
447            .detach();
448        rx
449    }
450
451    /// Runs until the given condition becomes true. (Prefer `run_until_parked` if you
452    /// don't need to jump in at a specific time).
453    pub async fn condition<T: 'static>(
454        &mut self,
455        model: &Model<T>,
456        mut predicate: impl FnMut(&mut T, &mut ModelContext<T>) -> bool,
457    ) {
458        let timer = self.executor().timer(Duration::from_secs(3));
459        let mut notifications = self.notifications(model);
460
461        use futures::FutureExt as _;
462        use smol::future::FutureExt as _;
463
464        async {
465            loop {
466                if model.update(self, &mut predicate) {
467                    return Ok(());
468                }
469
470                if notifications.next().await.is_none() {
471                    bail!("model dropped")
472                }
473            }
474        }
475        .race(timer.map(|_| Err(anyhow!("condition timed out"))))
476        .await
477        .unwrap();
478    }
479}
480
481impl<T: 'static> Model<T> {
482    /// Block until the next event is emitted by the model, then return it.
483    pub fn next_event<Event>(&self, cx: &mut TestAppContext) -> impl Future<Output = Event>
484    where
485        Event: Send + Clone + 'static,
486        T: EventEmitter<Event>,
487    {
488        let (tx, mut rx) = oneshot::channel();
489        let mut tx = Some(tx);
490        let subscription = self.update(cx, |_, cx| {
491            cx.subscribe(self, move |_, _, event, _| {
492                if let Some(tx) = tx.take() {
493                    _ = tx.send(event.clone());
494                }
495            })
496        });
497
498        async move {
499            let event = rx.await.expect("no event emitted");
500            drop(subscription);
501            event
502        }
503    }
504
505    /// Returns a future that resolves when the model notifies.
506    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
507        use postage::prelude::{Sink as _, Stream as _};
508
509        let (mut tx, mut rx) = postage::mpsc::channel(1);
510        let mut cx = cx.app.app.borrow_mut();
511        let subscription = cx.observe(self, move |_, _| {
512            tx.try_send(()).ok();
513        });
514
515        let duration = if std::env::var("CI").is_ok() {
516            Duration::from_secs(5)
517        } else {
518            Duration::from_secs(1)
519        };
520
521        async move {
522            let notification = crate::util::timeout(duration, rx.recv())
523                .await
524                .expect("next notification timed out");
525            drop(subscription);
526            notification.expect("model dropped while test was waiting for its next notification")
527        }
528    }
529}
530
531impl<V: 'static> View<V> {
532    /// Returns a future that resolves when the view is next updated.
533    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
534        use postage::prelude::{Sink as _, Stream as _};
535
536        let (mut tx, mut rx) = postage::mpsc::channel(1);
537        let mut cx = cx.app.app.borrow_mut();
538        let subscription = cx.observe(self, move |_, _| {
539            tx.try_send(()).ok();
540        });
541
542        let duration = if std::env::var("CI").is_ok() {
543            Duration::from_secs(5)
544        } else {
545            Duration::from_secs(1)
546        };
547
548        async move {
549            let notification = crate::util::timeout(duration, rx.recv())
550                .await
551                .expect("next notification timed out");
552            drop(subscription);
553            notification.expect("model dropped while test was waiting for its next notification")
554        }
555    }
556}
557
558impl<V> View<V> {
559    /// Returns a future that resolves when the condition becomes true.
560    pub fn condition<Evt>(
561        &self,
562        cx: &TestAppContext,
563        mut predicate: impl FnMut(&V, &AppContext) -> bool,
564    ) -> impl Future<Output = ()>
565    where
566        Evt: 'static,
567        V: EventEmitter<Evt>,
568    {
569        use postage::prelude::{Sink as _, Stream as _};
570
571        let (tx, mut rx) = postage::mpsc::channel(1024);
572        let timeout_duration = Duration::from_millis(100);
573
574        let mut cx = cx.app.borrow_mut();
575        let subscriptions = (
576            cx.observe(self, {
577                let mut tx = tx.clone();
578                move |_, _| {
579                    tx.blocking_send(()).ok();
580                }
581            }),
582            cx.subscribe(self, {
583                let mut tx = tx.clone();
584                move |_, _: &Evt, _| {
585                    tx.blocking_send(()).ok();
586                }
587            }),
588        );
589
590        let cx = cx.this.upgrade().unwrap();
591        let handle = self.downgrade();
592
593        async move {
594            crate::util::timeout(timeout_duration, async move {
595                loop {
596                    {
597                        let cx = cx.borrow();
598                        let cx = &*cx;
599                        if predicate(
600                            handle
601                                .upgrade()
602                                .expect("view dropped with pending condition")
603                                .read(cx),
604                            cx,
605                        ) {
606                            break;
607                        }
608                    }
609
610                    cx.borrow().background_executor().start_waiting();
611                    rx.recv()
612                        .await
613                        .expect("view dropped with pending condition");
614                    cx.borrow().background_executor().finish_waiting();
615                }
616            })
617            .await
618            .expect("condition timed out");
619            drop(subscriptions);
620        }
621    }
622}
623
624use derive_more::{Deref, DerefMut};
625#[derive(Deref, DerefMut, Clone)]
626/// A VisualTestContext is the test-equivalent of a `WindowContext`. It allows you to
627/// run window-specific test code.
628pub struct VisualTestContext {
629    #[deref]
630    #[deref_mut]
631    /// cx is the original TestAppContext (you can more easily access this using Deref)
632    pub cx: TestAppContext,
633    window: AnyWindowHandle,
634}
635
636impl VisualTestContext {
637    /// Get the underlying window handle underlying this context.
638    pub fn handle(&self) -> AnyWindowHandle {
639        self.window
640    }
641
642    /// Provides the `WindowContext` for the duration of the closure.
643    pub fn update<R>(&mut self, f: impl FnOnce(&mut WindowContext) -> R) -> R {
644        self.cx.update_window(self.window, |_, cx| f(cx)).unwrap()
645    }
646
647    /// Creates a new VisualTestContext. You would typically shadow the passed in
648    /// TestAppContext with this, as this is typically more useful.
649    /// `let cx = VisualTestContext::from_window(window, cx);`
650    pub fn from_window(window: AnyWindowHandle, cx: &TestAppContext) -> Self {
651        Self {
652            cx: cx.clone(),
653            window,
654        }
655    }
656
657    /// Wait until there are no more pending tasks.
658    pub fn run_until_parked(&self) {
659        self.cx.background_executor.run_until_parked();
660    }
661
662    /// Dispatch the action to the currently focused node.
663    pub fn dispatch_action<A>(&mut self, action: A)
664    where
665        A: Action,
666    {
667        self.cx.dispatch_action(self.window, action)
668    }
669
670    /// Read the title off the window (set by `WindowContext#set_window_title`)
671    pub fn window_title(&mut self) -> Option<String> {
672        self.cx.test_window(self.window).0.lock().title.clone()
673    }
674
675    /// Simulate a sequence of keystrokes `cx.simulate_keystrokes("cmd-p escape")`
676    /// Automatically runs until parked.
677    pub fn simulate_keystrokes(&mut self, keystrokes: &str) {
678        self.cx.simulate_keystrokes(self.window, keystrokes)
679    }
680
681    /// Simulate typing text `cx.simulate_input("hello")`
682    /// Automatically runs until parked.
683    pub fn simulate_input(&mut self, input: &str) {
684        self.cx.simulate_input(self.window, input)
685    }
686
687    /// Simulate a mouse move event to the given point
688    pub fn simulate_mouse_move(
689        &mut self,
690        position: Point<Pixels>,
691        button: impl Into<Option<MouseButton>>,
692        modifiers: Modifiers,
693    ) {
694        self.simulate_event(MouseMoveEvent {
695            position,
696            modifiers,
697            pressed_button: button.into(),
698        })
699    }
700
701    /// Simulate a mouse down event to the given point
702    pub fn simulate_mouse_down(
703        &mut self,
704        position: Point<Pixels>,
705        button: MouseButton,
706        modifiers: Modifiers,
707    ) {
708        self.simulate_event(MouseDownEvent {
709            position,
710            modifiers,
711            button,
712            click_count: 1,
713            first_mouse: false,
714        })
715    }
716
717    /// Simulate a mouse up event to the given point
718    pub fn simulate_mouse_up(
719        &mut self,
720        position: Point<Pixels>,
721        button: MouseButton,
722        modifiers: Modifiers,
723    ) {
724        self.simulate_event(MouseUpEvent {
725            position,
726            modifiers,
727            button,
728            click_count: 1,
729        })
730    }
731
732    /// Simulate a primary mouse click at the given point
733    pub fn simulate_click(&mut self, position: Point<Pixels>, modifiers: Modifiers) {
734        self.simulate_event(MouseDownEvent {
735            position,
736            modifiers,
737            button: MouseButton::Left,
738            click_count: 1,
739            first_mouse: false,
740        });
741        self.simulate_event(MouseUpEvent {
742            position,
743            modifiers,
744            button: MouseButton::Left,
745            click_count: 1,
746        });
747    }
748
749    /// Simulate a modifiers changed event
750    pub fn simulate_modifiers_change(&mut self, modifiers: Modifiers) {
751        self.simulate_event(ModifiersChangedEvent { modifiers })
752    }
753
754    /// Simulates the user resizing the window to the new size.
755    pub fn simulate_resize(&self, size: Size<Pixels>) {
756        self.simulate_window_resize(self.window, size)
757    }
758
759    /// debug_bounds returns the bounds of the element with the given selector.
760    pub fn debug_bounds(&mut self, selector: &'static str) -> Option<Bounds<Pixels>> {
761        self.update(|cx| cx.window.rendered_frame.debug_bounds.get(selector).copied())
762    }
763
764    /// Draw an element to the window. Useful for simulating events or actions
765    pub fn draw<E>(
766        &mut self,
767        origin: Point<Pixels>,
768        space: impl Into<Size<AvailableSpace>>,
769        f: impl FnOnce(&mut WindowContext) -> E,
770    ) -> (E::RequestLayoutState, E::PrepaintState)
771    where
772        E: Element,
773    {
774        self.update(|cx| {
775            cx.window.draw_phase = DrawPhase::Prepaint;
776            let mut element = Drawable::new(f(cx));
777            element.layout_as_root(space.into(), cx);
778            cx.with_absolute_element_offset(origin, |cx| element.prepaint(cx));
779
780            cx.window.draw_phase = DrawPhase::Paint;
781            let (request_layout_state, prepaint_state) = element.paint(cx);
782
783            cx.window.draw_phase = DrawPhase::None;
784            cx.refresh();
785
786            (request_layout_state, prepaint_state)
787        })
788    }
789
790    /// Simulate an event from the platform, e.g. a SrollWheelEvent
791    /// Make sure you've called [VisualTestContext::draw] first!
792    pub fn simulate_event<E: InputEvent>(&mut self, event: E) {
793        self.test_window(self.window)
794            .simulate_input(event.to_platform_input());
795        self.background_executor.run_until_parked();
796    }
797
798    /// Simulates the user blurring the window.
799    pub fn deactivate_window(&mut self) {
800        if Some(self.window) == self.test_platform.active_window() {
801            self.test_platform.set_active_window(None)
802        }
803        self.background_executor.run_until_parked();
804    }
805
806    /// Simulates the user closing the window.
807    /// Returns true if the window was closed.
808    pub fn simulate_close(&mut self) -> bool {
809        let handler = self
810            .cx
811            .update_window(self.window, |_, cx| {
812                cx.window
813                    .platform_window
814                    .as_test()
815                    .unwrap()
816                    .0
817                    .lock()
818                    .should_close_handler
819                    .take()
820            })
821            .unwrap();
822        if let Some(mut handler) = handler {
823            let should_close = handler();
824            self.cx
825                .update_window(self.window, |_, cx| {
826                    cx.window.platform_window.on_should_close(handler);
827                })
828                .unwrap();
829            should_close
830        } else {
831            false
832        }
833    }
834
835    /// Get an &mut VisualTestContext (which is mostly what you need to pass to other methods).
836    /// This method internally retains the VisualTestContext until the end of the test.
837    pub fn as_mut(self) -> &'static mut Self {
838        let ptr = Box::into_raw(Box::new(self));
839        // safety: on_quit will be called after the test has finished.
840        // the executor will ensure that all tasks related to the test have stopped.
841        // so there is no way for cx to be accessed after on_quit is called.
842        let cx = Box::leak(unsafe { Box::from_raw(ptr) });
843        cx.on_quit(move || unsafe {
844            drop(Box::from_raw(ptr));
845        });
846        cx
847    }
848}
849
850impl Context for VisualTestContext {
851    type Result<T> = <TestAppContext as Context>::Result<T>;
852
853    fn new_model<T: 'static>(
854        &mut self,
855        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
856    ) -> Self::Result<Model<T>> {
857        self.cx.new_model(build_model)
858    }
859
860    fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
861        self.cx.reserve_model()
862    }
863
864    fn insert_model<T: 'static>(
865        &mut self,
866        reservation: crate::Reservation<T>,
867        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
868    ) -> Self::Result<Model<T>> {
869        self.cx.insert_model(reservation, build_model)
870    }
871
872    fn update_model<T, R>(
873        &mut self,
874        handle: &Model<T>,
875        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
876    ) -> Self::Result<R>
877    where
878        T: 'static,
879    {
880        self.cx.update_model(handle, update)
881    }
882
883    fn read_model<T, R>(
884        &self,
885        handle: &Model<T>,
886        read: impl FnOnce(&T, &AppContext) -> R,
887    ) -> Self::Result<R>
888    where
889        T: 'static,
890    {
891        self.cx.read_model(handle, read)
892    }
893
894    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
895    where
896        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
897    {
898        self.cx.update_window(window, f)
899    }
900
901    fn read_window<T, R>(
902        &self,
903        window: &WindowHandle<T>,
904        read: impl FnOnce(View<T>, &AppContext) -> R,
905    ) -> Result<R>
906    where
907        T: 'static,
908    {
909        self.cx.read_window(window, read)
910    }
911}
912
913impl VisualContext for VisualTestContext {
914    fn new_view<V>(
915        &mut self,
916        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
917    ) -> Self::Result<View<V>>
918    where
919        V: 'static + Render,
920    {
921        self.window
922            .update(&mut self.cx, |_, cx| cx.new_view(build_view))
923            .unwrap()
924    }
925
926    fn update_view<V: 'static, R>(
927        &mut self,
928        view: &View<V>,
929        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
930    ) -> Self::Result<R> {
931        self.window
932            .update(&mut self.cx, |_, cx| cx.update_view(view, update))
933            .unwrap()
934    }
935
936    fn replace_root_view<V>(
937        &mut self,
938        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
939    ) -> Self::Result<View<V>>
940    where
941        V: 'static + Render,
942    {
943        self.window
944            .update(&mut self.cx, |_, cx| cx.replace_root_view(build_view))
945            .unwrap()
946    }
947
948    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
949        self.window
950            .update(&mut self.cx, |_, cx| {
951                view.read(cx).focus_handle(cx).clone().focus(cx)
952            })
953            .unwrap()
954    }
955
956    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
957    where
958        V: crate::ManagedView,
959    {
960        self.window
961            .update(&mut self.cx, |_, cx| {
962                view.update(cx, |_, cx| cx.emit(crate::DismissEvent))
963            })
964            .unwrap()
965    }
966}
967
968impl AnyWindowHandle {
969    /// Creates the given view in this window.
970    pub fn build_view<V: Render + 'static>(
971        &self,
972        cx: &mut TestAppContext,
973        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
974    ) -> View<V> {
975        self.update(cx, |_, cx| cx.new_view(build_view)).unwrap()
976    }
977}