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> View<V> {
390    pub fn condition<Evt>(
391        &self,
392        cx: &TestAppContext,
393        mut predicate: impl FnMut(&V, &AppContext) -> bool,
394    ) -> impl Future<Output = ()>
395    where
396        Evt: 'static,
397        V: EventEmitter<Evt>,
398    {
399        use postage::prelude::{Sink as _, Stream as _};
400
401        let (tx, mut rx) = postage::mpsc::channel(1024);
402        let timeout_duration = Duration::from_millis(100); //todo!() cx.condition_duration();
403
404        let mut cx = cx.app.borrow_mut();
405        let subscriptions = (
406            cx.observe(self, {
407                let mut tx = tx.clone();
408                move |_, _| {
409                    tx.blocking_send(()).ok();
410                }
411            }),
412            cx.subscribe(self, {
413                let mut tx = tx.clone();
414                move |_, _: &Evt, _| {
415                    tx.blocking_send(()).ok();
416                }
417            }),
418        );
419
420        let cx = cx.this.upgrade().unwrap();
421        let handle = self.downgrade();
422
423        async move {
424            crate::util::timeout(timeout_duration, async move {
425                loop {
426                    {
427                        let cx = cx.borrow();
428                        let cx = &*cx;
429                        if predicate(
430                            handle
431                                .upgrade()
432                                .expect("view dropped with pending condition")
433                                .read(cx),
434                            cx,
435                        ) {
436                            break;
437                        }
438                    }
439
440                    // todo!(start_waiting)
441                    // cx.borrow().foreground_executor().start_waiting();
442                    rx.recv()
443                        .await
444                        .expect("view dropped with pending condition");
445                    // cx.borrow().foreground_executor().finish_waiting();
446                }
447            })
448            .await
449            .expect("condition timed out");
450            drop(subscriptions);
451        }
452    }
453}
454
455use derive_more::{Deref, DerefMut};
456#[derive(Deref, DerefMut)]
457pub struct VisualTestContext<'a> {
458    #[deref]
459    #[deref_mut]
460    cx: &'a mut TestAppContext,
461    window: AnyWindowHandle,
462}
463
464impl<'a> VisualTestContext<'a> {
465    pub fn from_window(window: AnyWindowHandle, cx: &'a mut TestAppContext) -> Self {
466        Self { cx, window }
467    }
468
469    pub fn run_until_parked(&self) {
470        self.cx.background_executor.run_until_parked();
471    }
472
473    pub fn dispatch_action<A>(&mut self, action: A)
474    where
475        A: Action,
476    {
477        self.cx.dispatch_action(self.window, action)
478    }
479
480    pub fn simulate_keystrokes(&mut self, keystrokes: &str) {
481        self.cx.simulate_keystrokes(self.window, keystrokes)
482    }
483
484    pub fn simulate_input(&mut self, input: &str) {
485        self.cx.simulate_input(self.window, input)
486    }
487}
488
489impl<'a> Context for VisualTestContext<'a> {
490    type Result<T> = <TestAppContext as Context>::Result<T>;
491
492    fn build_model<T: 'static>(
493        &mut self,
494        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
495    ) -> Self::Result<Model<T>> {
496        self.cx.build_model(build_model)
497    }
498
499    fn update_model<T, R>(
500        &mut self,
501        handle: &Model<T>,
502        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
503    ) -> Self::Result<R>
504    where
505        T: 'static,
506    {
507        self.cx.update_model(handle, update)
508    }
509
510    fn read_model<T, R>(
511        &self,
512        handle: &Model<T>,
513        read: impl FnOnce(&T, &AppContext) -> R,
514    ) -> Self::Result<R>
515    where
516        T: 'static,
517    {
518        self.cx.read_model(handle, read)
519    }
520
521    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
522    where
523        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
524    {
525        self.cx.update_window(window, f)
526    }
527
528    fn read_window<T, R>(
529        &self,
530        window: &WindowHandle<T>,
531        read: impl FnOnce(View<T>, &AppContext) -> R,
532    ) -> Result<R>
533    where
534        T: 'static,
535    {
536        self.cx.read_window(window, read)
537    }
538}
539
540impl<'a> VisualContext for VisualTestContext<'a> {
541    fn build_view<V>(
542        &mut self,
543        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
544    ) -> Self::Result<View<V>>
545    where
546        V: 'static + Render,
547    {
548        self.window
549            .update(self.cx, |_, cx| cx.build_view(build_view))
550            .unwrap()
551    }
552
553    fn update_view<V: 'static, R>(
554        &mut self,
555        view: &View<V>,
556        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
557    ) -> Self::Result<R> {
558        self.window
559            .update(self.cx, |_, cx| cx.update_view(view, update))
560            .unwrap()
561    }
562
563    fn replace_root_view<V>(
564        &mut self,
565        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
566    ) -> Self::Result<View<V>>
567    where
568        V: Render,
569    {
570        self.window
571            .update(self.cx, |_, cx| cx.replace_root_view(build_view))
572            .unwrap()
573    }
574
575    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
576        self.window
577            .update(self.cx, |_, cx| {
578                view.read(cx).focus_handle(cx).clone().focus(cx)
579            })
580            .unwrap()
581    }
582}
583
584impl AnyWindowHandle {
585    pub fn build_view<V: Render + 'static>(
586        &self,
587        cx: &mut TestAppContext,
588        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
589    ) -> View<V> {
590        self.update(cx, |_, cx| cx.build_view(build_view)).unwrap()
591    }
592}
593
594pub struct EmptyView {}
595
596impl Render for EmptyView {
597    type Element = Div<Self>;
598
599    fn render(&mut self, _cx: &mut crate::ViewContext<Self>) -> Self::Element {
600        div()
601    }
602}