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