test_context.rs

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