test_context.rs

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