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