1use crate::{
2 Action, AnyView, AnyWindowHandle, AppCell, AppContext, AsyncAppContext, AvailableSpace,
3 BackgroundExecutor, BorrowAppContext, Bounds, ClipboardItem, Context, DrawPhase, Drawable,
4 Element, Empty, Entity, EventEmitter, ForegroundExecutor, Global, InputEvent, Keystroke, Model,
5 ModelContext, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent,
6 MouseUpEvent, Pixels, Platform, Point, Render, Result, Size, Task, TestDispatcher,
7 TestPlatform, TestWindow, TextSystem, View, ViewContext, VisualContext, WindowBounds,
8 WindowContext, WindowHandle, WindowOptions,
9};
10use anyhow::{anyhow, bail};
11use futures::{channel::oneshot, Stream, StreamExt};
12use std::{cell::RefCell, future::Future, ops::Deref, rc::Rc, sync::Arc, time::Duration};
13
14/// A TestAppContext is provided to tests created with `#[gpui::test]`, it provides
15/// an implementation of `Context` with additional methods that are useful in tests.
16#[derive(Clone)]
17pub struct TestAppContext {
18 #[doc(hidden)]
19 pub app: Rc<AppCell>,
20 #[doc(hidden)]
21 pub background_executor: BackgroundExecutor,
22 #[doc(hidden)]
23 pub foreground_executor: ForegroundExecutor,
24 #[doc(hidden)]
25 pub dispatcher: TestDispatcher,
26 test_platform: Rc<TestPlatform>,
27 text_system: Arc<TextSystem>,
28 fn_name: Option<&'static str>,
29 on_quit: Rc<RefCell<Vec<Box<dyn FnOnce() + 'static>>>>,
30}
31
32impl Context for TestAppContext {
33 type Result<T> = T;
34
35 fn new_model<T: 'static>(
36 &mut self,
37 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
38 ) -> Self::Result<Model<T>> {
39 let mut app = self.app.borrow_mut();
40 app.new_model(build_model)
41 }
42
43 fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
44 let mut app = self.app.borrow_mut();
45 app.reserve_model()
46 }
47
48 fn insert_model<T: 'static>(
49 &mut self,
50 reservation: crate::Reservation<T>,
51 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
52 ) -> Self::Result<Model<T>> {
53 let mut app = self.app.borrow_mut();
54 app.insert_model(reservation, build_model)
55 }
56
57 fn update_model<T: 'static, R>(
58 &mut self,
59 handle: &Model<T>,
60 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
61 ) -> Self::Result<R> {
62 let mut app = self.app.borrow_mut();
63 app.update_model(handle, update)
64 }
65
66 fn read_model<T, R>(
67 &self,
68 handle: &Model<T>,
69 read: impl FnOnce(&T, &AppContext) -> R,
70 ) -> Self::Result<R>
71 where
72 T: 'static,
73 {
74 let app = self.app.borrow();
75 app.read_model(handle, read)
76 }
77
78 fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
79 where
80 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
81 {
82 let mut lock = self.app.borrow_mut();
83 lock.update_window(window, f)
84 }
85
86 fn read_window<T, R>(
87 &self,
88 window: &WindowHandle<T>,
89 read: impl FnOnce(View<T>, &AppContext) -> R,
90 ) -> Result<R>
91 where
92 T: 'static,
93 {
94 let app = self.app.borrow();
95 app.read_window(window, read)
96 }
97}
98
99impl TestAppContext {
100 /// Creates a new `TestAppContext`. Usually you can rely on `#[gpui::test]` to do this for you.
101 pub fn new(dispatcher: TestDispatcher, fn_name: Option<&'static str>) -> Self {
102 let arc_dispatcher = Arc::new(dispatcher.clone());
103 let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
104 let foreground_executor = ForegroundExecutor::new(arc_dispatcher);
105 let platform = TestPlatform::new(background_executor.clone(), foreground_executor.clone());
106 let asset_source = Arc::new(());
107 let http_client = http::FakeHttpClient::with_404_response();
108 let text_system = Arc::new(TextSystem::new(platform.text_system()));
109
110 Self {
111 app: AppContext::new(platform.clone(), asset_source, http_client),
112 background_executor,
113 foreground_executor,
114 dispatcher: dispatcher.clone(),
115 test_platform: platform,
116 text_system,
117 fn_name,
118 on_quit: Rc::new(RefCell::new(Vec::default())),
119 }
120 }
121
122 /// The name of the test function that created this `TestAppContext`
123 pub fn test_function_name(&self) -> Option<&'static str> {
124 self.fn_name
125 }
126
127 /// Checks whether there have been any new path prompts received by the platform.
128 pub fn did_prompt_for_new_path(&self) -> bool {
129 self.test_platform.did_prompt_for_new_path()
130 }
131
132 /// returns a new `TestAppContext` re-using the same executors to interleave tasks.
133 pub fn new_app(&self) -> TestAppContext {
134 Self::new(self.dispatcher.clone(), self.fn_name)
135 }
136
137 /// Called by the test helper to end the test.
138 /// public so the macro can call it.
139 pub fn quit(&self) {
140 self.on_quit.borrow_mut().drain(..).for_each(|f| f());
141 self.app.borrow_mut().shutdown();
142 }
143
144 /// Register cleanup to run when the test ends.
145 pub fn on_quit(&mut self, f: impl FnOnce() + 'static) {
146 self.on_quit.borrow_mut().push(Box::new(f));
147 }
148
149 /// Schedules all windows to be redrawn on the next effect cycle.
150 pub fn refresh(&mut self) -> Result<()> {
151 let mut app = self.app.borrow_mut();
152 app.refresh();
153 Ok(())
154 }
155
156 /// Returns an executor (for running tasks in the background)
157 pub fn executor(&self) -> BackgroundExecutor {
158 self.background_executor.clone()
159 }
160
161 /// Returns an executor (for running tasks on the main thread)
162 pub fn foreground_executor(&self) -> &ForegroundExecutor {
163 &self.foreground_executor
164 }
165
166 /// Gives you an `&mut AppContext` for the duration of the closure
167 pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> R {
168 let mut cx = self.app.borrow_mut();
169 cx.update(f)
170 }
171
172 /// Gives you an `&AppContext` for the duration of the closure
173 pub fn read<R>(&self, f: impl FnOnce(&AppContext) -> R) -> R {
174 let cx = self.app.borrow();
175 f(&cx)
176 }
177
178 /// Adds a new window. The Window will always be backed by a `TestWindow` which
179 /// can be retrieved with `self.test_window(handle)`
180 pub fn add_window<F, V>(&mut self, build_window: F) -> WindowHandle<V>
181 where
182 F: FnOnce(&mut ViewContext<V>) -> V,
183 V: 'static + Render,
184 {
185 let mut cx = self.app.borrow_mut();
186
187 // Some tests rely on the window size matching the bounds of the test display
188 let bounds = Bounds::maximized(None, &mut cx);
189 cx.open_window(
190 WindowOptions {
191 window_bounds: Some(WindowBounds::Windowed(bounds)),
192 ..Default::default()
193 },
194 |cx| cx.new_view(build_window),
195 )
196 .unwrap()
197 }
198
199 /// Adds a new window with no content.
200 pub fn add_empty_window(&mut self) -> &mut VisualTestContext {
201 let mut cx = self.app.borrow_mut();
202 let bounds = Bounds::maximized(None, &mut cx);
203 let window = cx
204 .open_window(
205 WindowOptions {
206 window_bounds: Some(WindowBounds::Windowed(bounds)),
207 ..Default::default()
208 },
209 |cx| cx.new_view(|_| Empty),
210 )
211 .unwrap();
212 drop(cx);
213 let cx = VisualTestContext::from_window(*window.deref(), self).as_mut();
214 cx.run_until_parked();
215 cx
216 }
217
218 /// Adds a new window, and returns its root view and a `VisualTestContext` which can be used
219 /// as a `WindowContext` for the rest of the test. Typically you would shadow this context with
220 /// the returned one. `let (view, cx) = cx.add_window_view(...);`
221 pub fn add_window_view<F, V>(&mut self, build_root_view: F) -> (View<V>, &mut VisualTestContext)
222 where
223 F: FnOnce(&mut ViewContext<V>) -> V,
224 V: 'static + Render,
225 {
226 let mut cx = self.app.borrow_mut();
227 let bounds = Bounds::maximized(None, &mut cx);
228 let window = cx
229 .open_window(
230 WindowOptions {
231 window_bounds: Some(WindowBounds::Windowed(bounds)),
232 ..Default::default()
233 },
234 |cx| cx.new_view(build_root_view),
235 )
236 .unwrap();
237 drop(cx);
238 let view = window.root_view(self).unwrap();
239 let cx = VisualTestContext::from_window(*window.deref(), self).as_mut();
240 cx.run_until_parked();
241
242 // it might be nice to try and cleanup these at the end of each test.
243 (view, cx)
244 }
245
246 /// returns the TextSystem
247 pub fn text_system(&self) -> &Arc<TextSystem> {
248 &self.text_system
249 }
250
251 /// Simulates writing to the platform clipboard
252 pub fn write_to_clipboard(&self, item: ClipboardItem) {
253 self.test_platform.write_to_clipboard(item)
254 }
255
256 /// Simulates reading from the platform clipboard.
257 /// This will return the most recent value from `write_to_clipboard`.
258 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
259 self.test_platform.read_from_clipboard()
260 }
261
262 /// Simulates choosing a File in the platform's "Open" dialog.
263 pub fn simulate_new_path_selection(
264 &self,
265 select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
266 ) {
267 self.test_platform.simulate_new_path_selection(select_path);
268 }
269
270 /// Simulates clicking a button in an platform-level alert dialog.
271 pub fn simulate_prompt_answer(&self, button_ix: usize) {
272 self.test_platform.simulate_prompt_answer(button_ix);
273 }
274
275 /// Returns true if there's an alert dialog open.
276 pub fn has_pending_prompt(&self) -> bool {
277 self.test_platform.has_pending_prompt()
278 }
279
280 /// All the urls that have been opened with cx.open_url() during this test.
281 pub fn opened_url(&self) -> Option<String> {
282 self.test_platform.opened_url.borrow().clone()
283 }
284
285 /// Simulates the user resizing the window to the new size.
286 pub fn simulate_window_resize(&self, window_handle: AnyWindowHandle, size: Size<Pixels>) {
287 self.test_window(window_handle).simulate_resize(size);
288 }
289
290 /// Returns all windows open in the test.
291 pub fn windows(&self) -> Vec<AnyWindowHandle> {
292 self.app.borrow().windows().clone()
293 }
294
295 /// Run the given task on the main thread.
296 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
297 where
298 Fut: Future<Output = R> + 'static,
299 R: 'static,
300 {
301 self.foreground_executor.spawn(f(self.to_async()))
302 }
303
304 /// true if the given global is defined
305 pub fn has_global<G: Global>(&self) -> bool {
306 let app = self.app.borrow();
307 app.has_global::<G>()
308 }
309
310 /// runs the given closure with a reference to the global
311 /// panics if `has_global` would return false.
312 pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> R {
313 let app = self.app.borrow();
314 read(app.global(), &app)
315 }
316
317 /// runs the given closure with a reference to the global (if set)
318 pub fn try_read_global<G: Global, R>(
319 &self,
320 read: impl FnOnce(&G, &AppContext) -> R,
321 ) -> Option<R> {
322 let lock = self.app.borrow();
323 Some(read(lock.try_global()?, &lock))
324 }
325
326 /// sets the global in this context.
327 pub fn set_global<G: Global>(&mut self, global: G) {
328 let mut lock = self.app.borrow_mut();
329 lock.update(|cx| cx.set_global(global))
330 }
331
332 /// updates the global in this context. (panics if `has_global` would return false)
333 pub fn update_global<G: Global, R>(
334 &mut self,
335 update: impl FnOnce(&mut G, &mut AppContext) -> R,
336 ) -> R {
337 let mut lock = self.app.borrow_mut();
338 lock.update(|cx| cx.update_global(update))
339 }
340
341 /// Returns an `AsyncAppContext` which can be used to run tasks that expect to be on a background
342 /// thread on the current thread in tests.
343 pub fn to_async(&self) -> AsyncAppContext {
344 AsyncAppContext {
345 app: Rc::downgrade(&self.app),
346 background_executor: self.background_executor.clone(),
347 foreground_executor: self.foreground_executor.clone(),
348 }
349 }
350
351 /// Wait until there are no more pending tasks.
352 pub fn run_until_parked(&mut self) {
353 self.background_executor.run_until_parked()
354 }
355
356 /// Simulate dispatching an action to the currently focused node in the window.
357 pub fn dispatch_action<A>(&mut self, window: AnyWindowHandle, action: A)
358 where
359 A: Action,
360 {
361 window
362 .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
363 .unwrap();
364
365 self.background_executor.run_until_parked()
366 }
367
368 /// simulate_keystrokes takes a space-separated list of keys to type.
369 /// cx.simulate_keystrokes("cmd-shift-p b k s p enter")
370 /// in Zed, this will run backspace on the current editor through the command palette.
371 /// This will also run the background executor until it's parked.
372 pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
373 for keystroke in keystrokes
374 .split(' ')
375 .map(Keystroke::parse)
376 .map(Result::unwrap)
377 {
378 self.dispatch_keystroke(window, keystroke);
379 }
380
381 self.background_executor.run_until_parked()
382 }
383
384 /// simulate_input takes a string of text to type.
385 /// cx.simulate_input("abc")
386 /// will type abc into your current editor
387 /// This will also run the background executor until it's parked.
388 pub fn simulate_input(&mut self, window: AnyWindowHandle, input: &str) {
389 for keystroke in input.split("").map(Keystroke::parse).map(Result::unwrap) {
390 self.dispatch_keystroke(window, keystroke);
391 }
392
393 self.background_executor.run_until_parked()
394 }
395
396 /// dispatches a single Keystroke (see also `simulate_keystrokes` and `simulate_input`)
397 pub fn dispatch_keystroke(&mut self, window: AnyWindowHandle, keystroke: Keystroke) {
398 self.update_window(window, |_, cx| cx.dispatch_keystroke(keystroke))
399 .unwrap();
400 }
401
402 /// Returns the `TestWindow` backing the given handle.
403 pub(crate) fn test_window(&self, window: AnyWindowHandle) -> TestWindow {
404 self.app
405 .borrow_mut()
406 .windows
407 .get_mut(window.id)
408 .unwrap()
409 .as_mut()
410 .unwrap()
411 .platform_window
412 .as_test()
413 .unwrap()
414 .clone()
415 }
416
417 /// Returns a stream of notifications whenever the View or Model is updated.
418 pub fn notifications<T: 'static>(&mut self, entity: &impl Entity<T>) -> impl Stream<Item = ()> {
419 let (tx, rx) = futures::channel::mpsc::unbounded();
420 self.update(|cx| {
421 cx.observe(entity, {
422 let tx = tx.clone();
423 move |_, _| {
424 let _ = tx.unbounded_send(());
425 }
426 })
427 .detach();
428 cx.observe_release(entity, move |_, _| tx.close_channel())
429 .detach()
430 });
431 rx
432 }
433
434 /// Retuens a stream of events emitted by the given Model.
435 pub fn events<Evt, T: 'static + EventEmitter<Evt>>(
436 &mut self,
437 entity: &Model<T>,
438 ) -> futures::channel::mpsc::UnboundedReceiver<Evt>
439 where
440 Evt: 'static + Clone,
441 {
442 let (tx, rx) = futures::channel::mpsc::unbounded();
443 entity
444 .update(self, |_, cx: &mut ModelContext<T>| {
445 cx.subscribe(entity, move |_model, _handle, event, _cx| {
446 let _ = tx.unbounded_send(event.clone());
447 })
448 })
449 .detach();
450 rx
451 }
452
453 /// Runs until the given condition becomes true. (Prefer `run_until_parked` if you
454 /// don't need to jump in at a specific time).
455 pub async fn condition<T: 'static>(
456 &mut self,
457 model: &Model<T>,
458 mut predicate: impl FnMut(&mut T, &mut ModelContext<T>) -> bool,
459 ) {
460 let timer = self.executor().timer(Duration::from_secs(3));
461 let mut notifications = self.notifications(model);
462
463 use futures::FutureExt as _;
464 use smol::future::FutureExt as _;
465
466 async {
467 loop {
468 if model.update(self, &mut predicate) {
469 return Ok(());
470 }
471
472 if notifications.next().await.is_none() {
473 bail!("model dropped")
474 }
475 }
476 }
477 .race(timer.map(|_| Err(anyhow!("condition timed out"))))
478 .await
479 .unwrap();
480 }
481}
482
483impl<T: 'static> Model<T> {
484 /// Block until the next event is emitted by the model, then return it.
485 pub fn next_event<Event>(&self, cx: &mut TestAppContext) -> impl Future<Output = Event>
486 where
487 Event: Send + Clone + 'static,
488 T: EventEmitter<Event>,
489 {
490 let (tx, mut rx) = oneshot::channel();
491 let mut tx = Some(tx);
492 let subscription = self.update(cx, |_, cx| {
493 cx.subscribe(self, move |_, _, event, _| {
494 if let Some(tx) = tx.take() {
495 _ = tx.send(event.clone());
496 }
497 })
498 });
499
500 async move {
501 let event = rx.await.expect("no event emitted");
502 drop(subscription);
503 event
504 }
505 }
506
507 /// Returns a future that resolves when the model notifies.
508 pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
509 use postage::prelude::{Sink as _, Stream as _};
510
511 let (mut tx, mut rx) = postage::mpsc::channel(1);
512 let mut cx = cx.app.app.borrow_mut();
513 let subscription = cx.observe(self, move |_, _| {
514 tx.try_send(()).ok();
515 });
516
517 let duration = if std::env::var("CI").is_ok() {
518 Duration::from_secs(5)
519 } else {
520 Duration::from_secs(1)
521 };
522
523 async move {
524 let notification = crate::util::timeout(duration, rx.recv())
525 .await
526 .expect("next notification timed out");
527 drop(subscription);
528 notification.expect("model dropped while test was waiting for its next notification")
529 }
530 }
531}
532
533impl<V: 'static> View<V> {
534 /// Returns a future that resolves when the view is next updated.
535 pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
536 use postage::prelude::{Sink as _, Stream as _};
537
538 let (mut tx, mut rx) = postage::mpsc::channel(1);
539 let mut cx = cx.app.app.borrow_mut();
540 let subscription = cx.observe(self, move |_, _| {
541 tx.try_send(()).ok();
542 });
543
544 let duration = if std::env::var("CI").is_ok() {
545 Duration::from_secs(5)
546 } else {
547 Duration::from_secs(1)
548 };
549
550 async move {
551 let notification = crate::util::timeout(duration, rx.recv())
552 .await
553 .expect("next notification timed out");
554 drop(subscription);
555 notification.expect("model dropped while test was waiting for its next notification")
556 }
557 }
558}
559
560impl<V> View<V> {
561 /// Returns a future that resolves when the condition becomes true.
562 pub fn condition<Evt>(
563 &self,
564 cx: &TestAppContext,
565 mut predicate: impl FnMut(&V, &AppContext) -> bool,
566 ) -> impl Future<Output = ()>
567 where
568 Evt: 'static,
569 V: EventEmitter<Evt>,
570 {
571 use postage::prelude::{Sink as _, Stream as _};
572
573 let (tx, mut rx) = postage::mpsc::channel(1024);
574 let timeout_duration = Duration::from_millis(100);
575
576 let mut cx = cx.app.borrow_mut();
577 let subscriptions = (
578 cx.observe(self, {
579 let mut tx = tx.clone();
580 move |_, _| {
581 tx.blocking_send(()).ok();
582 }
583 }),
584 cx.subscribe(self, {
585 let mut tx = tx.clone();
586 move |_, _: &Evt, _| {
587 tx.blocking_send(()).ok();
588 }
589 }),
590 );
591
592 let cx = cx.this.upgrade().unwrap();
593 let handle = self.downgrade();
594
595 async move {
596 crate::util::timeout(timeout_duration, async move {
597 loop {
598 {
599 let cx = cx.borrow();
600 let cx = &*cx;
601 if predicate(
602 handle
603 .upgrade()
604 .expect("view dropped with pending condition")
605 .read(cx),
606 cx,
607 ) {
608 break;
609 }
610 }
611
612 cx.borrow().background_executor().start_waiting();
613 rx.recv()
614 .await
615 .expect("view dropped with pending condition");
616 cx.borrow().background_executor().finish_waiting();
617 }
618 })
619 .await
620 .expect("condition timed out");
621 drop(subscriptions);
622 }
623 }
624}
625
626use derive_more::{Deref, DerefMut};
627#[derive(Deref, DerefMut, Clone)]
628/// A VisualTestContext is the test-equivalent of a `WindowContext`. It allows you to
629/// run window-specific test code.
630pub struct VisualTestContext {
631 #[deref]
632 #[deref_mut]
633 /// cx is the original TestAppContext (you can more easily access this using Deref)
634 pub cx: TestAppContext,
635 window: AnyWindowHandle,
636}
637
638impl VisualTestContext {
639 /// Get the underlying window handle underlying this context.
640 pub fn handle(&self) -> AnyWindowHandle {
641 self.window
642 }
643
644 /// Provides the `WindowContext` for the duration of the closure.
645 pub fn update<R>(&mut self, f: impl FnOnce(&mut WindowContext) -> R) -> R {
646 self.cx.update_window(self.window, |_, cx| f(cx)).unwrap()
647 }
648
649 /// Creates a new VisualTestContext. You would typically shadow the passed in
650 /// TestAppContext with this, as this is typically more useful.
651 /// `let cx = VisualTestContext::from_window(window, cx);`
652 pub fn from_window(window: AnyWindowHandle, cx: &TestAppContext) -> Self {
653 Self {
654 cx: cx.clone(),
655 window,
656 }
657 }
658
659 /// Wait until there are no more pending tasks.
660 pub fn run_until_parked(&self) {
661 self.cx.background_executor.run_until_parked();
662 }
663
664 /// Dispatch the action to the currently focused node.
665 pub fn dispatch_action<A>(&mut self, action: A)
666 where
667 A: Action,
668 {
669 self.cx.dispatch_action(self.window, action)
670 }
671
672 /// Read the title off the window (set by `WindowContext#set_window_title`)
673 pub fn window_title(&mut self) -> Option<String> {
674 self.cx.test_window(self.window).0.lock().title.clone()
675 }
676
677 /// Simulate a sequence of keystrokes `cx.simulate_keystrokes("cmd-p escape")`
678 /// Automatically runs until parked.
679 pub fn simulate_keystrokes(&mut self, keystrokes: &str) {
680 self.cx.simulate_keystrokes(self.window, keystrokes)
681 }
682
683 /// Simulate typing text `cx.simulate_input("hello")`
684 /// Automatically runs until parked.
685 pub fn simulate_input(&mut self, input: &str) {
686 self.cx.simulate_input(self.window, input)
687 }
688
689 /// Simulate a mouse move event to the given point
690 pub fn simulate_mouse_move(
691 &mut self,
692 position: Point<Pixels>,
693 button: impl Into<Option<MouseButton>>,
694 modifiers: Modifiers,
695 ) {
696 self.simulate_event(MouseMoveEvent {
697 position,
698 modifiers,
699 pressed_button: button.into(),
700 })
701 }
702
703 /// Simulate a mouse down event to the given point
704 pub fn simulate_mouse_down(
705 &mut self,
706 position: Point<Pixels>,
707 button: MouseButton,
708 modifiers: Modifiers,
709 ) {
710 self.simulate_event(MouseDownEvent {
711 position,
712 modifiers,
713 button,
714 click_count: 1,
715 first_mouse: false,
716 })
717 }
718
719 /// Simulate a mouse up event to the given point
720 pub fn simulate_mouse_up(
721 &mut self,
722 position: Point<Pixels>,
723 button: MouseButton,
724 modifiers: Modifiers,
725 ) {
726 self.simulate_event(MouseUpEvent {
727 position,
728 modifiers,
729 button,
730 click_count: 1,
731 })
732 }
733
734 /// Simulate a primary mouse click at the given point
735 pub fn simulate_click(&mut self, position: Point<Pixels>, modifiers: Modifiers) {
736 self.simulate_event(MouseDownEvent {
737 position,
738 modifiers,
739 button: MouseButton::Left,
740 click_count: 1,
741 first_mouse: false,
742 });
743 self.simulate_event(MouseUpEvent {
744 position,
745 modifiers,
746 button: MouseButton::Left,
747 click_count: 1,
748 });
749 }
750
751 /// Simulate a modifiers changed event
752 pub fn simulate_modifiers_change(&mut self, modifiers: Modifiers) {
753 self.simulate_event(ModifiersChangedEvent { modifiers })
754 }
755
756 /// Simulates the user resizing the window to the new size.
757 pub fn simulate_resize(&self, size: Size<Pixels>) {
758 self.simulate_window_resize(self.window, size)
759 }
760
761 /// debug_bounds returns the bounds of the element with the given selector.
762 pub fn debug_bounds(&mut self, selector: &'static str) -> Option<Bounds<Pixels>> {
763 self.update(|cx| cx.window.rendered_frame.debug_bounds.get(selector).copied())
764 }
765
766 /// Draw an element to the window. Useful for simulating events or actions
767 pub fn draw<E>(
768 &mut self,
769 origin: Point<Pixels>,
770 space: impl Into<Size<AvailableSpace>>,
771 f: impl FnOnce(&mut WindowContext) -> E,
772 ) -> (E::RequestLayoutState, E::PrepaintState)
773 where
774 E: Element,
775 {
776 self.update(|cx| {
777 cx.window.draw_phase = DrawPhase::Prepaint;
778 let mut element = Drawable::new(f(cx));
779 element.layout_as_root(space.into(), cx);
780 cx.with_absolute_element_offset(origin, |cx| element.prepaint(cx));
781
782 cx.window.draw_phase = DrawPhase::Paint;
783 let (request_layout_state, prepaint_state) = element.paint(cx);
784
785 cx.window.draw_phase = DrawPhase::None;
786 cx.refresh();
787
788 (request_layout_state, prepaint_state)
789 })
790 }
791
792 /// Simulate an event from the platform, e.g. a SrollWheelEvent
793 /// Make sure you've called [VisualTestContext::draw] first!
794 pub fn simulate_event<E: InputEvent>(&mut self, event: E) {
795 self.test_window(self.window)
796 .simulate_input(event.to_platform_input());
797 self.background_executor.run_until_parked();
798 }
799
800 /// Simulates the user blurring the window.
801 pub fn deactivate_window(&mut self) {
802 if Some(self.window) == self.test_platform.active_window() {
803 self.test_platform.set_active_window(None)
804 }
805 self.background_executor.run_until_parked();
806 }
807
808 /// Simulates the user closing the window.
809 /// Returns true if the window was closed.
810 pub fn simulate_close(&mut self) -> bool {
811 let handler = self
812 .cx
813 .update_window(self.window, |_, cx| {
814 cx.window
815 .platform_window
816 .as_test()
817 .unwrap()
818 .0
819 .lock()
820 .should_close_handler
821 .take()
822 })
823 .unwrap();
824 if let Some(mut handler) = handler {
825 let should_close = handler();
826 self.cx
827 .update_window(self.window, |_, cx| {
828 cx.window.platform_window.on_should_close(handler);
829 })
830 .unwrap();
831 should_close
832 } else {
833 false
834 }
835 }
836
837 /// Get an &mut VisualTestContext (which is mostly what you need to pass to other methods).
838 /// This method internally retains the VisualTestContext until the end of the test.
839 pub fn as_mut(self) -> &'static mut Self {
840 let ptr = Box::into_raw(Box::new(self));
841 // safety: on_quit will be called after the test has finished.
842 // the executor will ensure that all tasks related to the test have stopped.
843 // so there is no way for cx to be accessed after on_quit is called.
844 let cx = Box::leak(unsafe { Box::from_raw(ptr) });
845 cx.on_quit(move || unsafe {
846 drop(Box::from_raw(ptr));
847 });
848 cx
849 }
850}
851
852impl Context for VisualTestContext {
853 type Result<T> = <TestAppContext as Context>::Result<T>;
854
855 fn new_model<T: 'static>(
856 &mut self,
857 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
858 ) -> Self::Result<Model<T>> {
859 self.cx.new_model(build_model)
860 }
861
862 fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
863 self.cx.reserve_model()
864 }
865
866 fn insert_model<T: 'static>(
867 &mut self,
868 reservation: crate::Reservation<T>,
869 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
870 ) -> Self::Result<Model<T>> {
871 self.cx.insert_model(reservation, build_model)
872 }
873
874 fn update_model<T, R>(
875 &mut self,
876 handle: &Model<T>,
877 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
878 ) -> Self::Result<R>
879 where
880 T: 'static,
881 {
882 self.cx.update_model(handle, update)
883 }
884
885 fn read_model<T, R>(
886 &self,
887 handle: &Model<T>,
888 read: impl FnOnce(&T, &AppContext) -> R,
889 ) -> Self::Result<R>
890 where
891 T: 'static,
892 {
893 self.cx.read_model(handle, read)
894 }
895
896 fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
897 where
898 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
899 {
900 self.cx.update_window(window, f)
901 }
902
903 fn read_window<T, R>(
904 &self,
905 window: &WindowHandle<T>,
906 read: impl FnOnce(View<T>, &AppContext) -> R,
907 ) -> Result<R>
908 where
909 T: 'static,
910 {
911 self.cx.read_window(window, read)
912 }
913}
914
915impl VisualContext for VisualTestContext {
916 fn new_view<V>(
917 &mut self,
918 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
919 ) -> Self::Result<View<V>>
920 where
921 V: 'static + Render,
922 {
923 self.window
924 .update(&mut self.cx, |_, cx| cx.new_view(build_view))
925 .unwrap()
926 }
927
928 fn update_view<V: 'static, R>(
929 &mut self,
930 view: &View<V>,
931 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
932 ) -> Self::Result<R> {
933 self.window
934 .update(&mut self.cx, |_, cx| cx.update_view(view, update))
935 .unwrap()
936 }
937
938 fn replace_root_view<V>(
939 &mut self,
940 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
941 ) -> Self::Result<View<V>>
942 where
943 V: 'static + Render,
944 {
945 self.window
946 .update(&mut self.cx, |_, cx| cx.replace_root_view(build_view))
947 .unwrap()
948 }
949
950 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
951 self.window
952 .update(&mut self.cx, |_, cx| {
953 view.read(cx).focus_handle(cx).clone().focus(cx)
954 })
955 .unwrap()
956 }
957
958 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
959 where
960 V: crate::ManagedView,
961 {
962 self.window
963 .update(&mut self.cx, |_, cx| {
964 view.update(cx, |_, cx| cx.emit(crate::DismissEvent))
965 })
966 .unwrap()
967 }
968}
969
970impl AnyWindowHandle {
971 /// Creates the given view in this window.
972 pub fn build_view<V: Render + 'static>(
973 &self,
974 cx: &mut TestAppContext,
975 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
976 ) -> View<V> {
977 self.update(cx, |_, cx| cx.new_view(build_view)).unwrap()
978 }
979}