test_context.rs

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