test_context.rs

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