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