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(&mut self, position: Point<Pixels>, modifiers: Modifiers) {
689        self.simulate_event(MouseMoveEvent {
690            position,
691            modifiers,
692            pressed_button: None,
693        })
694    }
695
696    /// Simulate a primary mouse click at the given point
697    pub fn simulate_click(&mut self, position: Point<Pixels>, modifiers: Modifiers) {
698        self.simulate_event(MouseDownEvent {
699            position,
700            modifiers,
701            button: MouseButton::Left,
702            click_count: 1,
703            first_mouse: false,
704        });
705        self.simulate_event(MouseUpEvent {
706            position,
707            modifiers,
708            button: MouseButton::Left,
709            click_count: 1,
710        });
711    }
712
713    /// Simulate a modifiers changed event
714    pub fn simulate_modifiers_change(&mut self, modifiers: Modifiers) {
715        self.simulate_event(ModifiersChangedEvent { modifiers })
716    }
717
718    /// Simulates the user resizing the window to the new size.
719    pub fn simulate_resize(&self, size: Size<Pixels>) {
720        self.simulate_window_resize(self.window, size)
721    }
722
723    /// debug_bounds returns the bounds of the element with the given selector.
724    pub fn debug_bounds(&mut self, selector: &'static str) -> Option<Bounds<Pixels>> {
725        self.update(|cx| cx.window.rendered_frame.debug_bounds.get(selector).copied())
726    }
727
728    /// Draw an element to the window. Useful for simulating events or actions
729    pub fn draw<E>(
730        &mut self,
731        origin: Point<Pixels>,
732        space: impl Into<Size<AvailableSpace>>,
733        f: impl FnOnce(&mut WindowContext) -> E,
734    ) -> (E::RequestLayoutState, E::PrepaintState)
735    where
736        E: Element,
737    {
738        self.update(|cx| {
739            cx.window.draw_phase = DrawPhase::Prepaint;
740            let mut element = Drawable::new(f(cx));
741            element.layout_as_root(space.into(), cx);
742            cx.with_absolute_element_offset(origin, |cx| element.prepaint(cx));
743
744            cx.window.draw_phase = DrawPhase::Paint;
745            let (request_layout_state, prepaint_state) = element.paint(cx);
746
747            cx.window.draw_phase = DrawPhase::None;
748            cx.refresh();
749
750            (request_layout_state, prepaint_state)
751        })
752    }
753
754    /// Simulate an event from the platform, e.g. a SrollWheelEvent
755    /// Make sure you've called [VisualTestContext::draw] first!
756    pub fn simulate_event<E: InputEvent>(&mut self, event: E) {
757        self.test_window(self.window)
758            .simulate_input(event.to_platform_input());
759        self.background_executor.run_until_parked();
760    }
761
762    /// Simulates the user blurring the window.
763    pub fn deactivate_window(&mut self) {
764        if Some(self.window) == self.test_platform.active_window() {
765            self.test_platform.set_active_window(None)
766        }
767        self.background_executor.run_until_parked();
768    }
769
770    /// Simulates the user closing the window.
771    /// Returns true if the window was closed.
772    pub fn simulate_close(&mut self) -> bool {
773        let handler = self
774            .cx
775            .update_window(self.window, |_, cx| {
776                cx.window
777                    .platform_window
778                    .as_test()
779                    .unwrap()
780                    .0
781                    .lock()
782                    .should_close_handler
783                    .take()
784            })
785            .unwrap();
786        if let Some(mut handler) = handler {
787            let should_close = handler();
788            self.cx
789                .update_window(self.window, |_, cx| {
790                    cx.window.platform_window.on_should_close(handler);
791                })
792                .unwrap();
793            should_close
794        } else {
795            false
796        }
797    }
798
799    /// Get an &mut VisualTestContext (which is mostly what you need to pass to other methods).
800    /// This method internally retains the VisualTestContext until the end of the test.
801    pub fn as_mut(self) -> &'static mut Self {
802        let ptr = Box::into_raw(Box::new(self));
803        // safety: on_quit will be called after the test has finished.
804        // the executor will ensure that all tasks related to the test have stopped.
805        // so there is no way for cx to be accessed after on_quit is called.
806        let cx = Box::leak(unsafe { Box::from_raw(ptr) });
807        cx.on_quit(move || unsafe {
808            drop(Box::from_raw(ptr));
809        });
810        cx
811    }
812}
813
814impl Context for VisualTestContext {
815    type Result<T> = <TestAppContext as Context>::Result<T>;
816
817    fn new_model<T: 'static>(
818        &mut self,
819        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
820    ) -> Self::Result<Model<T>> {
821        self.cx.new_model(build_model)
822    }
823
824    fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
825        self.cx.reserve_model()
826    }
827
828    fn insert_model<T: 'static>(
829        &mut self,
830        reservation: crate::Reservation<T>,
831        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
832    ) -> Self::Result<Model<T>> {
833        self.cx.insert_model(reservation, build_model)
834    }
835
836    fn update_model<T, R>(
837        &mut self,
838        handle: &Model<T>,
839        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
840    ) -> Self::Result<R>
841    where
842        T: 'static,
843    {
844        self.cx.update_model(handle, update)
845    }
846
847    fn read_model<T, R>(
848        &self,
849        handle: &Model<T>,
850        read: impl FnOnce(&T, &AppContext) -> R,
851    ) -> Self::Result<R>
852    where
853        T: 'static,
854    {
855        self.cx.read_model(handle, read)
856    }
857
858    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
859    where
860        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
861    {
862        self.cx.update_window(window, f)
863    }
864
865    fn read_window<T, R>(
866        &self,
867        window: &WindowHandle<T>,
868        read: impl FnOnce(View<T>, &AppContext) -> R,
869    ) -> Result<R>
870    where
871        T: 'static,
872    {
873        self.cx.read_window(window, read)
874    }
875}
876
877impl VisualContext for VisualTestContext {
878    fn new_view<V>(
879        &mut self,
880        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
881    ) -> Self::Result<View<V>>
882    where
883        V: 'static + Render,
884    {
885        self.window
886            .update(&mut self.cx, |_, cx| cx.new_view(build_view))
887            .unwrap()
888    }
889
890    fn update_view<V: 'static, R>(
891        &mut self,
892        view: &View<V>,
893        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
894    ) -> Self::Result<R> {
895        self.window
896            .update(&mut self.cx, |_, cx| cx.update_view(view, update))
897            .unwrap()
898    }
899
900    fn replace_root_view<V>(
901        &mut self,
902        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
903    ) -> Self::Result<View<V>>
904    where
905        V: 'static + Render,
906    {
907        self.window
908            .update(&mut self.cx, |_, cx| cx.replace_root_view(build_view))
909            .unwrap()
910    }
911
912    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
913        self.window
914            .update(&mut self.cx, |_, cx| {
915                view.read(cx).focus_handle(cx).clone().focus(cx)
916            })
917            .unwrap()
918    }
919
920    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
921    where
922        V: crate::ManagedView,
923    {
924        self.window
925            .update(&mut self.cx, |_, cx| {
926                view.update(cx, |_, cx| cx.emit(crate::DismissEvent))
927            })
928            .unwrap()
929    }
930}
931
932impl AnyWindowHandle {
933    /// Creates the given view in this window.
934    pub fn build_view<V: Render + 'static>(
935        &self,
936        cx: &mut TestAppContext,
937        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
938    ) -> View<V> {
939        self.update(cx, |_, cx| cx.new_view(build_view)).unwrap()
940    }
941}