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