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