test_context.rs

  1use crate::{
  2    div, Action, AnyView, AnyWindowHandle, AppCell, AppContext, AsyncAppContext,
  3    BackgroundExecutor, Bounds, ClipboardItem, Context, Entity, EventEmitter, ForegroundExecutor,
  4    InputEvent, IntoElement, KeyDownEvent, Keystroke, Model, ModelContext, Pixels, Platform,
  5    PlatformWindow, Point, Render, Result, Size, Task, TestDispatcher, TestPlatform, TestWindow,
  6    TestWindowHandlers, TextSystem, View, ViewContext, VisualContext, WindowBounds, WindowContext,
  7    WindowHandle, WindowOptions,
  8};
  9use anyhow::{anyhow, bail};
 10use futures::{Stream, StreamExt};
 11use std::{future::Future, mem, ops::Deref, rc::Rc, sync::Arc, time::Duration};
 12
 13#[derive(Clone)]
 14pub struct TestAppContext {
 15    pub app: Rc<AppCell>,
 16    pub background_executor: BackgroundExecutor,
 17    pub foreground_executor: ForegroundExecutor,
 18    pub dispatcher: TestDispatcher,
 19    pub test_platform: Rc<TestPlatform>,
 20    text_system: Arc<TextSystem>,
 21}
 22
 23impl Context for TestAppContext {
 24    type Result<T> = T;
 25
 26    fn new_model<T: 'static>(
 27        &mut self,
 28        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
 29    ) -> Self::Result<Model<T>>
 30    where
 31        T: 'static,
 32    {
 33        let mut app = self.app.borrow_mut();
 34        app.new_model(build_model)
 35    }
 36
 37    fn update_model<T: 'static, R>(
 38        &mut self,
 39        handle: &Model<T>,
 40        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
 41    ) -> Self::Result<R> {
 42        let mut app = self.app.borrow_mut();
 43        app.update_model(handle, update)
 44    }
 45
 46    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
 47    where
 48        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
 49    {
 50        let mut lock = self.app.borrow_mut();
 51        lock.update_window(window, f)
 52    }
 53
 54    fn read_model<T, R>(
 55        &self,
 56        handle: &Model<T>,
 57        read: impl FnOnce(&T, &AppContext) -> R,
 58    ) -> Self::Result<R>
 59    where
 60        T: 'static,
 61    {
 62        let app = self.app.borrow();
 63        app.read_model(handle, read)
 64    }
 65
 66    fn read_window<T, R>(
 67        &self,
 68        window: &WindowHandle<T>,
 69        read: impl FnOnce(View<T>, &AppContext) -> R,
 70    ) -> Result<R>
 71    where
 72        T: 'static,
 73    {
 74        let app = self.app.borrow();
 75        app.read_window(window, read)
 76    }
 77}
 78
 79impl TestAppContext {
 80    pub fn new(dispatcher: TestDispatcher) -> Self {
 81        let arc_dispatcher = Arc::new(dispatcher.clone());
 82        let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
 83        let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
 84        let platform = TestPlatform::new(background_executor.clone(), foreground_executor.clone());
 85        let asset_source = Arc::new(());
 86        let http_client = util::http::FakeHttpClient::with_404_response();
 87        let text_system = Arc::new(TextSystem::new(platform.text_system()));
 88
 89        Self {
 90            app: AppContext::new(platform.clone(), asset_source, http_client),
 91            background_executor,
 92            foreground_executor,
 93            dispatcher: dispatcher.clone(),
 94            test_platform: platform,
 95            text_system,
 96        }
 97    }
 98
 99    pub fn new_app(&self) -> TestAppContext {
100        Self::new(self.dispatcher.clone())
101    }
102
103    pub fn quit(&self) {
104        self.app.borrow_mut().shutdown();
105    }
106
107    pub fn refresh(&mut self) -> Result<()> {
108        let mut app = self.app.borrow_mut();
109        app.refresh();
110        Ok(())
111    }
112
113    pub fn executor(&self) -> BackgroundExecutor {
114        self.background_executor.clone()
115    }
116
117    pub fn foreground_executor(&self) -> &ForegroundExecutor {
118        &self.foreground_executor
119    }
120
121    pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> R {
122        let mut cx = self.app.borrow_mut();
123        cx.update(f)
124    }
125
126    pub fn read<R>(&self, f: impl FnOnce(&AppContext) -> R) -> R {
127        let cx = self.app.borrow();
128        f(&*cx)
129    }
130
131    pub fn add_window<F, V>(&mut self, build_window: F) -> WindowHandle<V>
132    where
133        F: FnOnce(&mut ViewContext<V>) -> V,
134        V: 'static + Render,
135    {
136        let mut cx = self.app.borrow_mut();
137        cx.open_window(WindowOptions::default(), |cx| cx.new_view(build_window))
138    }
139
140    pub fn add_empty_window(&mut self) -> AnyWindowHandle {
141        let mut cx = self.app.borrow_mut();
142        cx.open_window(WindowOptions::default(), |cx| cx.new_view(|_| EmptyView {}))
143            .any_handle
144    }
145
146    pub fn add_window_view<F, V>(&mut self, build_window: F) -> (View<V>, &mut VisualTestContext)
147    where
148        F: FnOnce(&mut ViewContext<V>) -> V,
149        V: 'static + Render,
150    {
151        let mut cx = self.app.borrow_mut();
152        let window = cx.open_window(WindowOptions::default(), |cx| cx.new_view(build_window));
153        drop(cx);
154        let view = window.root_view(self).unwrap();
155        let cx = Box::new(VisualTestContext::from_window(*window.deref(), self));
156        // it might be nice to try and cleanup these at the end of each test.
157        (view, Box::leak(cx))
158    }
159
160    pub fn text_system(&self) -> &Arc<TextSystem> {
161        &self.text_system
162    }
163
164    pub fn write_to_clipboard(&self, item: ClipboardItem) {
165        self.test_platform.write_to_clipboard(item)
166    }
167
168    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
169        self.test_platform.read_from_clipboard()
170    }
171
172    pub fn simulate_new_path_selection(
173        &self,
174        select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
175    ) {
176        self.test_platform.simulate_new_path_selection(select_path);
177    }
178
179    pub fn simulate_prompt_answer(&self, button_ix: usize) {
180        self.test_platform.simulate_prompt_answer(button_ix);
181    }
182
183    pub fn has_pending_prompt(&self) -> bool {
184        self.test_platform.has_pending_prompt()
185    }
186
187    pub fn simulate_window_resize(&self, window_handle: AnyWindowHandle, size: Size<Pixels>) {
188        let (mut handlers, scale_factor) = self
189            .app
190            .borrow_mut()
191            .update_window(window_handle, |_, cx| {
192                let platform_window = cx.window.platform_window.as_test().unwrap();
193                let scale_factor = platform_window.scale_factor();
194                match &mut platform_window.bounds {
195                    WindowBounds::Fullscreen | WindowBounds::Maximized => {
196                        platform_window.bounds = WindowBounds::Fixed(Bounds {
197                            origin: Point::default(),
198                            size: size.map(|pixels| f64::from(pixels).into()),
199                        });
200                    }
201                    WindowBounds::Fixed(bounds) => {
202                        bounds.size = size.map(|pixels| f64::from(pixels).into());
203                    }
204                }
205
206                (
207                    mem::take(&mut platform_window.handlers.lock().resize),
208                    scale_factor,
209                )
210            })
211            .unwrap();
212
213        for handler in &mut handlers {
214            handler(size, scale_factor);
215        }
216
217        self.app
218            .borrow_mut()
219            .update_window(window_handle, |_, cx| {
220                let platform_window = cx.window.platform_window.as_test().unwrap();
221                platform_window.handlers.lock().resize = handlers;
222            })
223            .unwrap();
224    }
225
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    pub fn has_global<G: 'static>(&self) -> bool {
235        let app = self.app.borrow();
236        app.has_global::<G>()
237    }
238
239    pub fn read_global<G: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> R {
240        let app = self.app.borrow();
241        read(app.global(), &app)
242    }
243
244    pub fn try_read_global<G: 'static, R>(
245        &self,
246        read: impl FnOnce(&G, &AppContext) -> R,
247    ) -> Option<R> {
248        let lock = self.app.borrow();
249        Some(read(lock.try_global()?, &lock))
250    }
251
252    pub fn set_global<G: 'static>(&mut self, global: G) {
253        let mut lock = self.app.borrow_mut();
254        lock.set_global(global);
255    }
256
257    pub fn update_global<G: 'static, R>(
258        &mut self,
259        update: impl FnOnce(&mut G, &mut AppContext) -> R,
260    ) -> R {
261        let mut lock = self.app.borrow_mut();
262        lock.update_global(update)
263    }
264
265    pub fn to_async(&self) -> AsyncAppContext {
266        AsyncAppContext {
267            app: Rc::downgrade(&self.app),
268            background_executor: self.background_executor.clone(),
269            foreground_executor: self.foreground_executor.clone(),
270        }
271    }
272
273    pub fn dispatch_action<A>(&mut self, window: AnyWindowHandle, action: A)
274    where
275        A: Action,
276    {
277        window
278            .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
279            .unwrap();
280
281        self.background_executor.run_until_parked()
282    }
283
284    /// simulate_keystrokes takes a space-separated list of keys to type.
285    /// cx.simulate_keystrokes("cmd-shift-p b k s p enter")
286    /// will run backspace on the current editor through the command palette.
287    pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
288        for keystroke in keystrokes
289            .split(" ")
290            .map(Keystroke::parse)
291            .map(Result::unwrap)
292        {
293            self.dispatch_keystroke(window, keystroke.into(), false);
294        }
295
296        self.background_executor.run_until_parked()
297    }
298
299    /// simulate_input takes a string of text to type.
300    /// cx.simulate_input("abc")
301    /// will type abc into your current editor.
302    pub fn simulate_input(&mut self, window: AnyWindowHandle, input: &str) {
303        for keystroke in input.split("").map(Keystroke::parse).map(Result::unwrap) {
304            self.dispatch_keystroke(window, keystroke.into(), false);
305        }
306
307        self.background_executor.run_until_parked()
308    }
309
310    pub fn dispatch_keystroke(
311        &mut self,
312        window: AnyWindowHandle,
313        keystroke: Keystroke,
314        is_held: bool,
315    ) {
316        let keystroke2 = keystroke.clone();
317        let handled = window
318            .update(self, |_, cx| {
319                cx.dispatch_event(InputEvent::KeyDown(KeyDownEvent { keystroke, is_held }))
320            })
321            .is_ok_and(|handled| handled);
322        if handled {
323            return;
324        }
325
326        let input_handler = self.update_test_window(window, |window| window.input_handler.clone());
327        let Some(input_handler) = input_handler else {
328            panic!(
329                "dispatch_keystroke {:?} failed to dispatch action or input",
330                &keystroke2
331            );
332        };
333        let text = keystroke2.ime_key.unwrap_or(keystroke2.key);
334        input_handler.lock().replace_text_in_range(None, &text);
335    }
336
337    pub fn update_test_window<R>(
338        &mut self,
339        window: AnyWindowHandle,
340        f: impl FnOnce(&mut TestWindow) -> R,
341    ) -> R {
342        window
343            .update(self, |_, cx| {
344                f(cx.window
345                    .platform_window
346                    .as_any_mut()
347                    .downcast_mut::<TestWindow>()
348                    .unwrap())
349            })
350            .unwrap()
351    }
352
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    pub fn events<Evt, T: 'static + EventEmitter<Evt>>(
370        &mut self,
371        entity: &Model<T>,
372    ) -> futures::channel::mpsc::UnboundedReceiver<Evt>
373    where
374        Evt: 'static + Clone,
375    {
376        let (tx, rx) = futures::channel::mpsc::unbounded();
377        entity
378            .update(self, |_, cx: &mut ModelContext<T>| {
379                cx.subscribe(entity, move |_model, _handle, event, _cx| {
380                    let _ = tx.unbounded_send(event.clone());
381                })
382            })
383            .detach();
384        rx
385    }
386
387    pub async fn condition<T: 'static>(
388        &mut self,
389        model: &Model<T>,
390        mut predicate: impl FnMut(&mut T, &mut ModelContext<T>) -> bool,
391    ) {
392        let timer = self.executor().timer(Duration::from_secs(3));
393        let mut notifications = self.notifications(model);
394
395        use futures::FutureExt as _;
396        use smol::future::FutureExt as _;
397
398        async {
399            loop {
400                if model.update(self, &mut predicate) {
401                    return Ok(());
402                }
403
404                if notifications.next().await.is_none() {
405                    bail!("model dropped")
406                }
407            }
408        }
409        .race(timer.map(|_| Err(anyhow!("condition timed out"))))
410        .await
411        .unwrap();
412    }
413}
414
415impl<T: Send> Model<T> {
416    pub fn next_event<Evt>(&self, cx: &mut TestAppContext) -> Evt
417    where
418        Evt: Send + Clone + 'static,
419        T: EventEmitter<Evt>,
420    {
421        let (tx, mut rx) = futures::channel::mpsc::unbounded();
422        let _subscription = self.update(cx, |_, cx| {
423            cx.subscribe(self, move |_, _, event, _| {
424                tx.unbounded_send(event.clone()).ok();
425            })
426        });
427
428        // Run other tasks until the event is emitted.
429        loop {
430            match rx.try_next() {
431                Ok(Some(event)) => return event,
432                Ok(None) => panic!("model was dropped"),
433                Err(_) => {
434                    if !cx.executor().tick() {
435                        break;
436                    }
437                }
438            }
439        }
440        panic!("no event received")
441    }
442}
443
444impl<V: 'static> View<V> {
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    pub fn condition<Evt>(
472        &self,
473        cx: &TestAppContext,
474        mut predicate: impl FnMut(&V, &AppContext) -> bool,
475    ) -> impl Future<Output = ()>
476    where
477        Evt: 'static,
478        V: EventEmitter<Evt>,
479    {
480        use postage::prelude::{Sink as _, Stream as _};
481
482        let (tx, mut rx) = postage::mpsc::channel(1024);
483        let timeout_duration = Duration::from_millis(100); //todo!() cx.condition_duration();
484
485        let mut cx = cx.app.borrow_mut();
486        let subscriptions = (
487            cx.observe(self, {
488                let mut tx = tx.clone();
489                move |_, _| {
490                    tx.blocking_send(()).ok();
491                }
492            }),
493            cx.subscribe(self, {
494                let mut tx = tx.clone();
495                move |_, _: &Evt, _| {
496                    tx.blocking_send(()).ok();
497                }
498            }),
499        );
500
501        let cx = cx.this.upgrade().unwrap();
502        let handle = self.downgrade();
503
504        async move {
505            crate::util::timeout(timeout_duration, async move {
506                loop {
507                    {
508                        let cx = cx.borrow();
509                        let cx = &*cx;
510                        if predicate(
511                            handle
512                                .upgrade()
513                                .expect("view dropped with pending condition")
514                                .read(cx),
515                            cx,
516                        ) {
517                            break;
518                        }
519                    }
520
521                    // todo!(start_waiting)
522                    // cx.borrow().foreground_executor().start_waiting();
523                    rx.recv()
524                        .await
525                        .expect("view dropped with pending condition");
526                    // cx.borrow().foreground_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)]
538pub struct VisualTestContext<'a> {
539    #[deref]
540    #[deref_mut]
541    cx: &'a mut TestAppContext,
542    window: AnyWindowHandle,
543}
544
545impl<'a> VisualTestContext<'a> {
546    pub fn update<R>(&mut self, f: impl FnOnce(&mut WindowContext) -> R) -> R {
547        self.cx.update_window(self.window, |_, cx| f(cx)).unwrap()
548    }
549
550    pub fn from_window(window: AnyWindowHandle, cx: &'a mut TestAppContext) -> Self {
551        Self { cx, window }
552    }
553
554    pub fn run_until_parked(&self) {
555        self.cx.background_executor.run_until_parked();
556    }
557
558    pub fn dispatch_action<A>(&mut self, action: A)
559    where
560        A: Action,
561    {
562        self.cx.dispatch_action(self.window, action)
563    }
564
565    pub fn window_title(&mut self) -> Option<String> {
566        self.cx
567            .update_window(self.window, |_, cx| {
568                cx.window.platform_window.as_test().unwrap().title.clone()
569            })
570            .unwrap()
571    }
572
573    pub fn simulate_keystrokes(&mut self, keystrokes: &str) {
574        self.cx.simulate_keystrokes(self.window, keystrokes)
575    }
576
577    pub fn simulate_input(&mut self, input: &str) {
578        self.cx.simulate_input(self.window, input)
579    }
580
581    pub fn simulate_activation(&mut self) {
582        self.simulate_window_events(&mut |handlers| {
583            handlers
584                .active_status_change
585                .iter_mut()
586                .for_each(|f| f(true));
587        })
588    }
589
590    pub fn simulate_deactivation(&mut self) {
591        self.simulate_window_events(&mut |handlers| {
592            handlers
593                .active_status_change
594                .iter_mut()
595                .for_each(|f| f(false));
596        })
597    }
598
599    fn simulate_window_events(&mut self, f: &mut dyn FnMut(&mut TestWindowHandlers)) {
600        let handlers = self
601            .cx
602            .update_window(self.window, |_, cx| {
603                cx.window
604                    .platform_window
605                    .as_test()
606                    .unwrap()
607                    .handlers
608                    .clone()
609            })
610            .unwrap();
611        f(&mut *handlers.lock());
612    }
613}
614
615impl<'a> Context for VisualTestContext<'a> {
616    type Result<T> = <TestAppContext as Context>::Result<T>;
617
618    fn new_model<T: 'static>(
619        &mut self,
620        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
621    ) -> Self::Result<Model<T>> {
622        self.cx.new_model(build_model)
623    }
624
625    fn update_model<T, R>(
626        &mut self,
627        handle: &Model<T>,
628        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
629    ) -> Self::Result<R>
630    where
631        T: 'static,
632    {
633        self.cx.update_model(handle, update)
634    }
635
636    fn read_model<T, R>(
637        &self,
638        handle: &Model<T>,
639        read: impl FnOnce(&T, &AppContext) -> R,
640    ) -> Self::Result<R>
641    where
642        T: 'static,
643    {
644        self.cx.read_model(handle, read)
645    }
646
647    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
648    where
649        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
650    {
651        self.cx.update_window(window, f)
652    }
653
654    fn read_window<T, R>(
655        &self,
656        window: &WindowHandle<T>,
657        read: impl FnOnce(View<T>, &AppContext) -> R,
658    ) -> Result<R>
659    where
660        T: 'static,
661    {
662        self.cx.read_window(window, read)
663    }
664}
665
666impl<'a> VisualContext for VisualTestContext<'a> {
667    fn new_view<V>(
668        &mut self,
669        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
670    ) -> Self::Result<View<V>>
671    where
672        V: 'static + Render,
673    {
674        self.window
675            .update(self.cx, |_, cx| cx.new_view(build_view))
676            .unwrap()
677    }
678
679    fn update_view<V: 'static, R>(
680        &mut self,
681        view: &View<V>,
682        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
683    ) -> Self::Result<R> {
684        self.window
685            .update(self.cx, |_, cx| cx.update_view(view, update))
686            .unwrap()
687    }
688
689    fn replace_root_view<V>(
690        &mut self,
691        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
692    ) -> Self::Result<View<V>>
693    where
694        V: 'static + Render,
695    {
696        self.window
697            .update(self.cx, |_, cx| cx.replace_root_view(build_view))
698            .unwrap()
699    }
700
701    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
702        self.window
703            .update(self.cx, |_, cx| {
704                view.read(cx).focus_handle(cx).clone().focus(cx)
705            })
706            .unwrap()
707    }
708
709    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
710    where
711        V: crate::ManagedView,
712    {
713        self.window
714            .update(self.cx, |_, cx| {
715                view.update(cx, |_, cx| cx.emit(crate::DismissEvent))
716            })
717            .unwrap()
718    }
719}
720
721impl AnyWindowHandle {
722    pub fn build_view<V: Render + 'static>(
723        &self,
724        cx: &mut TestAppContext,
725        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
726    ) -> View<V> {
727        self.update(cx, |_, cx| cx.new_view(build_view)).unwrap()
728    }
729}
730
731pub struct EmptyView {}
732
733impl Render for EmptyView {
734    fn render(&mut self, _cx: &mut crate::ViewContext<Self>) -> impl IntoElement {
735        div()
736    }
737}