test_context.rs

  1use crate::{
  2    div, Action, AnyView, AnyWindowHandle, AppCell, AppContext, AsyncAppContext,
  3    BackgroundExecutor, Context, Div, EventEmitter, ForegroundExecutor, InputEvent, KeyDownEvent,
  4    Keystroke, Model, ModelContext, Render, Result, Task, TestDispatcher, TestPlatform, TestWindow,
  5    View, ViewContext, VisualContext, WindowContext, WindowHandle, WindowOptions,
  6};
  7use anyhow::{anyhow, bail};
  8use futures::{Stream, StreamExt};
  9use std::{future::Future, ops::Deref, rc::Rc, sync::Arc, time::Duration};
 10
 11#[derive(Clone)]
 12pub struct TestAppContext {
 13    pub app: Rc<AppCell>,
 14    pub background_executor: BackgroundExecutor,
 15    pub foreground_executor: ForegroundExecutor,
 16    pub dispatcher: TestDispatcher,
 17    pub test_platform: Rc<TestPlatform>,
 18}
 19
 20impl Context for TestAppContext {
 21    type Result<T> = T;
 22
 23    fn build_model<T: 'static>(
 24        &mut self,
 25        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
 26    ) -> Self::Result<Model<T>>
 27    where
 28        T: 'static,
 29    {
 30        let mut app = self.app.borrow_mut();
 31        app.build_model(build_model)
 32    }
 33
 34    fn update_model<T: 'static, R>(
 35        &mut self,
 36        handle: &Model<T>,
 37        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
 38    ) -> Self::Result<R> {
 39        let mut app = self.app.borrow_mut();
 40        app.update_model(handle, update)
 41    }
 42
 43    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
 44    where
 45        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
 46    {
 47        let mut lock = self.app.borrow_mut();
 48        lock.update_window(window, f)
 49    }
 50
 51    fn read_model<T, R>(
 52        &self,
 53        handle: &Model<T>,
 54        read: impl FnOnce(&T, &AppContext) -> R,
 55    ) -> Self::Result<R>
 56    where
 57        T: 'static,
 58    {
 59        let app = self.app.borrow();
 60        app.read_model(handle, read)
 61    }
 62
 63    fn read_window<T, R>(
 64        &self,
 65        window: &WindowHandle<T>,
 66        read: impl FnOnce(View<T>, &AppContext) -> R,
 67    ) -> Result<R>
 68    where
 69        T: 'static,
 70    {
 71        let app = self.app.borrow();
 72        app.read_window(window, read)
 73    }
 74}
 75
 76impl TestAppContext {
 77    pub fn new(dispatcher: TestDispatcher) -> Self {
 78        let arc_dispatcher = Arc::new(dispatcher.clone());
 79        let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
 80        let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
 81        let platform = TestPlatform::new(background_executor.clone(), foreground_executor.clone());
 82        let asset_source = Arc::new(());
 83        let http_client = util::http::FakeHttpClient::with_404_response();
 84
 85        Self {
 86            app: AppContext::new(platform.clone(), asset_source, http_client),
 87            background_executor,
 88            foreground_executor,
 89            dispatcher: dispatcher.clone(),
 90            test_platform: platform,
 91        }
 92    }
 93
 94    pub fn new_app(&self) -> TestAppContext {
 95        Self::new(self.dispatcher.clone())
 96    }
 97
 98    pub fn quit(&self) {
 99        self.app.borrow_mut().shutdown();
100    }
101
102    pub fn refresh(&mut self) -> Result<()> {
103        let mut app = self.app.borrow_mut();
104        app.refresh();
105        Ok(())
106    }
107
108    pub fn executor(&self) -> BackgroundExecutor {
109        self.background_executor.clone()
110    }
111
112    pub fn foreground_executor(&self) -> &ForegroundExecutor {
113        &self.foreground_executor
114    }
115
116    pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> R {
117        let mut cx = self.app.borrow_mut();
118        cx.update(f)
119    }
120
121    pub fn read<R>(&self, f: impl FnOnce(&AppContext) -> R) -> R {
122        let cx = self.app.borrow();
123        f(&*cx)
124    }
125
126    pub fn add_window<F, V>(&mut self, build_window: F) -> WindowHandle<V>
127    where
128        F: FnOnce(&mut ViewContext<V>) -> V,
129        V: Render,
130    {
131        let mut cx = self.app.borrow_mut();
132        cx.open_window(WindowOptions::default(), |cx| cx.build_view(build_window))
133    }
134
135    pub fn add_empty_window(&mut self) -> AnyWindowHandle {
136        let mut cx = self.app.borrow_mut();
137        cx.open_window(WindowOptions::default(), |cx| {
138            cx.build_view(|_| EmptyView {})
139        })
140        .any_handle
141    }
142
143    pub fn add_window_view<F, V>(&mut self, build_window: F) -> (View<V>, &mut VisualTestContext)
144    where
145        F: FnOnce(&mut ViewContext<V>) -> V,
146        V: Render,
147    {
148        let mut cx = self.app.borrow_mut();
149        let window = cx.open_window(WindowOptions::default(), |cx| cx.build_view(build_window));
150        drop(cx);
151        let view = window.root_view(self).unwrap();
152        let cx = Box::new(VisualTestContext::from_window(*window.deref(), self));
153        // it might be nice to try and cleanup these at the end of each test.
154        (view, Box::leak(cx))
155    }
156
157    pub fn simulate_new_path_selection(
158        &self,
159        select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
160    ) {
161        self.test_platform.simulate_new_path_selection(select_path);
162    }
163
164    pub fn simulate_prompt_answer(&self, button_ix: usize) {
165        self.test_platform.simulate_prompt_answer(button_ix);
166    }
167
168    pub fn has_pending_prompt(&self) -> bool {
169        self.test_platform.has_pending_prompt()
170    }
171
172    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
173    where
174        Fut: Future<Output = R> + 'static,
175        R: 'static,
176    {
177        self.foreground_executor.spawn(f(self.to_async()))
178    }
179
180    pub fn has_global<G: 'static>(&self) -> bool {
181        let app = self.app.borrow();
182        app.has_global::<G>()
183    }
184
185    pub fn read_global<G: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> R {
186        let app = self.app.borrow();
187        read(app.global(), &app)
188    }
189
190    pub fn try_read_global<G: 'static, R>(
191        &self,
192        read: impl FnOnce(&G, &AppContext) -> R,
193    ) -> Option<R> {
194        let lock = self.app.borrow();
195        Some(read(lock.try_global()?, &lock))
196    }
197
198    pub fn set_global<G: 'static>(&mut self, global: G) {
199        let mut lock = self.app.borrow_mut();
200        lock.set_global(global);
201    }
202
203    pub fn update_global<G: 'static, R>(
204        &mut self,
205        update: impl FnOnce(&mut G, &mut AppContext) -> R,
206    ) -> R {
207        let mut lock = self.app.borrow_mut();
208        lock.update_global(update)
209    }
210
211    pub fn to_async(&self) -> AsyncAppContext {
212        AsyncAppContext {
213            app: Rc::downgrade(&self.app),
214            background_executor: self.background_executor.clone(),
215            foreground_executor: self.foreground_executor.clone(),
216        }
217    }
218
219    pub fn dispatch_action<A>(&mut self, window: AnyWindowHandle, action: A)
220    where
221        A: Action,
222    {
223        window
224            .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
225            .unwrap();
226
227        self.background_executor.run_until_parked()
228    }
229
230    /// simulate_keystrokes takes a space-separated list of keys to type.
231    /// cx.simulate_keystrokes("cmd-shift-p b k s p enter")
232    /// will run backspace on the current editor through the command palette.
233    pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
234        for keystroke in keystrokes
235            .split(" ")
236            .map(Keystroke::parse)
237            .map(Result::unwrap)
238        {
239            self.dispatch_keystroke(window, keystroke.into(), false);
240        }
241
242        self.background_executor.run_until_parked()
243    }
244
245    /// simulate_input takes a string of text to type.
246    /// cx.simulate_input("abc")
247    /// will type abc into your current editor.
248    pub fn simulate_input(&mut self, window: AnyWindowHandle, input: &str) {
249        for keystroke in input.split("").map(Keystroke::parse).map(Result::unwrap) {
250            self.dispatch_keystroke(window, keystroke.into(), false);
251        }
252
253        self.background_executor.run_until_parked()
254    }
255
256    pub fn dispatch_keystroke(
257        &mut self,
258        window: AnyWindowHandle,
259        keystroke: Keystroke,
260        is_held: bool,
261    ) {
262        let keystroke2 = keystroke.clone();
263        let handled = window
264            .update(self, |_, cx| {
265                cx.dispatch_event(InputEvent::KeyDown(KeyDownEvent { keystroke, is_held }))
266            })
267            .is_ok_and(|handled| handled);
268        if handled {
269            return;
270        }
271
272        let input_handler = self.update_test_window(window, |window| window.input_handler.clone());
273        let Some(input_handler) = input_handler else {
274            panic!(
275                "dispatch_keystroke {:?} failed to dispatch action or input",
276                &keystroke2
277            );
278        };
279        let text = keystroke2.ime_key.unwrap_or(keystroke2.key);
280        input_handler.lock().replace_text_in_range(None, &text);
281    }
282
283    pub fn update_test_window<R>(
284        &mut self,
285        window: AnyWindowHandle,
286        f: impl FnOnce(&mut TestWindow) -> R,
287    ) -> R {
288        window
289            .update(self, |_, cx| {
290                f(cx.window
291                    .platform_window
292                    .as_any_mut()
293                    .downcast_mut::<TestWindow>()
294                    .unwrap())
295            })
296            .unwrap()
297    }
298
299    pub fn notifications<T: 'static>(&mut self, entity: &Model<T>) -> impl Stream<Item = ()> {
300        let (tx, rx) = futures::channel::mpsc::unbounded();
301
302        entity.update(self, move |_, cx: &mut ModelContext<T>| {
303            cx.observe(entity, {
304                let tx = tx.clone();
305                move |_, _, _| {
306                    let _ = tx.unbounded_send(());
307                }
308            })
309            .detach();
310
311            cx.on_release(move |_, _| tx.close_channel()).detach();
312        });
313
314        rx
315    }
316
317    pub fn events<Evt, T: 'static + EventEmitter<Evt>>(
318        &mut self,
319        entity: &Model<T>,
320    ) -> futures::channel::mpsc::UnboundedReceiver<Evt>
321    where
322        Evt: 'static + Clone,
323    {
324        let (tx, rx) = futures::channel::mpsc::unbounded();
325        entity
326            .update(self, |_, cx: &mut ModelContext<T>| {
327                cx.subscribe(entity, move |_model, _handle, event, _cx| {
328                    let _ = tx.unbounded_send(event.clone());
329                })
330            })
331            .detach();
332        rx
333    }
334
335    pub async fn condition<T: 'static>(
336        &mut self,
337        model: &Model<T>,
338        mut predicate: impl FnMut(&mut T, &mut ModelContext<T>) -> bool,
339    ) {
340        let timer = self.executor().timer(Duration::from_secs(3));
341        let mut notifications = self.notifications(model);
342
343        use futures::FutureExt as _;
344        use smol::future::FutureExt as _;
345
346        async {
347            while notifications.next().await.is_some() {
348                if model.update(self, &mut predicate) {
349                    return Ok(());
350                }
351            }
352            bail!("model dropped")
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 from_window(window: AnyWindowHandle, cx: &'a mut TestAppContext) -> Self {
492        Self { cx, window }
493    }
494
495    pub fn run_until_parked(&self) {
496        self.cx.background_executor.run_until_parked();
497    }
498
499    pub fn dispatch_action<A>(&mut self, action: A)
500    where
501        A: Action,
502    {
503        self.cx.dispatch_action(self.window, action)
504    }
505
506    pub fn simulate_keystrokes(&mut self, keystrokes: &str) {
507        self.cx.simulate_keystrokes(self.window, keystrokes)
508    }
509
510    pub fn simulate_input(&mut self, input: &str) {
511        self.cx.simulate_input(self.window, input)
512    }
513}
514
515impl<'a> Context for VisualTestContext<'a> {
516    type Result<T> = <TestAppContext as Context>::Result<T>;
517
518    fn build_model<T: 'static>(
519        &mut self,
520        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
521    ) -> Self::Result<Model<T>> {
522        self.cx.build_model(build_model)
523    }
524
525    fn update_model<T, R>(
526        &mut self,
527        handle: &Model<T>,
528        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
529    ) -> Self::Result<R>
530    where
531        T: 'static,
532    {
533        self.cx.update_model(handle, update)
534    }
535
536    fn read_model<T, R>(
537        &self,
538        handle: &Model<T>,
539        read: impl FnOnce(&T, &AppContext) -> R,
540    ) -> Self::Result<R>
541    where
542        T: 'static,
543    {
544        self.cx.read_model(handle, read)
545    }
546
547    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
548    where
549        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
550    {
551        self.cx.update_window(window, f)
552    }
553
554    fn read_window<T, R>(
555        &self,
556        window: &WindowHandle<T>,
557        read: impl FnOnce(View<T>, &AppContext) -> R,
558    ) -> Result<R>
559    where
560        T: 'static,
561    {
562        self.cx.read_window(window, read)
563    }
564}
565
566impl<'a> VisualContext for VisualTestContext<'a> {
567    fn build_view<V>(
568        &mut self,
569        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
570    ) -> Self::Result<View<V>>
571    where
572        V: 'static + Render,
573    {
574        self.window
575            .update(self.cx, |_, cx| cx.build_view(build_view))
576            .unwrap()
577    }
578
579    fn update_view<V: 'static, R>(
580        &mut self,
581        view: &View<V>,
582        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
583    ) -> Self::Result<R> {
584        self.window
585            .update(self.cx, |_, cx| cx.update_view(view, update))
586            .unwrap()
587    }
588
589    fn replace_root_view<V>(
590        &mut self,
591        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
592    ) -> Self::Result<View<V>>
593    where
594        V: Render,
595    {
596        self.window
597            .update(self.cx, |_, cx| cx.replace_root_view(build_view))
598            .unwrap()
599    }
600
601    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
602        self.window
603            .update(self.cx, |_, cx| {
604                view.read(cx).focus_handle(cx).clone().focus(cx)
605            })
606            .unwrap()
607    }
608
609    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
610    where
611        V: crate::ManagedView,
612    {
613        self.window
614            .update(self.cx, |_, cx| {
615                view.update(cx, |_, cx| cx.emit(crate::Manager::Dismiss))
616            })
617            .unwrap()
618    }
619}
620
621impl AnyWindowHandle {
622    pub fn build_view<V: Render + 'static>(
623        &self,
624        cx: &mut TestAppContext,
625        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
626    ) -> View<V> {
627        self.update(cx, |_, cx| cx.build_view(build_view)).unwrap()
628    }
629}
630
631pub struct EmptyView {}
632
633impl Render for EmptyView {
634    type Element = Div<Self>;
635
636    fn render(&mut self, _cx: &mut crate::ViewContext<Self>) -> Self::Element {
637        div()
638    }
639}