test_context.rs

  1use crate::{
  2    Action, AnyElement, AnyView, AnyWindowHandle, AppCell, AppContext, AsyncAppContext,
  3    AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem, Context, Entity, EventEmitter,
  4    ForegroundExecutor, Global, InputEvent, Keystroke, Model, ModelContext, Modifiers,
  5    ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
  6    Platform, Point, Render, Result, Size, Task, TestDispatcher, TestPlatform, TestWindow,
  7    TextSystem, View, ViewContext, VisualContext, WindowContext, WindowHandle, WindowOptions,
  8};
  9use anyhow::{anyhow, bail};
 10use futures::{Stream, StreamExt};
 11use std::{cell::RefCell, future::Future, ops::Deref, rc::Rc, sync::Arc, time::Duration};
 12
 13/// A TestAppContext is provided to tests created with `#[gpui::test]`, it provides
 14/// an implementation of `Context` with additional methods that are useful in tests.
 15#[derive(Clone)]
 16pub struct TestAppContext {
 17    #[doc(hidden)]
 18    pub app: Rc<AppCell>,
 19    #[doc(hidden)]
 20    pub background_executor: BackgroundExecutor,
 21    #[doc(hidden)]
 22    pub foreground_executor: ForegroundExecutor,
 23    #[doc(hidden)]
 24    pub dispatcher: TestDispatcher,
 25    test_platform: Rc<TestPlatform>,
 26    text_system: Arc<TextSystem>,
 27    fn_name: Option<&'static str>,
 28    on_quit: Rc<RefCell<Vec<Box<dyn FnOnce() + 'static>>>>,
 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            on_quit: Rc::new(RefCell::new(Vec::default())),
107        }
108    }
109
110    /// The name of the test function that created this `TestAppContext`
111    pub fn test_function_name(&self) -> Option<&'static str> {
112        self.fn_name
113    }
114
115    /// Checks whether there have been any new path prompts received by the platform.
116    pub fn did_prompt_for_new_path(&self) -> bool {
117        self.test_platform.did_prompt_for_new_path()
118    }
119
120    /// returns a new `TestAppContext` re-using the same executors to interleave tasks.
121    pub fn new_app(&self) -> TestAppContext {
122        Self::new(self.dispatcher.clone(), self.fn_name)
123    }
124
125    /// Called by the test helper to end the test.
126    /// public so the macro can call it.
127    pub fn quit(&self) {
128        self.on_quit.borrow_mut().drain(..).for_each(|f| f());
129        self.app.borrow_mut().shutdown();
130    }
131
132    /// Register cleanup to run when the test ends.
133    pub fn on_quit(&mut self, f: impl FnOnce() + 'static) {
134        self.on_quit.borrow_mut().push(Box::new(f));
135    }
136
137    /// Schedules all windows to be redrawn on the next effect cycle.
138    pub fn refresh(&mut self) -> Result<()> {
139        let mut app = self.app.borrow_mut();
140        app.refresh();
141        Ok(())
142    }
143
144    /// Returns an executor (for running tasks in the background)
145    pub fn executor(&self) -> BackgroundExecutor {
146        self.background_executor.clone()
147    }
148
149    /// Returns an executor (for running tasks on the main thread)
150    pub fn foreground_executor(&self) -> &ForegroundExecutor {
151        &self.foreground_executor
152    }
153
154    /// Gives you an `&mut AppContext` for the duration of the closure
155    pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> R {
156        let mut cx = self.app.borrow_mut();
157        cx.update(f)
158    }
159
160    /// Gives you an `&AppContext` for the duration of the closure
161    pub fn read<R>(&self, f: impl FnOnce(&AppContext) -> R) -> R {
162        let cx = self.app.borrow();
163        f(&*cx)
164    }
165
166    /// Adds a new window. The Window will always be backed by a `TestWindow` which
167    /// can be retrieved with `self.test_window(handle)`
168    pub fn add_window<F, V>(&mut self, build_window: F) -> WindowHandle<V>
169    where
170        F: FnOnce(&mut ViewContext<V>) -> V,
171        V: 'static + Render,
172    {
173        let mut cx = self.app.borrow_mut();
174        cx.open_window(WindowOptions::default(), |cx| cx.new_view(build_window))
175    }
176
177    /// Adds a new window with no content.
178    pub fn add_empty_window(&mut self) -> &mut VisualTestContext {
179        let mut cx = self.app.borrow_mut();
180        let window = cx.open_window(WindowOptions::default(), |cx| cx.new_view(|_| ()));
181        drop(cx);
182        let cx = VisualTestContext::from_window(*window.deref(), self).as_mut();
183        cx.run_until_parked();
184        cx
185    }
186
187    /// Adds a new window, and returns its root view and a `VisualTestContext` which can be used
188    /// as a `WindowContext` for the rest of the test. Typically you would shadow this context with
189    /// the returned one. `let (view, cx) = cx.add_window_view(...);`
190    pub fn add_window_view<F, V>(&mut self, build_window: F) -> (View<V>, &mut VisualTestContext)
191    where
192        F: FnOnce(&mut ViewContext<V>) -> V,
193        V: 'static + Render,
194    {
195        let mut cx = self.app.borrow_mut();
196        let window = cx.open_window(WindowOptions::default(), |cx| cx.new_view(build_window));
197        drop(cx);
198        let view = window.root_view(self).unwrap();
199        let cx = VisualTestContext::from_window(*window.deref(), self).as_mut();
200        cx.run_until_parked();
201
202        // it might be nice to try and cleanup these at the end of each test.
203        (view, cx)
204    }
205
206    /// returns the TextSystem
207    pub fn text_system(&self) -> &Arc<TextSystem> {
208        &self.text_system
209    }
210
211    /// Simulates writing to the platform clipboard
212    pub fn write_to_clipboard(&self, item: ClipboardItem) {
213        self.test_platform.write_to_clipboard(item)
214    }
215
216    /// Simulates reading from the platform clipboard.
217    /// This will return the most recent value from `write_to_clipboard`.
218    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
219        self.test_platform.read_from_clipboard()
220    }
221
222    /// Simulates choosing a File in the platform's "Open" dialog.
223    pub fn simulate_new_path_selection(
224        &self,
225        select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
226    ) {
227        self.test_platform.simulate_new_path_selection(select_path);
228    }
229
230    /// Simulates clicking a button in an platform-level alert dialog.
231    pub fn simulate_prompt_answer(&self, button_ix: usize) {
232        self.test_platform.simulate_prompt_answer(button_ix);
233    }
234
235    /// Returns true if there's an alert dialog open.
236    pub fn has_pending_prompt(&self) -> bool {
237        self.test_platform.has_pending_prompt()
238    }
239
240    /// All the urls that have been opened with cx.open_url() during this test.
241    pub fn opened_url(&self) -> Option<String> {
242        self.test_platform.opened_url.borrow().clone()
243    }
244
245    /// Simulates the user resizing the window to the new size.
246    pub fn simulate_window_resize(&self, window_handle: AnyWindowHandle, size: Size<Pixels>) {
247        self.test_window(window_handle).simulate_resize(size);
248    }
249
250    /// Returns all windows open in the test.
251    pub fn windows(&self) -> Vec<AnyWindowHandle> {
252        self.app.borrow().windows().clone()
253    }
254
255    /// Run the given task on the main thread.
256    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
257    where
258        Fut: Future<Output = R> + 'static,
259        R: 'static,
260    {
261        self.foreground_executor.spawn(f(self.to_async()))
262    }
263
264    /// true if the given global is defined
265    pub fn has_global<G: Global>(&self) -> bool {
266        let app = self.app.borrow();
267        app.has_global::<G>()
268    }
269
270    /// runs the given closure with a reference to the global
271    /// panics if `has_global` would return false.
272    pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> R {
273        let app = self.app.borrow();
274        read(app.global(), &app)
275    }
276
277    /// runs the given closure with a reference to the global (if set)
278    pub fn try_read_global<G: Global, R>(
279        &self,
280        read: impl FnOnce(&G, &AppContext) -> R,
281    ) -> Option<R> {
282        let lock = self.app.borrow();
283        Some(read(lock.try_global()?, &lock))
284    }
285
286    /// sets the global in this context.
287    pub fn set_global<G: Global>(&mut self, global: G) {
288        let mut lock = self.app.borrow_mut();
289        lock.set_global(global);
290    }
291
292    /// updates the global in this context. (panics if `has_global` would return false)
293    pub fn update_global<G: Global, R>(
294        &mut self,
295        update: impl FnOnce(&mut G, &mut AppContext) -> R,
296    ) -> R {
297        let mut lock = self.app.borrow_mut();
298        lock.update_global(update)
299    }
300
301    /// Returns an `AsyncAppContext` which can be used to run tasks that expect to be on a background
302    /// thread on the current thread in tests.
303    pub fn to_async(&self) -> AsyncAppContext {
304        AsyncAppContext {
305            app: Rc::downgrade(&self.app),
306            background_executor: self.background_executor.clone(),
307            foreground_executor: self.foreground_executor.clone(),
308        }
309    }
310
311    /// Wait until there are no more pending tasks.
312    pub fn run_until_parked(&mut self) {
313        self.background_executor.run_until_parked()
314    }
315
316    /// Simulate dispatching an action to the currently focused node in the window.
317    pub fn dispatch_action<A>(&mut self, window: AnyWindowHandle, action: A)
318    where
319        A: Action,
320    {
321        window
322            .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
323            .unwrap();
324
325        self.background_executor.run_until_parked()
326    }
327
328    /// simulate_keystrokes takes a space-separated list of keys to type.
329    /// cx.simulate_keystrokes("cmd-shift-p b k s p enter")
330    /// in Zed, this will run backspace on the current editor through the command palette.
331    /// This will also run the background executor until it's parked.
332    pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
333        for keystroke in keystrokes
334            .split(" ")
335            .map(Keystroke::parse)
336            .map(Result::unwrap)
337        {
338            self.dispatch_keystroke(window, keystroke.into(), false);
339        }
340
341        self.background_executor.run_until_parked()
342    }
343
344    /// simulate_input takes a string of text to type.
345    /// cx.simulate_input("abc")
346    /// will type abc into your current editor
347    /// This will also run the background executor until it's parked.
348    pub fn simulate_input(&mut self, window: AnyWindowHandle, input: &str) {
349        for keystroke in input.split("").map(Keystroke::parse).map(Result::unwrap) {
350            self.dispatch_keystroke(window, keystroke.into(), false);
351        }
352
353        self.background_executor.run_until_parked()
354    }
355
356    /// dispatches a single Keystroke (see also `simulate_keystrokes` and `simulate_input`)
357    pub fn dispatch_keystroke(
358        &mut self,
359        window: AnyWindowHandle,
360        keystroke: Keystroke,
361        is_held: bool,
362    ) {
363        self.test_window(window)
364            .simulate_keystroke(keystroke, is_held)
365    }
366
367    /// Returns the `TestWindow` backing the given handle.
368    pub(crate) fn test_window(&self, window: AnyWindowHandle) -> TestWindow {
369        self.app
370            .borrow_mut()
371            .windows
372            .get_mut(window.id)
373            .unwrap()
374            .as_mut()
375            .unwrap()
376            .platform_window
377            .as_test()
378            .unwrap()
379            .clone()
380    }
381
382    /// Returns a stream of notifications whenever the View or Model is updated.
383    pub fn notifications<T: 'static>(&mut self, entity: &impl Entity<T>) -> impl Stream<Item = ()> {
384        let (tx, rx) = futures::channel::mpsc::unbounded();
385        self.update(|cx| {
386            cx.observe(entity, {
387                let tx = tx.clone();
388                move |_, _| {
389                    let _ = tx.unbounded_send(());
390                }
391            })
392            .detach();
393            cx.observe_release(entity, move |_, _| tx.close_channel())
394                .detach()
395        });
396        rx
397    }
398
399    /// Retuens a stream of events emitted by the given Model.
400    pub fn events<Evt, T: 'static + EventEmitter<Evt>>(
401        &mut self,
402        entity: &Model<T>,
403    ) -> futures::channel::mpsc::UnboundedReceiver<Evt>
404    where
405        Evt: 'static + Clone,
406    {
407        let (tx, rx) = futures::channel::mpsc::unbounded();
408        entity
409            .update(self, |_, cx: &mut ModelContext<T>| {
410                cx.subscribe(entity, move |_model, _handle, event, _cx| {
411                    let _ = tx.unbounded_send(event.clone());
412                })
413            })
414            .detach();
415        rx
416    }
417
418    /// Runs until the given condition becomes true. (Prefer `run_until_parked` if you
419    /// don't need to jump in at a specific time).
420    pub async fn condition<T: 'static>(
421        &mut self,
422        model: &Model<T>,
423        mut predicate: impl FnMut(&mut T, &mut ModelContext<T>) -> bool,
424    ) {
425        let timer = self.executor().timer(Duration::from_secs(3));
426        let mut notifications = self.notifications(model);
427
428        use futures::FutureExt as _;
429        use smol::future::FutureExt as _;
430
431        async {
432            loop {
433                if model.update(self, &mut predicate) {
434                    return Ok(());
435                }
436
437                if notifications.next().await.is_none() {
438                    bail!("model dropped")
439                }
440            }
441        }
442        .race(timer.map(|_| Err(anyhow!("condition timed out"))))
443        .await
444        .unwrap();
445    }
446}
447
448impl<T: Send> Model<T> {
449    /// Block until the next event is emitted by the model, then return it.
450    pub fn next_event<Evt>(&self, cx: &mut TestAppContext) -> Evt
451    where
452        Evt: Send + Clone + 'static,
453        T: EventEmitter<Evt>,
454    {
455        let (tx, mut rx) = futures::channel::mpsc::unbounded();
456        let _subscription = self.update(cx, |_, cx| {
457            cx.subscribe(self, move |_, _, event, _| {
458                tx.unbounded_send(event.clone()).ok();
459            })
460        });
461
462        // Run other tasks until the event is emitted.
463        loop {
464            match rx.try_next() {
465                Ok(Some(event)) => return event,
466                Ok(None) => panic!("model was dropped"),
467                Err(_) => {
468                    if !cx.executor().tick() {
469                        break;
470                    }
471                }
472            }
473        }
474        panic!("no event received")
475    }
476}
477
478impl<V: 'static> View<V> {
479    /// Returns a future that resolves when the view is next updated.
480    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
481        use postage::prelude::{Sink as _, Stream as _};
482
483        let (mut tx, mut rx) = postage::mpsc::channel(1);
484        let mut cx = cx.app.app.borrow_mut();
485        let subscription = cx.observe(self, move |_, _| {
486            tx.try_send(()).ok();
487        });
488
489        let duration = if std::env::var("CI").is_ok() {
490            Duration::from_secs(5)
491        } else {
492            Duration::from_secs(1)
493        };
494
495        async move {
496            let notification = crate::util::timeout(duration, rx.recv())
497                .await
498                .expect("next notification timed out");
499            drop(subscription);
500            notification.expect("model dropped while test was waiting for its next notification")
501        }
502    }
503}
504
505impl<V> View<V> {
506    /// Returns a future that resolves when the condition becomes true.
507    pub fn condition<Evt>(
508        &self,
509        cx: &TestAppContext,
510        mut predicate: impl FnMut(&V, &AppContext) -> bool,
511    ) -> impl Future<Output = ()>
512    where
513        Evt: 'static,
514        V: EventEmitter<Evt>,
515    {
516        use postage::prelude::{Sink as _, Stream as _};
517
518        let (tx, mut rx) = postage::mpsc::channel(1024);
519        let timeout_duration = Duration::from_millis(100);
520
521        let mut cx = cx.app.borrow_mut();
522        let subscriptions = (
523            cx.observe(self, {
524                let mut tx = tx.clone();
525                move |_, _| {
526                    tx.blocking_send(()).ok();
527                }
528            }),
529            cx.subscribe(self, {
530                let mut tx = tx.clone();
531                move |_, _: &Evt, _| {
532                    tx.blocking_send(()).ok();
533                }
534            }),
535        );
536
537        let cx = cx.this.upgrade().unwrap();
538        let handle = self.downgrade();
539
540        async move {
541            crate::util::timeout(timeout_duration, async move {
542                loop {
543                    {
544                        let cx = cx.borrow();
545                        let cx = &*cx;
546                        if predicate(
547                            handle
548                                .upgrade()
549                                .expect("view dropped with pending condition")
550                                .read(cx),
551                            cx,
552                        ) {
553                            break;
554                        }
555                    }
556
557                    cx.borrow().background_executor().start_waiting();
558                    rx.recv()
559                        .await
560                        .expect("view dropped with pending condition");
561                    cx.borrow().background_executor().finish_waiting();
562                }
563            })
564            .await
565            .expect("condition timed out");
566            drop(subscriptions);
567        }
568    }
569}
570
571use derive_more::{Deref, DerefMut};
572#[derive(Deref, DerefMut, Clone)]
573/// A VisualTestContext is the test-equivalent of a `WindowContext`. It allows you to
574/// run window-specific test code.
575pub struct VisualTestContext {
576    #[deref]
577    #[deref_mut]
578    /// cx is the original TestAppContext (you can more easily access this using Deref)
579    pub cx: TestAppContext,
580    window: AnyWindowHandle,
581}
582
583impl<'a> VisualTestContext {
584    /// Get the underlying window handle underlying this context.
585    pub fn handle(&self) -> AnyWindowHandle {
586        self.window
587    }
588
589    /// Provides the `WindowContext` for the duration of the closure.
590    pub fn update<R>(&mut self, f: impl FnOnce(&mut WindowContext) -> R) -> R {
591        self.cx.update_window(self.window, |_, cx| f(cx)).unwrap()
592    }
593
594    /// Creates a new VisualTestContext. You would typically shadow the passed in
595    /// TestAppContext with this, as this is typically more useful.
596    /// `let cx = VisualTestContext::from_window(window, cx);`
597    pub fn from_window(window: AnyWindowHandle, cx: &TestAppContext) -> Self {
598        Self {
599            cx: cx.clone(),
600            window,
601        }
602    }
603
604    /// Wait until there are no more pending tasks.
605    pub fn run_until_parked(&self) {
606        self.cx.background_executor.run_until_parked();
607    }
608
609    /// Dispatch the action to the currently focused node.
610    pub fn dispatch_action<A>(&mut self, action: A)
611    where
612        A: Action,
613    {
614        self.cx.dispatch_action(self.window, action)
615    }
616
617    /// Read the title off the window (set by `WindowContext#set_window_title`)
618    pub fn window_title(&mut self) -> Option<String> {
619        self.cx.test_window(self.window).0.lock().title.clone()
620    }
621
622    /// Simulate a sequence of keystrokes `cx.simulate_keystrokes("cmd-p escape")`
623    /// Automatically runs until parked.
624    pub fn simulate_keystrokes(&mut self, keystrokes: &str) {
625        self.cx.simulate_keystrokes(self.window, keystrokes)
626    }
627
628    /// Simulate typing text `cx.simulate_input("hello")`
629    /// Automatically runs until parked.
630    pub fn simulate_input(&mut self, input: &str) {
631        self.cx.simulate_input(self.window, input)
632    }
633
634    /// Simulate a mouse move event to the given point
635    pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, modifiers: Modifiers) {
636        self.simulate_event(MouseMoveEvent {
637            position,
638            modifiers,
639            pressed_button: None,
640        })
641    }
642
643    /// Simulate a primary mouse click at the given point
644    pub fn simulate_click(&mut self, position: Point<Pixels>, modifiers: Modifiers) {
645        self.simulate_event(MouseDownEvent {
646            position,
647            modifiers,
648            button: MouseButton::Left,
649            click_count: 1,
650        });
651        self.simulate_event(MouseUpEvent {
652            position,
653            modifiers,
654            button: MouseButton::Left,
655            click_count: 1,
656        });
657    }
658
659    /// Simulate a modifiers changed event
660    pub fn simulate_modifiers_change(&mut self, modifiers: Modifiers) {
661        self.simulate_event(ModifiersChangedEvent { modifiers })
662    }
663
664    /// Simulates the user resizing the window to the new size.
665    pub fn simulate_resize(&self, size: Size<Pixels>) {
666        self.simulate_window_resize(self.window, size)
667    }
668
669    /// debug_bounds returns the bounds of the element with the given selector.
670    pub fn debug_bounds(&mut self, selector: &'static str) -> Option<Bounds<Pixels>> {
671        self.update(|cx| cx.window.rendered_frame.debug_bounds.get(selector).copied())
672    }
673
674    /// Draw an element to the window. Useful for simulating events or actions
675    pub fn draw(
676        &mut self,
677        origin: Point<Pixels>,
678        space: Size<AvailableSpace>,
679        f: impl FnOnce(&mut WindowContext) -> AnyElement,
680    ) {
681        self.update(|cx| {
682            let entity_id = cx
683                .window
684                .root_view
685                .as_ref()
686                .expect("Can't draw to this window without a root view")
687                .entity_id();
688
689            cx.with_element_context(|cx| {
690                cx.with_view_id(entity_id, |cx| {
691                    f(cx).draw(origin, space, cx);
692                })
693            });
694
695            cx.refresh();
696        })
697    }
698
699    /// Simulate an event from the platform, e.g. a SrollWheelEvent
700    /// Make sure you've called [VisualTestContext::draw] first!
701    pub fn simulate_event<E: InputEvent>(&mut self, event: E) {
702        self.test_window(self.window)
703            .simulate_input(event.to_platform_input());
704        self.background_executor.run_until_parked();
705    }
706
707    /// Simulates the user blurring the window.
708    pub fn deactivate_window(&mut self) {
709        if Some(self.window) == self.test_platform.active_window() {
710            self.test_platform.set_active_window(None)
711        }
712        self.background_executor.run_until_parked();
713    }
714
715    /// Simulates the user closing the window.
716    /// Returns true if the window was closed.
717    pub fn simulate_close(&mut self) -> bool {
718        let handler = self
719            .cx
720            .update_window(self.window, |_, cx| {
721                cx.window
722                    .platform_window
723                    .as_test()
724                    .unwrap()
725                    .0
726                    .lock()
727                    .should_close_handler
728                    .take()
729            })
730            .unwrap();
731        if let Some(mut handler) = handler {
732            let should_close = handler();
733            self.cx
734                .update_window(self.window, |_, cx| {
735                    cx.window.platform_window.on_should_close(handler);
736                })
737                .unwrap();
738            should_close
739        } else {
740            false
741        }
742    }
743
744    /// Get an &mut VisualTestContext (which is mostly what you need to pass to other methods).
745    /// This method internally retains the VisualTestContext until the end of the test.
746    pub fn as_mut(self) -> &'static mut Self {
747        let ptr = Box::into_raw(Box::new(self));
748        // safety: on_quit will be called after the test has finished.
749        // the executor will ensure that all tasks related to the test have stopped.
750        // so there is no way for cx to be accessed after on_quit is called.
751        let cx = Box::leak(unsafe { Box::from_raw(ptr) });
752        cx.on_quit(move || unsafe {
753            drop(Box::from_raw(ptr));
754        });
755        cx
756    }
757}
758
759impl Context for VisualTestContext {
760    type Result<T> = <TestAppContext as Context>::Result<T>;
761
762    fn new_model<T: 'static>(
763        &mut self,
764        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
765    ) -> Self::Result<Model<T>> {
766        self.cx.new_model(build_model)
767    }
768
769    fn update_model<T, R>(
770        &mut self,
771        handle: &Model<T>,
772        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
773    ) -> Self::Result<R>
774    where
775        T: 'static,
776    {
777        self.cx.update_model(handle, update)
778    }
779
780    fn read_model<T, R>(
781        &self,
782        handle: &Model<T>,
783        read: impl FnOnce(&T, &AppContext) -> R,
784    ) -> Self::Result<R>
785    where
786        T: 'static,
787    {
788        self.cx.read_model(handle, read)
789    }
790
791    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
792    where
793        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
794    {
795        self.cx.update_window(window, f)
796    }
797
798    fn read_window<T, R>(
799        &self,
800        window: &WindowHandle<T>,
801        read: impl FnOnce(View<T>, &AppContext) -> R,
802    ) -> Result<R>
803    where
804        T: 'static,
805    {
806        self.cx.read_window(window, read)
807    }
808}
809
810impl VisualContext for VisualTestContext {
811    fn new_view<V>(
812        &mut self,
813        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
814    ) -> Self::Result<View<V>>
815    where
816        V: 'static + Render,
817    {
818        self.window
819            .update(&mut self.cx, |_, cx| cx.new_view(build_view))
820            .unwrap()
821    }
822
823    fn update_view<V: 'static, R>(
824        &mut self,
825        view: &View<V>,
826        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
827    ) -> Self::Result<R> {
828        self.window
829            .update(&mut self.cx, |_, cx| cx.update_view(view, update))
830            .unwrap()
831    }
832
833    fn replace_root_view<V>(
834        &mut self,
835        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
836    ) -> Self::Result<View<V>>
837    where
838        V: 'static + Render,
839    {
840        self.window
841            .update(&mut self.cx, |_, cx| cx.replace_root_view(build_view))
842            .unwrap()
843    }
844
845    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
846        self.window
847            .update(&mut self.cx, |_, cx| {
848                view.read(cx).focus_handle(cx).clone().focus(cx)
849            })
850            .unwrap()
851    }
852
853    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
854    where
855        V: crate::ManagedView,
856    {
857        self.window
858            .update(&mut self.cx, |_, cx| {
859                view.update(cx, |_, cx| cx.emit(crate::DismissEvent))
860            })
861            .unwrap()
862    }
863}
864
865impl AnyWindowHandle {
866    /// Creates the given view in this window.
867    pub fn build_view<V: Render + 'static>(
868        &self,
869        cx: &mut TestAppContext,
870        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
871    ) -> View<V> {
872        self.update(cx, |_, cx| cx.new_view(build_view)).unwrap()
873    }
874}