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>, 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        (view, VisualTestContext::from_window(*window.deref(), self))
153    }
154
155    pub fn simulate_new_path_selection(
156        &self,
157        select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
158    ) {
159        self.test_platform.simulate_new_path_selection(select_path);
160    }
161
162    pub fn simulate_prompt_answer(&self, button_ix: usize) {
163        self.test_platform.simulate_prompt_answer(button_ix);
164    }
165
166    pub fn has_pending_prompt(&self) -> bool {
167        self.test_platform.has_pending_prompt()
168    }
169
170    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
171    where
172        Fut: Future<Output = R> + 'static,
173        R: 'static,
174    {
175        self.foreground_executor.spawn(f(self.to_async()))
176    }
177
178    pub fn has_global<G: 'static>(&self) -> bool {
179        let app = self.app.borrow();
180        app.has_global::<G>()
181    }
182
183    pub fn read_global<G: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> R {
184        let app = self.app.borrow();
185        read(app.global(), &app)
186    }
187
188    pub fn try_read_global<G: 'static, R>(
189        &self,
190        read: impl FnOnce(&G, &AppContext) -> R,
191    ) -> Option<R> {
192        let lock = self.app.borrow();
193        Some(read(lock.try_global()?, &lock))
194    }
195
196    pub fn set_global<G: 'static>(&mut self, global: G) {
197        let mut lock = self.app.borrow_mut();
198        lock.set_global(global);
199    }
200
201    pub fn update_global<G: 'static, R>(
202        &mut self,
203        update: impl FnOnce(&mut G, &mut AppContext) -> R,
204    ) -> R {
205        let mut lock = self.app.borrow_mut();
206        lock.update_global(update)
207    }
208
209    pub fn to_async(&self) -> AsyncAppContext {
210        AsyncAppContext {
211            app: Rc::downgrade(&self.app),
212            background_executor: self.background_executor.clone(),
213            foreground_executor: self.foreground_executor.clone(),
214        }
215    }
216
217    pub fn dispatch_action<A>(&mut self, window: AnyWindowHandle, action: A)
218    where
219        A: Action,
220    {
221        window
222            .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
223            .unwrap();
224
225        self.background_executor.run_until_parked()
226    }
227
228    /// simulate_keystrokes takes a space-separated list of keys to type.
229    /// cx.simulate_keystrokes("cmd-shift-p b k s p enter")
230    /// will run backspace on the current editor through the command palette.
231    pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
232        for keystroke in keystrokes
233            .split(" ")
234            .map(Keystroke::parse)
235            .map(Result::unwrap)
236        {
237            self.dispatch_keystroke(window, keystroke.into(), false);
238        }
239
240        self.background_executor.run_until_parked()
241    }
242
243    /// simulate_input takes a string of text to type.
244    /// cx.simulate_input("abc")
245    /// will type abc into your current editor.
246    pub fn simulate_input(&mut self, window: AnyWindowHandle, input: &str) {
247        for keystroke in input.split("").map(Keystroke::parse).map(Result::unwrap) {
248            self.dispatch_keystroke(window, keystroke.into(), false);
249        }
250
251        self.background_executor.run_until_parked()
252    }
253
254    pub fn dispatch_keystroke(
255        &mut self,
256        window: AnyWindowHandle,
257        keystroke: Keystroke,
258        is_held: bool,
259    ) {
260        let keystroke2 = keystroke.clone();
261        let handled = window
262            .update(self, |_, cx| {
263                cx.dispatch_event(InputEvent::KeyDown(KeyDownEvent { keystroke, is_held }))
264            })
265            .is_ok_and(|handled| handled);
266        if handled {
267            return;
268        }
269
270        let input_handler = self.update_test_window(window, |window| window.input_handler.clone());
271        let Some(input_handler) = input_handler else {
272            panic!(
273                "dispatch_keystroke {:?} failed to dispatch action or input",
274                &keystroke2
275            );
276        };
277        let text = keystroke2.ime_key.unwrap_or(keystroke2.key);
278        input_handler.lock().replace_text_in_range(None, &text);
279    }
280
281    pub fn update_test_window<R>(
282        &mut self,
283        window: AnyWindowHandle,
284        f: impl FnOnce(&mut TestWindow) -> R,
285    ) -> R {
286        window
287            .update(self, |_, cx| {
288                f(cx.window
289                    .platform_window
290                    .as_any_mut()
291                    .downcast_mut::<TestWindow>()
292                    .unwrap())
293            })
294            .unwrap()
295    }
296
297    pub fn notifications<T: 'static>(&mut self, entity: &Model<T>) -> impl Stream<Item = ()> {
298        let (tx, rx) = futures::channel::mpsc::unbounded();
299
300        entity.update(self, move |_, cx: &mut ModelContext<T>| {
301            cx.observe(entity, {
302                let tx = tx.clone();
303                move |_, _, _| {
304                    let _ = tx.unbounded_send(());
305                }
306            })
307            .detach();
308
309            cx.on_release(move |_, _| tx.close_channel()).detach();
310        });
311
312        rx
313    }
314
315    pub fn events<Evt, T: 'static + EventEmitter<Evt>>(
316        &mut self,
317        entity: &Model<T>,
318    ) -> futures::channel::mpsc::UnboundedReceiver<Evt>
319    where
320        Evt: 'static + Clone,
321    {
322        let (tx, rx) = futures::channel::mpsc::unbounded();
323        entity
324            .update(self, |_, cx: &mut ModelContext<T>| {
325                cx.subscribe(entity, move |_model, _handle, event, _cx| {
326                    let _ = tx.unbounded_send(event.clone());
327                })
328            })
329            .detach();
330        rx
331    }
332
333    pub async fn condition<T: 'static>(
334        &mut self,
335        model: &Model<T>,
336        mut predicate: impl FnMut(&mut T, &mut ModelContext<T>) -> bool,
337    ) {
338        let timer = self.executor().timer(Duration::from_secs(3));
339        let mut notifications = self.notifications(model);
340
341        use futures::FutureExt as _;
342        use smol::future::FutureExt as _;
343
344        async {
345            while notifications.next().await.is_some() {
346                if model.update(self, &mut predicate) {
347                    return Ok(());
348                }
349            }
350            bail!("model dropped")
351        }
352        .race(timer.map(|_| Err(anyhow!("condition timed out"))))
353        .await
354        .unwrap();
355    }
356}
357
358impl<T: Send> Model<T> {
359    pub fn next_event<Evt>(&self, cx: &mut TestAppContext) -> Evt
360    where
361        Evt: Send + Clone + 'static,
362        T: EventEmitter<Evt>,
363    {
364        let (tx, mut rx) = futures::channel::mpsc::unbounded();
365        let _subscription = self.update(cx, |_, cx| {
366            cx.subscribe(self, move |_, _, event, _| {
367                tx.unbounded_send(event.clone()).ok();
368            })
369        });
370
371        cx.executor().run_until_parked();
372        rx.try_next()
373            .expect("no event received")
374            .expect("model was dropped")
375    }
376}
377
378impl<V> View<V> {
379    pub fn condition<Evt>(
380        &self,
381        cx: &TestAppContext,
382        mut predicate: impl FnMut(&V, &AppContext) -> bool,
383    ) -> impl Future<Output = ()>
384    where
385        Evt: 'static,
386        V: EventEmitter<Evt>,
387    {
388        use postage::prelude::{Sink as _, Stream as _};
389
390        let (tx, mut rx) = postage::mpsc::channel(1024);
391        let timeout_duration = Duration::from_millis(100); //todo!() cx.condition_duration();
392
393        let mut cx = cx.app.borrow_mut();
394        let subscriptions = (
395            cx.observe(self, {
396                let mut tx = tx.clone();
397                move |_, _| {
398                    tx.blocking_send(()).ok();
399                }
400            }),
401            cx.subscribe(self, {
402                let mut tx = tx.clone();
403                move |_, _: &Evt, _| {
404                    tx.blocking_send(()).ok();
405                }
406            }),
407        );
408
409        let cx = cx.this.upgrade().unwrap();
410        let handle = self.downgrade();
411
412        async move {
413            crate::util::timeout(timeout_duration, async move {
414                loop {
415                    {
416                        let cx = cx.borrow();
417                        let cx = &*cx;
418                        if predicate(
419                            handle
420                                .upgrade()
421                                .expect("view dropped with pending condition")
422                                .read(cx),
423                            cx,
424                        ) {
425                            break;
426                        }
427                    }
428
429                    // todo!(start_waiting)
430                    // cx.borrow().foreground_executor().start_waiting();
431                    rx.recv()
432                        .await
433                        .expect("view dropped with pending condition");
434                    // cx.borrow().foreground_executor().finish_waiting();
435                }
436            })
437            .await
438            .expect("condition timed out");
439            drop(subscriptions);
440        }
441    }
442}
443
444use derive_more::{Deref, DerefMut};
445#[derive(Deref, DerefMut)]
446pub struct VisualTestContext<'a> {
447    #[deref]
448    #[deref_mut]
449    cx: &'a mut TestAppContext,
450    window: AnyWindowHandle,
451}
452
453impl<'a> VisualTestContext<'a> {
454    pub fn from_window(window: AnyWindowHandle, cx: &'a mut TestAppContext) -> Self {
455        Self { cx, window }
456    }
457
458    pub fn run_until_parked(&self) {
459        self.cx.background_executor.run_until_parked();
460    }
461
462    pub fn dispatch_action<A>(&mut self, action: A)
463    where
464        A: Action,
465    {
466        self.cx.dispatch_action(self.window, action)
467    }
468
469    pub fn simulate_keystrokes(&mut self, keystrokes: &str) {
470        self.cx.simulate_keystrokes(self.window, keystrokes)
471    }
472
473    pub fn simulate_input(&mut self, input: &str) {
474        self.cx.simulate_input(self.window, input)
475    }
476}
477
478impl<'a> Context for VisualTestContext<'a> {
479    type Result<T> = <TestAppContext as Context>::Result<T>;
480
481    fn build_model<T: 'static>(
482        &mut self,
483        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
484    ) -> Self::Result<Model<T>> {
485        self.cx.build_model(build_model)
486    }
487
488    fn update_model<T, R>(
489        &mut self,
490        handle: &Model<T>,
491        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
492    ) -> Self::Result<R>
493    where
494        T: 'static,
495    {
496        self.cx.update_model(handle, update)
497    }
498
499    fn read_model<T, R>(
500        &self,
501        handle: &Model<T>,
502        read: impl FnOnce(&T, &AppContext) -> R,
503    ) -> Self::Result<R>
504    where
505        T: 'static,
506    {
507        self.cx.read_model(handle, read)
508    }
509
510    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
511    where
512        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
513    {
514        self.cx.update_window(window, f)
515    }
516
517    fn read_window<T, R>(
518        &self,
519        window: &WindowHandle<T>,
520        read: impl FnOnce(View<T>, &AppContext) -> R,
521    ) -> Result<R>
522    where
523        T: 'static,
524    {
525        self.cx.read_window(window, read)
526    }
527}
528
529impl<'a> VisualContext for VisualTestContext<'a> {
530    fn build_view<V>(
531        &mut self,
532        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
533    ) -> Self::Result<View<V>>
534    where
535        V: 'static + Render,
536    {
537        self.window
538            .update(self.cx, |_, cx| cx.build_view(build_view))
539            .unwrap()
540    }
541
542    fn update_view<V: 'static, R>(
543        &mut self,
544        view: &View<V>,
545        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
546    ) -> Self::Result<R> {
547        self.window
548            .update(self.cx, |_, cx| cx.update_view(view, update))
549            .unwrap()
550    }
551
552    fn replace_root_view<V>(
553        &mut self,
554        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
555    ) -> Self::Result<View<V>>
556    where
557        V: Render,
558    {
559        self.window
560            .update(self.cx, |_, cx| cx.replace_root_view(build_view))
561            .unwrap()
562    }
563}
564
565impl AnyWindowHandle {
566    pub fn build_view<V: Render + 'static>(
567        &self,
568        cx: &mut TestAppContext,
569        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
570    ) -> View<V> {
571        self.update(cx, |_, cx| cx.build_view(build_view)).unwrap()
572    }
573}
574
575pub struct EmptyView {}
576
577impl Render for EmptyView {
578    type Element = Div<Self>;
579
580    fn render(&mut self, _cx: &mut crate::ViewContext<Self>) -> Self::Element {
581        div()
582    }
583}