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