1use crate::{
2 div, Action, AnyView, AnyWindowHandle, AppCell, AppContext, AsyncAppContext,
3 BackgroundExecutor, ClipboardItem, Context, Entity, EventEmitter, ForegroundExecutor,
4 IntoElement, Keystroke, Model, ModelContext, Pixels, Platform, Render, Result, Size, Task,
5 TestDispatcher, TestPlatform, TestWindow, TextSystem, View, ViewContext, VisualContext,
6 WindowContext, WindowHandle, WindowOptions,
7};
8use anyhow::{anyhow, bail};
9use futures::{Stream, StreamExt};
10use std::{future::Future, ops::Deref, rc::Rc, sync::Arc, time::Duration};
11
12#[derive(Clone)]
13pub struct TestAppContext {
14 pub app: Rc<AppCell>,
15 pub background_executor: BackgroundExecutor,
16 pub foreground_executor: ForegroundExecutor,
17 pub dispatcher: TestDispatcher,
18 pub test_platform: Rc<TestPlatform>,
19 text_system: Arc<TextSystem>,
20}
21
22impl Context for TestAppContext {
23 type Result<T> = T;
24
25 fn new_model<T: 'static>(
26 &mut self,
27 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
28 ) -> Self::Result<Model<T>>
29 where
30 T: 'static,
31 {
32 let mut app = self.app.borrow_mut();
33 app.new_model(build_model)
34 }
35
36 fn update_model<T: 'static, R>(
37 &mut self,
38 handle: &Model<T>,
39 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
40 ) -> Self::Result<R> {
41 let mut app = self.app.borrow_mut();
42 app.update_model(handle, update)
43 }
44
45 fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
46 where
47 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
48 {
49 let mut lock = self.app.borrow_mut();
50 lock.update_window(window, f)
51 }
52
53 fn read_model<T, R>(
54 &self,
55 handle: &Model<T>,
56 read: impl FnOnce(&T, &AppContext) -> R,
57 ) -> Self::Result<R>
58 where
59 T: 'static,
60 {
61 let app = self.app.borrow();
62 app.read_model(handle, read)
63 }
64
65 fn read_window<T, R>(
66 &self,
67 window: &WindowHandle<T>,
68 read: impl FnOnce(View<T>, &AppContext) -> R,
69 ) -> Result<R>
70 where
71 T: 'static,
72 {
73 let app = self.app.borrow();
74 app.read_window(window, read)
75 }
76}
77
78impl TestAppContext {
79 pub fn new(dispatcher: TestDispatcher) -> Self {
80 let arc_dispatcher = Arc::new(dispatcher.clone());
81 let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
82 let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
83 let platform = TestPlatform::new(background_executor.clone(), foreground_executor.clone());
84 let asset_source = Arc::new(());
85 let http_client = util::http::FakeHttpClient::with_404_response();
86 let text_system = Arc::new(TextSystem::new(platform.text_system()));
87
88 Self {
89 app: AppContext::new(platform.clone(), asset_source, http_client),
90 background_executor,
91 foreground_executor,
92 dispatcher: dispatcher.clone(),
93 test_platform: platform,
94 text_system,
95 }
96 }
97
98 pub fn new_app(&self) -> TestAppContext {
99 Self::new(self.dispatcher.clone())
100 }
101
102 pub fn quit(&self) {
103 self.app.borrow_mut().shutdown();
104 }
105
106 pub fn refresh(&mut self) -> Result<()> {
107 let mut app = self.app.borrow_mut();
108 app.refresh();
109 Ok(())
110 }
111
112 pub fn executor(&self) -> BackgroundExecutor {
113 self.background_executor.clone()
114 }
115
116 pub fn foreground_executor(&self) -> &ForegroundExecutor {
117 &self.foreground_executor
118 }
119
120 pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> R {
121 let mut cx = self.app.borrow_mut();
122 cx.update(f)
123 }
124
125 pub fn read<R>(&self, f: impl FnOnce(&AppContext) -> R) -> R {
126 let cx = self.app.borrow();
127 f(&*cx)
128 }
129
130 pub fn add_window<F, V>(&mut self, build_window: F) -> WindowHandle<V>
131 where
132 F: FnOnce(&mut ViewContext<V>) -> V,
133 V: 'static + Render,
134 {
135 let mut cx = self.app.borrow_mut();
136 cx.open_window(WindowOptions::default(), |cx| cx.new_view(build_window))
137 }
138
139 pub fn add_empty_window(&mut self) -> AnyWindowHandle {
140 let mut cx = self.app.borrow_mut();
141 cx.open_window(WindowOptions::default(), |cx| cx.new_view(|_| EmptyView {}))
142 .any_handle
143 }
144
145 pub fn add_window_view<F, V>(&mut self, build_window: F) -> (View<V>, &mut VisualTestContext)
146 where
147 F: FnOnce(&mut ViewContext<V>) -> V,
148 V: 'static + Render,
149 {
150 let mut cx = self.app.borrow_mut();
151 let window = cx.open_window(WindowOptions::default(), |cx| cx.new_view(build_window));
152 drop(cx);
153 let view = window.root_view(self).unwrap();
154 let cx = Box::new(VisualTestContext::from_window(*window.deref(), self));
155 // it might be nice to try and cleanup these at the end of each test.
156 (view, Box::leak(cx))
157 }
158
159 pub fn text_system(&self) -> &Arc<TextSystem> {
160 &self.text_system
161 }
162
163 pub fn write_to_clipboard(&self, item: ClipboardItem) {
164 self.test_platform.write_to_clipboard(item)
165 }
166
167 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
168 self.test_platform.read_from_clipboard()
169 }
170
171 pub fn simulate_new_path_selection(
172 &self,
173 select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
174 ) {
175 self.test_platform.simulate_new_path_selection(select_path);
176 }
177
178 pub fn simulate_prompt_answer(&self, button_ix: usize) {
179 self.test_platform.simulate_prompt_answer(button_ix);
180 }
181
182 pub fn has_pending_prompt(&self) -> bool {
183 self.test_platform.has_pending_prompt()
184 }
185
186 pub fn simulate_window_resize(&self, window_handle: AnyWindowHandle, size: Size<Pixels>) {
187 self.test_window(window_handle).simulate_resize(size);
188 }
189
190 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
191 where
192 Fut: Future<Output = R> + 'static,
193 R: 'static,
194 {
195 self.foreground_executor.spawn(f(self.to_async()))
196 }
197
198 pub fn has_global<G: 'static>(&self) -> bool {
199 let app = self.app.borrow();
200 app.has_global::<G>()
201 }
202
203 pub fn read_global<G: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> R {
204 let app = self.app.borrow();
205 read(app.global(), &app)
206 }
207
208 pub fn try_read_global<G: 'static, R>(
209 &self,
210 read: impl FnOnce(&G, &AppContext) -> R,
211 ) -> Option<R> {
212 let lock = self.app.borrow();
213 Some(read(lock.try_global()?, &lock))
214 }
215
216 pub fn set_global<G: 'static>(&mut self, global: G) {
217 let mut lock = self.app.borrow_mut();
218 lock.set_global(global);
219 }
220
221 pub fn update_global<G: 'static, R>(
222 &mut self,
223 update: impl FnOnce(&mut G, &mut AppContext) -> R,
224 ) -> R {
225 let mut lock = self.app.borrow_mut();
226 lock.update_global(update)
227 }
228
229 pub fn to_async(&self) -> AsyncAppContext {
230 AsyncAppContext {
231 app: Rc::downgrade(&self.app),
232 background_executor: self.background_executor.clone(),
233 foreground_executor: self.foreground_executor.clone(),
234 }
235 }
236
237 pub fn dispatch_action<A>(&mut self, window: AnyWindowHandle, action: A)
238 where
239 A: Action,
240 {
241 window
242 .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
243 .unwrap();
244
245 self.background_executor.run_until_parked()
246 }
247
248 /// simulate_keystrokes takes a space-separated list of keys to type.
249 /// cx.simulate_keystrokes("cmd-shift-p b k s p enter")
250 /// will run backspace on the current editor through the command palette.
251 pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
252 for keystroke in keystrokes
253 .split(" ")
254 .map(Keystroke::parse)
255 .map(Result::unwrap)
256 {
257 self.dispatch_keystroke(window, keystroke.into(), false);
258 }
259
260 self.background_executor.run_until_parked()
261 }
262
263 /// simulate_input takes a string of text to type.
264 /// cx.simulate_input("abc")
265 /// will type abc into your current editor.
266 pub fn simulate_input(&mut self, window: AnyWindowHandle, input: &str) {
267 for keystroke in input.split("").map(Keystroke::parse).map(Result::unwrap) {
268 self.dispatch_keystroke(window, keystroke.into(), false);
269 }
270
271 self.background_executor.run_until_parked()
272 }
273
274 pub fn dispatch_keystroke(
275 &mut self,
276 window: AnyWindowHandle,
277 keystroke: Keystroke,
278 is_held: bool,
279 ) {
280 self.test_window(window)
281 .simulate_keystroke(keystroke, is_held)
282 }
283
284 pub fn test_window(&self, window: AnyWindowHandle) -> TestWindow {
285 self.app
286 .borrow_mut()
287 .windows
288 .get_mut(window.id)
289 .unwrap()
290 .as_mut()
291 .unwrap()
292 .platform_window
293 .as_test()
294 .unwrap()
295 .clone()
296 }
297
298 pub fn notifications<T: 'static>(&mut self, entity: &impl Entity<T>) -> impl Stream<Item = ()> {
299 let (tx, rx) = futures::channel::mpsc::unbounded();
300 self.update(|cx| {
301 cx.observe(entity, {
302 let tx = tx.clone();
303 move |_, _| {
304 let _ = tx.unbounded_send(());
305 }
306 })
307 .detach();
308 cx.observe_release(entity, move |_, _| tx.close_channel())
309 .detach()
310 });
311 rx
312 }
313
314 pub fn events<Evt, T: 'static + EventEmitter<Evt>>(
315 &mut self,
316 entity: &Model<T>,
317 ) -> futures::channel::mpsc::UnboundedReceiver<Evt>
318 where
319 Evt: 'static + Clone,
320 {
321 let (tx, rx) = futures::channel::mpsc::unbounded();
322 entity
323 .update(self, |_, cx: &mut ModelContext<T>| {
324 cx.subscribe(entity, move |_model, _handle, event, _cx| {
325 let _ = tx.unbounded_send(event.clone());
326 })
327 })
328 .detach();
329 rx
330 }
331
332 pub async fn condition<T: 'static>(
333 &mut self,
334 model: &Model<T>,
335 mut predicate: impl FnMut(&mut T, &mut ModelContext<T>) -> bool,
336 ) {
337 let timer = self.executor().timer(Duration::from_secs(3));
338 let mut notifications = self.notifications(model);
339
340 use futures::FutureExt as _;
341 use smol::future::FutureExt as _;
342
343 async {
344 loop {
345 if model.update(self, &mut predicate) {
346 return Ok(());
347 }
348
349 if notifications.next().await.is_none() {
350 bail!("model dropped")
351 }
352 }
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: 'static> View<V> {
390 pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
391 use postage::prelude::{Sink as _, Stream as _};
392
393 let (mut tx, mut rx) = postage::mpsc::channel(1);
394 let mut cx = cx.app.app.borrow_mut();
395 let subscription = cx.observe(self, move |_, _| {
396 tx.try_send(()).ok();
397 });
398
399 let duration = if std::env::var("CI").is_ok() {
400 Duration::from_secs(5)
401 } else {
402 Duration::from_secs(1)
403 };
404
405 async move {
406 let notification = crate::util::timeout(duration, rx.recv())
407 .await
408 .expect("next notification timed out");
409 drop(subscription);
410 notification.expect("model dropped while test was waiting for its next notification")
411 }
412 }
413}
414
415impl<V> View<V> {
416 pub fn condition<Evt>(
417 &self,
418 cx: &TestAppContext,
419 mut predicate: impl FnMut(&V, &AppContext) -> bool,
420 ) -> impl Future<Output = ()>
421 where
422 Evt: 'static,
423 V: EventEmitter<Evt>,
424 {
425 use postage::prelude::{Sink as _, Stream as _};
426
427 let (tx, mut rx) = postage::mpsc::channel(1024);
428 let timeout_duration = Duration::from_millis(100); //todo!() cx.condition_duration();
429
430 let mut cx = cx.app.borrow_mut();
431 let subscriptions = (
432 cx.observe(self, {
433 let mut tx = tx.clone();
434 move |_, _| {
435 tx.blocking_send(()).ok();
436 }
437 }),
438 cx.subscribe(self, {
439 let mut tx = tx.clone();
440 move |_, _: &Evt, _| {
441 tx.blocking_send(()).ok();
442 }
443 }),
444 );
445
446 let cx = cx.this.upgrade().unwrap();
447 let handle = self.downgrade();
448
449 async move {
450 crate::util::timeout(timeout_duration, async move {
451 loop {
452 {
453 let cx = cx.borrow();
454 let cx = &*cx;
455 if predicate(
456 handle
457 .upgrade()
458 .expect("view dropped with pending condition")
459 .read(cx),
460 cx,
461 ) {
462 break;
463 }
464 }
465
466 // todo!(start_waiting)
467 // cx.borrow().foreground_executor().start_waiting();
468 rx.recv()
469 .await
470 .expect("view dropped with pending condition");
471 // cx.borrow().foreground_executor().finish_waiting();
472 }
473 })
474 .await
475 .expect("condition timed out");
476 drop(subscriptions);
477 }
478 }
479}
480
481use derive_more::{Deref, DerefMut};
482#[derive(Deref, DerefMut)]
483pub struct VisualTestContext<'a> {
484 #[deref]
485 #[deref_mut]
486 cx: &'a mut TestAppContext,
487 window: AnyWindowHandle,
488}
489
490impl<'a> VisualTestContext<'a> {
491 pub fn update<R>(&mut self, f: impl FnOnce(&mut WindowContext) -> R) -> R {
492 self.cx.update_window(self.window, |_, cx| f(cx)).unwrap()
493 }
494
495 pub fn from_window(window: AnyWindowHandle, cx: &'a mut TestAppContext) -> Self {
496 Self { cx, window }
497 }
498
499 pub fn run_until_parked(&self) {
500 self.cx.background_executor.run_until_parked();
501 }
502
503 pub fn dispatch_action<A>(&mut self, action: A)
504 where
505 A: Action,
506 {
507 self.cx.dispatch_action(self.window, action)
508 }
509
510 pub fn window_title(&mut self) -> Option<String> {
511 self.cx.test_window(self.window).0.lock().title.clone()
512 }
513
514 pub fn simulate_keystrokes(&mut self, keystrokes: &str) {
515 self.cx.simulate_keystrokes(self.window, keystrokes)
516 }
517
518 pub fn simulate_input(&mut self, input: &str) {
519 self.cx.simulate_input(self.window, input)
520 }
521
522 pub fn simulate_activation(&mut self) {
523 self.cx
524 .test_window(self.window)
525 .simulate_active_status_change(true)
526 }
527
528 pub fn simulate_deactivation(&mut self) {
529 self.cx
530 .test_window(self.window)
531 .simulate_active_status_change(false)
532 }
533}
534
535impl<'a> Context for VisualTestContext<'a> {
536 type Result<T> = <TestAppContext as Context>::Result<T>;
537
538 fn new_model<T: 'static>(
539 &mut self,
540 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
541 ) -> Self::Result<Model<T>> {
542 self.cx.new_model(build_model)
543 }
544
545 fn update_model<T, R>(
546 &mut self,
547 handle: &Model<T>,
548 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
549 ) -> Self::Result<R>
550 where
551 T: 'static,
552 {
553 self.cx.update_model(handle, update)
554 }
555
556 fn read_model<T, R>(
557 &self,
558 handle: &Model<T>,
559 read: impl FnOnce(&T, &AppContext) -> R,
560 ) -> Self::Result<R>
561 where
562 T: 'static,
563 {
564 self.cx.read_model(handle, read)
565 }
566
567 fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
568 where
569 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
570 {
571 self.cx.update_window(window, f)
572 }
573
574 fn read_window<T, R>(
575 &self,
576 window: &WindowHandle<T>,
577 read: impl FnOnce(View<T>, &AppContext) -> R,
578 ) -> Result<R>
579 where
580 T: 'static,
581 {
582 self.cx.read_window(window, read)
583 }
584}
585
586impl<'a> VisualContext for VisualTestContext<'a> {
587 fn new_view<V>(
588 &mut self,
589 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
590 ) -> Self::Result<View<V>>
591 where
592 V: 'static + Render,
593 {
594 self.window
595 .update(self.cx, |_, cx| cx.new_view(build_view))
596 .unwrap()
597 }
598
599 fn update_view<V: 'static, R>(
600 &mut self,
601 view: &View<V>,
602 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
603 ) -> Self::Result<R> {
604 self.window
605 .update(self.cx, |_, cx| cx.update_view(view, update))
606 .unwrap()
607 }
608
609 fn replace_root_view<V>(
610 &mut self,
611 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
612 ) -> Self::Result<View<V>>
613 where
614 V: 'static + Render,
615 {
616 self.window
617 .update(self.cx, |_, cx| cx.replace_root_view(build_view))
618 .unwrap()
619 }
620
621 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
622 self.window
623 .update(self.cx, |_, cx| {
624 view.read(cx).focus_handle(cx).clone().focus(cx)
625 })
626 .unwrap()
627 }
628
629 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
630 where
631 V: crate::ManagedView,
632 {
633 self.window
634 .update(self.cx, |_, cx| {
635 view.update(cx, |_, cx| cx.emit(crate::DismissEvent))
636 })
637 .unwrap()
638 }
639}
640
641impl AnyWindowHandle {
642 pub fn build_view<V: Render + 'static>(
643 &self,
644 cx: &mut TestAppContext,
645 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
646 ) -> View<V> {
647 self.update(cx, |_, cx| cx.new_view(build_view)).unwrap()
648 }
649}
650
651pub struct EmptyView {}
652
653impl Render for EmptyView {
654 fn render(&mut self, _cx: &mut crate::ViewContext<Self>) -> impl IntoElement {
655 div()
656 }
657}