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