test_context.rs

  1use crate::{
  2    div, AnyView, AnyWindowHandle, AppCell, AppContext, AsyncAppContext, BackgroundExecutor,
  3    Context, Div, EventEmitter, ForegroundExecutor, InputEvent, KeyDownEvent, Keystroke, Model,
  4    ModelContext, Render, Result, Task, TestDispatcher, TestPlatform, View, ViewContext,
  5    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}
 18
 19impl Context for TestAppContext {
 20    type Result<T> = T;
 21
 22    fn build_model<T: 'static>(
 23        &mut self,
 24        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
 25    ) -> Self::Result<Model<T>>
 26    where
 27        T: 'static,
 28    {
 29        let mut app = self.app.borrow_mut();
 30        app.build_model(build_model)
 31    }
 32
 33    fn update_model<T: 'static, R>(
 34        &mut self,
 35        handle: &Model<T>,
 36        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
 37    ) -> Self::Result<R> {
 38        let mut app = self.app.borrow_mut();
 39        app.update_model(handle, update)
 40    }
 41
 42    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
 43    where
 44        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
 45    {
 46        let mut lock = self.app.borrow_mut();
 47        lock.update_window(window, f)
 48    }
 49
 50    fn read_model<T, R>(
 51        &self,
 52        handle: &Model<T>,
 53        read: impl FnOnce(&T, &AppContext) -> R,
 54    ) -> Self::Result<R>
 55    where
 56        T: 'static,
 57    {
 58        let app = self.app.borrow();
 59        app.read_model(handle, read)
 60    }
 61
 62    fn read_window<T, R>(
 63        &self,
 64        window: &WindowHandle<T>,
 65        read: impl FnOnce(View<T>, &AppContext) -> R,
 66    ) -> Result<R>
 67    where
 68        T: 'static,
 69    {
 70        let app = self.app.borrow();
 71        app.read_window(window, read)
 72    }
 73}
 74
 75impl TestAppContext {
 76    pub fn new(dispatcher: TestDispatcher) -> Self {
 77        let arc_dispatcher = Arc::new(dispatcher.clone());
 78        let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
 79        let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
 80        let platform = Rc::new(TestPlatform::new(
 81            background_executor.clone(),
 82            foreground_executor.clone(),
 83        ));
 84        let asset_source = Arc::new(());
 85        let http_client = util::http::FakeHttpClient::with_404_response();
 86        Self {
 87            app: AppContext::new(platform, asset_source, http_client),
 88            background_executor,
 89            foreground_executor,
 90            dispatcher: dispatcher.clone(),
 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().quit();
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 spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
156    where
157        Fut: Future<Output = R> + 'static,
158        R: 'static,
159    {
160        self.foreground_executor.spawn(f(self.to_async()))
161    }
162
163    pub fn has_global<G: 'static>(&self) -> bool {
164        let app = self.app.borrow();
165        app.has_global::<G>()
166    }
167
168    pub fn read_global<G: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> R {
169        let app = self.app.borrow();
170        read(app.global(), &app)
171    }
172
173    pub fn try_read_global<G: 'static, R>(
174        &self,
175        read: impl FnOnce(&G, &AppContext) -> R,
176    ) -> Option<R> {
177        let lock = self.app.borrow();
178        Some(read(lock.try_global()?, &lock))
179    }
180
181    pub fn set_global<G: 'static>(&mut self, global: G) {
182        let mut lock = self.app.borrow_mut();
183        lock.set_global(global);
184    }
185
186    pub fn update_global<G: 'static, R>(
187        &mut self,
188        update: impl FnOnce(&mut G, &mut AppContext) -> R,
189    ) -> R {
190        let mut lock = self.app.borrow_mut();
191        lock.update_global(update)
192    }
193
194    pub fn to_async(&self) -> AsyncAppContext {
195        AsyncAppContext {
196            app: Rc::downgrade(&self.app),
197            background_executor: self.background_executor.clone(),
198            foreground_executor: self.foreground_executor.clone(),
199        }
200    }
201
202    pub fn dispatch_keystroke(
203        &mut self,
204        window: AnyWindowHandle,
205        keystroke: Keystroke,
206        is_held: bool,
207    ) {
208        let handled = window
209            .update(self, |_, cx| {
210                cx.dispatch_event(InputEvent::KeyDown(KeyDownEvent { keystroke, is_held }))
211            })
212            .is_ok_and(|handled| handled);
213
214        if !handled {
215            // todo!() simluate input here
216        }
217    }
218
219    pub fn notifications<T: 'static>(&mut self, entity: &Model<T>) -> impl Stream<Item = ()> {
220        let (tx, rx) = futures::channel::mpsc::unbounded();
221
222        entity.update(self, move |_, cx: &mut ModelContext<T>| {
223            cx.observe(entity, {
224                let tx = tx.clone();
225                move |_, _, _| {
226                    let _ = tx.unbounded_send(());
227                }
228            })
229            .detach();
230
231            cx.on_release(move |_, _| tx.close_channel()).detach();
232        });
233
234        rx
235    }
236
237    pub fn events<Evt, T: 'static + EventEmitter<Evt>>(
238        &mut self,
239        entity: &Model<T>,
240    ) -> futures::channel::mpsc::UnboundedReceiver<Evt>
241    where
242        Evt: 'static + Clone,
243    {
244        let (tx, rx) = futures::channel::mpsc::unbounded();
245        entity
246            .update(self, |_, cx: &mut ModelContext<T>| {
247                cx.subscribe(entity, move |_model, _handle, event, _cx| {
248                    let _ = tx.unbounded_send(event.clone());
249                })
250            })
251            .detach();
252        rx
253    }
254
255    pub async fn condition<T: 'static>(
256        &mut self,
257        model: &Model<T>,
258        mut predicate: impl FnMut(&mut T, &mut ModelContext<T>) -> bool,
259    ) {
260        let timer = self.executor().timer(Duration::from_secs(3));
261        let mut notifications = self.notifications(model);
262
263        use futures::FutureExt as _;
264        use smol::future::FutureExt as _;
265
266        async {
267            while notifications.next().await.is_some() {
268                if model.update(self, &mut predicate) {
269                    return Ok(());
270                }
271            }
272            bail!("model dropped")
273        }
274        .race(timer.map(|_| Err(anyhow!("condition timed out"))))
275        .await
276        .unwrap();
277    }
278}
279
280impl<T: Send> Model<T> {
281    pub fn next_event<Evt>(&self, cx: &mut TestAppContext) -> Evt
282    where
283        Evt: Send + Clone + 'static,
284        T: EventEmitter<Evt>,
285    {
286        let (tx, mut rx) = futures::channel::mpsc::unbounded();
287        let _subscription = self.update(cx, |_, cx| {
288            cx.subscribe(self, move |_, _, event, _| {
289                tx.unbounded_send(event.clone()).ok();
290            })
291        });
292
293        cx.executor().run_until_parked();
294        rx.try_next()
295            .expect("no event received")
296            .expect("model was dropped")
297    }
298}
299
300impl<V> View<V> {
301    pub fn condition<Evt>(
302        &self,
303        cx: &TestAppContext,
304        mut predicate: impl FnMut(&V, &AppContext) -> bool,
305    ) -> impl Future<Output = ()>
306    where
307        Evt: 'static,
308        V: EventEmitter<Evt>,
309    {
310        use postage::prelude::{Sink as _, Stream as _};
311
312        let (tx, mut rx) = postage::mpsc::channel(1024);
313        let timeout_duration = Duration::from_millis(100); //todo!() cx.condition_duration();
314
315        let mut cx = cx.app.borrow_mut();
316        let subscriptions = (
317            cx.observe(self, {
318                let mut tx = tx.clone();
319                move |_, _| {
320                    tx.blocking_send(()).ok();
321                }
322            }),
323            cx.subscribe(self, {
324                let mut tx = tx.clone();
325                move |_, _: &Evt, _| {
326                    tx.blocking_send(()).ok();
327                }
328            }),
329        );
330
331        let cx = cx.this.upgrade().unwrap();
332        let handle = self.downgrade();
333
334        async move {
335            crate::util::timeout(timeout_duration, async move {
336                loop {
337                    {
338                        let cx = cx.borrow();
339                        let cx = &*cx;
340                        if predicate(
341                            handle
342                                .upgrade()
343                                .expect("view dropped with pending condition")
344                                .read(cx),
345                            cx,
346                        ) {
347                            break;
348                        }
349                    }
350
351                    // todo!(start_waiting)
352                    // cx.borrow().foreground_executor().start_waiting();
353                    rx.recv()
354                        .await
355                        .expect("view dropped with pending condition");
356                    // cx.borrow().foreground_executor().finish_waiting();
357                }
358            })
359            .await
360            .expect("condition timed out");
361            drop(subscriptions);
362        }
363    }
364}
365
366use derive_more::{Deref, DerefMut};
367#[derive(Deref, DerefMut)]
368pub struct VisualTestContext<'a> {
369    #[deref]
370    #[deref_mut]
371    cx: &'a mut TestAppContext,
372    window: AnyWindowHandle,
373}
374
375impl<'a> VisualTestContext<'a> {
376    pub fn from_window(window: AnyWindowHandle, cx: &'a mut TestAppContext) -> Self {
377        Self { cx, window }
378    }
379}
380
381impl<'a> Context for VisualTestContext<'a> {
382    type Result<T> = <TestAppContext as Context>::Result<T>;
383
384    fn build_model<T: 'static>(
385        &mut self,
386        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
387    ) -> Self::Result<Model<T>> {
388        self.cx.build_model(build_model)
389    }
390
391    fn update_model<T, R>(
392        &mut self,
393        handle: &Model<T>,
394        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
395    ) -> Self::Result<R>
396    where
397        T: 'static,
398    {
399        self.cx.update_model(handle, update)
400    }
401
402    fn read_model<T, R>(
403        &self,
404        handle: &Model<T>,
405        read: impl FnOnce(&T, &AppContext) -> R,
406    ) -> Self::Result<R>
407    where
408        T: 'static,
409    {
410        self.cx.read_model(handle, read)
411    }
412
413    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
414    where
415        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
416    {
417        self.cx.update_window(window, f)
418    }
419
420    fn read_window<T, R>(
421        &self,
422        window: &WindowHandle<T>,
423        read: impl FnOnce(View<T>, &AppContext) -> R,
424    ) -> Result<R>
425    where
426        T: 'static,
427    {
428        self.cx.read_window(window, read)
429    }
430}
431
432impl<'a> VisualContext for VisualTestContext<'a> {
433    fn build_view<V>(
434        &mut self,
435        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
436    ) -> Self::Result<View<V>>
437    where
438        V: 'static + Render,
439    {
440        self.window
441            .update(self.cx, |_, cx| cx.build_view(build_view))
442            .unwrap()
443    }
444
445    fn update_view<V: 'static, R>(
446        &mut self,
447        view: &View<V>,
448        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
449    ) -> Self::Result<R> {
450        self.window
451            .update(self.cx, |_, cx| cx.update_view(view, update))
452            .unwrap()
453    }
454
455    fn replace_root_view<V>(
456        &mut self,
457        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
458    ) -> Self::Result<View<V>>
459    where
460        V: Render,
461    {
462        self.window
463            .update(self.cx, |_, cx| cx.replace_root_view(build_view))
464            .unwrap()
465    }
466}
467
468impl AnyWindowHandle {
469    pub fn build_view<V: Render + 'static>(
470        &self,
471        cx: &mut TestAppContext,
472        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
473    ) -> View<V> {
474        self.update(cx, |_, cx| cx.build_view(build_view)).unwrap()
475    }
476}
477
478pub struct EmptyView {}
479
480impl Render for EmptyView {
481    type Element = Div<Self>;
482
483    fn render(&mut self, _cx: &mut crate::ViewContext<Self>) -> Self::Element {
484        div()
485    }
486}