test_context.rs

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