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