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