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    pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
229        for keystroke in keystrokes
230            .split(" ")
231            .map(Keystroke::parse)
232            .map(Result::unwrap)
233        {
234            self.dispatch_keystroke(window, keystroke.into(), false);
235        }
236
237        self.background_executor.run_until_parked()
238    }
239
240    pub fn dispatch_keystroke(
241        &mut self,
242        window: AnyWindowHandle,
243        keystroke: Keystroke,
244        is_held: bool,
245    ) {
246        let keystroke2 = keystroke.clone();
247        let handled = window
248            .update(self, |_, cx| {
249                cx.dispatch_event(InputEvent::KeyDown(KeyDownEvent { keystroke, is_held }))
250            })
251            .is_ok_and(|handled| handled);
252        if handled {
253            return;
254        }
255
256        let input_handler = self.update_test_window(window, |window| window.input_handler.clone());
257        let Some(input_handler) = input_handler else {
258            panic!(
259                "dispatch_keystroke {:?} failed to dispatch action or input",
260                &keystroke2
261            );
262        };
263        let text = keystroke2.ime_key.unwrap_or(keystroke2.key);
264        input_handler.lock().replace_text_in_range(None, &text);
265    }
266
267    pub fn update_test_window<R>(
268        &mut self,
269        window: AnyWindowHandle,
270        f: impl FnOnce(&mut TestWindow) -> R,
271    ) -> R {
272        window
273            .update(self, |_, cx| {
274                f(cx.window
275                    .platform_window
276                    .as_any_mut()
277                    .downcast_mut::<TestWindow>()
278                    .unwrap())
279            })
280            .unwrap()
281    }
282
283    pub fn notifications<T: 'static>(&mut self, entity: &Model<T>) -> impl Stream<Item = ()> {
284        let (tx, rx) = futures::channel::mpsc::unbounded();
285
286        entity.update(self, move |_, cx: &mut ModelContext<T>| {
287            cx.observe(entity, {
288                let tx = tx.clone();
289                move |_, _, _| {
290                    let _ = tx.unbounded_send(());
291                }
292            })
293            .detach();
294
295            cx.on_release(move |_, _| tx.close_channel()).detach();
296        });
297
298        rx
299    }
300
301    pub fn events<Evt, T: 'static + EventEmitter<Evt>>(
302        &mut self,
303        entity: &Model<T>,
304    ) -> futures::channel::mpsc::UnboundedReceiver<Evt>
305    where
306        Evt: 'static + Clone,
307    {
308        let (tx, rx) = futures::channel::mpsc::unbounded();
309        entity
310            .update(self, |_, cx: &mut ModelContext<T>| {
311                cx.subscribe(entity, move |_model, _handle, event, _cx| {
312                    let _ = tx.unbounded_send(event.clone());
313                })
314            })
315            .detach();
316        rx
317    }
318
319    pub async fn condition<T: 'static>(
320        &mut self,
321        model: &Model<T>,
322        mut predicate: impl FnMut(&mut T, &mut ModelContext<T>) -> bool,
323    ) {
324        let timer = self.executor().timer(Duration::from_secs(3));
325        let mut notifications = self.notifications(model);
326
327        use futures::FutureExt as _;
328        use smol::future::FutureExt as _;
329
330        async {
331            while notifications.next().await.is_some() {
332                if model.update(self, &mut predicate) {
333                    return Ok(());
334                }
335            }
336            bail!("model dropped")
337        }
338        .race(timer.map(|_| Err(anyhow!("condition timed out"))))
339        .await
340        .unwrap();
341    }
342}
343
344impl<T: Send> Model<T> {
345    pub fn next_event<Evt>(&self, cx: &mut TestAppContext) -> Evt
346    where
347        Evt: Send + Clone + 'static,
348        T: EventEmitter<Evt>,
349    {
350        let (tx, mut rx) = futures::channel::mpsc::unbounded();
351        let _subscription = self.update(cx, |_, cx| {
352            cx.subscribe(self, move |_, _, event, _| {
353                tx.unbounded_send(event.clone()).ok();
354            })
355        });
356
357        cx.executor().run_until_parked();
358        rx.try_next()
359            .expect("no event received")
360            .expect("model was dropped")
361    }
362}
363
364impl<V> View<V> {
365    pub fn condition<Evt>(
366        &self,
367        cx: &TestAppContext,
368        mut predicate: impl FnMut(&V, &AppContext) -> bool,
369    ) -> impl Future<Output = ()>
370    where
371        Evt: 'static,
372        V: EventEmitter<Evt>,
373    {
374        use postage::prelude::{Sink as _, Stream as _};
375
376        let (tx, mut rx) = postage::mpsc::channel(1024);
377        let timeout_duration = Duration::from_millis(100); //todo!() cx.condition_duration();
378
379        let mut cx = cx.app.borrow_mut();
380        let subscriptions = (
381            cx.observe(self, {
382                let mut tx = tx.clone();
383                move |_, _| {
384                    tx.blocking_send(()).ok();
385                }
386            }),
387            cx.subscribe(self, {
388                let mut tx = tx.clone();
389                move |_, _: &Evt, _| {
390                    tx.blocking_send(()).ok();
391                }
392            }),
393        );
394
395        let cx = cx.this.upgrade().unwrap();
396        let handle = self.downgrade();
397
398        async move {
399            crate::util::timeout(timeout_duration, async move {
400                loop {
401                    {
402                        let cx = cx.borrow();
403                        let cx = &*cx;
404                        if predicate(
405                            handle
406                                .upgrade()
407                                .expect("view dropped with pending condition")
408                                .read(cx),
409                            cx,
410                        ) {
411                            break;
412                        }
413                    }
414
415                    // todo!(start_waiting)
416                    // cx.borrow().foreground_executor().start_waiting();
417                    rx.recv()
418                        .await
419                        .expect("view dropped with pending condition");
420                    // cx.borrow().foreground_executor().finish_waiting();
421                }
422            })
423            .await
424            .expect("condition timed out");
425            drop(subscriptions);
426        }
427    }
428}
429
430use derive_more::{Deref, DerefMut};
431#[derive(Deref, DerefMut)]
432pub struct VisualTestContext<'a> {
433    #[deref]
434    #[deref_mut]
435    cx: &'a mut TestAppContext,
436    window: AnyWindowHandle,
437}
438
439impl<'a> VisualTestContext<'a> {
440    pub fn from_window(window: AnyWindowHandle, cx: &'a mut TestAppContext) -> Self {
441        Self { cx, window }
442    }
443
444    pub fn run_until_parked(&self) {
445        self.cx.background_executor.run_until_parked();
446    }
447
448    pub fn dispatch_action<A>(&mut self, action: A)
449    where
450        A: Action,
451    {
452        self.cx.dispatch_action(self.window, action)
453    }
454
455    pub fn simulate_keystrokes(&mut self, keystrokes: &str) {
456        self.cx.simulate_keystrokes(self.window, keystrokes)
457    }
458}
459
460impl<'a> Context for VisualTestContext<'a> {
461    type Result<T> = <TestAppContext as Context>::Result<T>;
462
463    fn build_model<T: 'static>(
464        &mut self,
465        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
466    ) -> Self::Result<Model<T>> {
467        self.cx.build_model(build_model)
468    }
469
470    fn update_model<T, R>(
471        &mut self,
472        handle: &Model<T>,
473        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
474    ) -> Self::Result<R>
475    where
476        T: 'static,
477    {
478        self.cx.update_model(handle, update)
479    }
480
481    fn read_model<T, R>(
482        &self,
483        handle: &Model<T>,
484        read: impl FnOnce(&T, &AppContext) -> R,
485    ) -> Self::Result<R>
486    where
487        T: 'static,
488    {
489        self.cx.read_model(handle, read)
490    }
491
492    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
493    where
494        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
495    {
496        self.cx.update_window(window, f)
497    }
498
499    fn read_window<T, R>(
500        &self,
501        window: &WindowHandle<T>,
502        read: impl FnOnce(View<T>, &AppContext) -> R,
503    ) -> Result<R>
504    where
505        T: 'static,
506    {
507        self.cx.read_window(window, read)
508    }
509}
510
511impl<'a> VisualContext for VisualTestContext<'a> {
512    fn build_view<V>(
513        &mut self,
514        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
515    ) -> Self::Result<View<V>>
516    where
517        V: 'static + Render,
518    {
519        self.window
520            .update(self.cx, |_, cx| cx.build_view(build_view))
521            .unwrap()
522    }
523
524    fn update_view<V: 'static, R>(
525        &mut self,
526        view: &View<V>,
527        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
528    ) -> Self::Result<R> {
529        self.window
530            .update(self.cx, |_, cx| cx.update_view(view, update))
531            .unwrap()
532    }
533
534    fn replace_root_view<V>(
535        &mut self,
536        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
537    ) -> Self::Result<View<V>>
538    where
539        V: Render,
540    {
541        self.window
542            .update(self.cx, |_, cx| cx.replace_root_view(build_view))
543            .unwrap()
544    }
545}
546
547impl AnyWindowHandle {
548    pub fn build_view<V: Render + 'static>(
549        &self,
550        cx: &mut TestAppContext,
551        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
552    ) -> View<V> {
553        self.update(cx, |_, cx| cx.build_view(build_view)).unwrap()
554    }
555}
556
557pub struct EmptyView {}
558
559impl Render for EmptyView {
560    type Element = Div<Self>;
561
562    fn render(&mut self, _cx: &mut crate::ViewContext<Self>) -> Self::Element {
563        div()
564    }
565}