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