test_context.rs

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