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