test_context.rs

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