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