| 1 | //! Test support for GPUI. |
| 2 | //! |
| 3 | //! GPUI provides first-class support for testing, which includes a macro to run test that rely on having a context, |
| 4 | //! and a test implementation of the `ForegroundExecutor` and `BackgroundExecutor` which ensure that your tests run |
| 5 | //! deterministically even in the face of arbitrary parallelism. |
| 6 | //! |
| 7 | //! The output of the `gpui::test` macro is understood by other rust test runners, so you can use it with `cargo test` |
| 8 | //! or `cargo-nextest`, or another runner of your choice. |
| 9 | //! |
| 10 | //! To make it possible to test collaborative user interfaces (like Zed) you can ask for as many different contexts |
| 11 | //! as you need. |
| 12 | //! |
| 13 | //! ## Example |
| 14 | //! |
| 15 | //! ``` |
| 16 | //! use gpui; |
| 17 | //! |
| 18 | //! #[gpui::test] |
| 19 | //! async fn test_example(cx: &TestAppContext) { |
| 20 | //! assert!(true) |
| 21 | //! } |
| 22 | //! |
| 23 | //! #[gpui::test] |
| 24 | //! async fn test_collaboration_example(cx_a: &TestAppContext, cx_b: &TestAppContext) { |
| 25 | //! assert!(true) |
| 26 | //! } |
| 27 | //! ``` |
| 28 | use crate::{Entity, Subscription, TestAppContext, TestDispatcher, calculate_seeds}; |
| 29 | use futures::StreamExt as _; |
| 30 | use proptest::prelude::{Just, Strategy, any}; |
| 31 | use std::{ |
| 32 | env, |
| 33 | panic::{self, RefUnwindSafe, UnwindSafe}, |
| 34 | pin::Pin, |
| 35 | }; |
| 36 | |
| 37 | /// Strategy injected into `#[gpui::property_test]` tests to control the seed |
| 38 | /// given to the scheduler. Doesn't shrink, since all scheduler seeds are |
| 39 | /// equivalent in complexity. If `$SEED` is set, it always uses that value. |
| 40 | /// |
| 41 | /// Note: this function is not intended to be used directly. Rather, it is |
| 42 | /// public so that it can be used from the `property_test` macro. |
| 43 | pub fn seed_strategy() -> impl Strategy<Value = u64> { |
| 44 | match std::env::var("SEED") { |
| 45 | Ok(val) => Just(val.parse().unwrap()).boxed(), |
| 46 | Err(_) => any::<u64>().no_shrink().boxed(), |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /// Applies a fixed RNG seed to a proptest config so that case generation |
| 51 | /// is deterministic. Uses `$SEED` if set, otherwise defaults to `0`. |
| 52 | /// This bridges the GPUI `SEED` env var to proptest's RNG seed, so that |
| 53 | /// a single variable controls both the scheduler seed and case generation. |
| 54 | /// |
| 55 | /// Note: this function is not intended to be used directly. Rather, it is |
| 56 | /// public so that it can be used from the `property_test` macro. |
| 57 | pub fn apply_seed_to_proptest_config( |
| 58 | mut config: proptest::test_runner::Config, |
| 59 | ) -> proptest::test_runner::Config { |
| 60 | let seed = env::var("SEED") |
| 61 | .ok() |
| 62 | .and_then(|val| val.parse::<u64>().ok()) |
| 63 | .unwrap_or(0); |
| 64 | config.rng_seed = proptest::test_runner::RngSeed::Fixed(seed); |
| 65 | config |
| 66 | } |
| 67 | |
| 68 | /// Similar to [`run_test`], but only runs the callback once, allowing |
| 69 | /// [`FnOnce`] callbacks. This is intended for use with the |
| 70 | /// `gpui::property_test` macro and generally should not be used directly. |
| 71 | /// |
| 72 | /// Doesn't support many features of [`run_test`], since these are provided by |
| 73 | /// proptest. |
| 74 | pub fn run_test_once<R>( |
| 75 | seed: u64, |
| 76 | test_fn: Box<dyn UnwindSafe + FnOnce(TestDispatcher) -> R>, |
| 77 | ) -> R { |
| 78 | let result = panic::catch_unwind(|| { |
| 79 | let dispatcher = TestDispatcher::new(seed); |
| 80 | let scheduler = dispatcher.scheduler().clone(); |
| 81 | let res = test_fn(dispatcher); |
| 82 | scheduler.end_test(); |
| 83 | res |
| 84 | }); |
| 85 | |
| 86 | match result { |
| 87 | Ok(r) => r, |
| 88 | Err(e) => panic::resume_unwind(e), |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | /// Run the given test function with the configured parameters. |
| 93 | /// This is intended for use with the `gpui::test` macro |
| 94 | /// and generally should not be used directly. |
| 95 | pub fn run_test( |
| 96 | num_iterations: usize, |
| 97 | explicit_seeds: &[u64], |
| 98 | max_retries: usize, |
| 99 | test_fn: &mut (dyn RefUnwindSafe + Fn(TestDispatcher, u64)), |
| 100 | on_fail_fn: Option<fn()>, |
| 101 | ) { |
| 102 | let (seeds, is_multiple_runs) = calculate_seeds(num_iterations as u64, explicit_seeds); |
| 103 | |
| 104 | for seed in seeds { |
| 105 | let mut attempt = 0; |
| 106 | loop { |
| 107 | if is_multiple_runs { |
| 108 | eprintln!("seed = {seed}"); |
| 109 | } |
| 110 | let result = panic::catch_unwind(|| { |
| 111 | let dispatcher = TestDispatcher::new(seed); |
| 112 | let scheduler = dispatcher.scheduler().clone(); |
| 113 | test_fn(dispatcher, seed); |
| 114 | scheduler.end_test(); |
| 115 | }); |
| 116 | |
| 117 | match result { |
| 118 | Ok(_) => break, |
| 119 | Err(error) => { |
| 120 | if attempt < max_retries { |
| 121 | println!("attempt {} failed, retrying", attempt); |
| 122 | attempt += 1; |
| 123 | // The panic payload might itself trigger an unwind on drop: |
| 124 | // https://doc.rust-lang.org/std/panic/fn.catch_unwind.html#notes |
| 125 | std::mem::forget(error); |
| 126 | } else { |
| 127 | if is_multiple_runs { |
| 128 | eprintln!("failing seed: {seed}"); |
| 129 | eprintln!( |
| 130 | "You can rerun from this seed by setting the environmental variable SEED to {seed}" |
| 131 | ); |
| 132 | } |
| 133 | if let Some(on_fail_fn) = on_fail_fn { |
| 134 | on_fail_fn() |
| 135 | } |
| 136 | panic::resume_unwind(error); |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /// A test struct for converting an observation callback into a stream. |
| 145 | pub struct Observation<T> { |
| 146 | rx: Pin<Box<async_channel::Receiver<T>>>, |
| 147 | _subscription: Subscription, |
| 148 | } |
| 149 | |
| 150 | impl<T: 'static> futures::Stream for Observation<T> { |
| 151 | type Item = T; |
| 152 | |
| 153 | fn poll_next( |
| 154 | mut self: std::pin::Pin<&mut Self>, |
| 155 | cx: &mut std::task::Context<'_>, |
| 156 | ) -> std::task::Poll<Option<Self::Item>> { |
| 157 | self.rx.poll_next_unpin(cx) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | /// observe returns a stream of the change events from the given `Entity` |
| 162 | pub fn observe<T: 'static>(entity: &Entity<T>, cx: &mut TestAppContext) -> Observation<()> { |
| 163 | let (tx, rx) = async_channel::unbounded(); |
| 164 | let _subscription = cx.update(|cx| { |
| 165 | cx.observe(entity, move |_, _| { |
| 166 | let _ = gpui::block_on(tx.send(())); |
| 167 | }) |
| 168 | }); |
| 169 | let rx = Box::pin(rx); |
| 170 | |
| 171 | Observation { rx, _subscription } |
| 172 | } |