test.rs

  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//! ```
 28use crate::{Entity, Subscription, TestAppContext, TestDispatcher};
 29use futures::StreamExt as _;
 30use proptest::prelude::{Just, Strategy, any};
 31use 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.
 40pub fn seed_strategy() -> impl Strategy<Value = u64> {
 41    match std::env::var("SEED") {
 42        Ok(val) => Just(val.parse().unwrap()).boxed(),
 43        Err(_) => any::<u64>().no_shrink().boxed(),
 44    }
 45}
 46
 47/// Similar to [`run_test`], but only runs the callback once, allowing
 48/// [`FnOnce`] callbacks. This is intended for use with the
 49/// `gpui::property_test` macro and generally should not be used directly.
 50///
 51/// Doesn't support many features of [`run_test`], since these are provided by
 52/// proptest.
 53pub fn run_test_once(seed: u64, test_fn: Box<dyn UnwindSafe + FnOnce(TestDispatcher)>) {
 54    let result = panic::catch_unwind(|| {
 55        let dispatcher = TestDispatcher::new(seed);
 56        let scheduler = dispatcher.scheduler().clone();
 57        test_fn(dispatcher);
 58        scheduler.end_test();
 59    });
 60
 61    match result {
 62        Ok(()) => {}
 63        Err(e) => panic::resume_unwind(e),
 64    }
 65}
 66
 67/// Run the given test function with the configured parameters.
 68/// This is intended for use with the `gpui::test` macro
 69/// and generally should not be used directly.
 70pub fn run_test(
 71    num_iterations: usize,
 72    explicit_seeds: &[u64],
 73    max_retries: usize,
 74    test_fn: &mut (dyn RefUnwindSafe + Fn(TestDispatcher, u64)),
 75    on_fail_fn: Option<fn()>,
 76) {
 77    let (seeds, is_multiple_runs) = calculate_seeds(num_iterations as u64, explicit_seeds);
 78
 79    for seed in seeds {
 80        let mut attempt = 0;
 81        loop {
 82            if is_multiple_runs {
 83                eprintln!("seed = {seed}");
 84            }
 85            let result = panic::catch_unwind(|| {
 86                let dispatcher = TestDispatcher::new(seed);
 87                let scheduler = dispatcher.scheduler().clone();
 88                test_fn(dispatcher, seed);
 89                scheduler.end_test();
 90            });
 91
 92            match result {
 93                Ok(_) => break,
 94                Err(error) => {
 95                    if attempt < max_retries {
 96                        println!("attempt {} failed, retrying", attempt);
 97                        attempt += 1;
 98                        // The panic payload might itself trigger an unwind on drop:
 99                        // https://doc.rust-lang.org/std/panic/fn.catch_unwind.html#notes
100                        std::mem::forget(error);
101                    } else {
102                        if is_multiple_runs {
103                            eprintln!("failing seed: {seed}");
104                            eprintln!(
105                                "You can rerun from this seed by setting the environmental variable SEED to {seed}"
106                            );
107                        }
108                        if let Some(on_fail_fn) = on_fail_fn {
109                            on_fail_fn()
110                        }
111                        panic::resume_unwind(error);
112                    }
113                }
114            }
115        }
116    }
117}
118
119fn calculate_seeds(
120    iterations: u64,
121    explicit_seeds: &[u64],
122) -> (impl Iterator<Item = u64> + '_, bool) {
123    let iterations = env::var("ITERATIONS")
124        .ok()
125        .map(|var| var.parse().expect("invalid ITERATIONS variable"))
126        .unwrap_or(iterations);
127
128    let env_num = env::var("SEED")
129        .map(|seed| seed.parse().expect("invalid SEED variable as integer"))
130        .ok();
131
132    let empty_range = || 0..0;
133
134    let iter = {
135        let env_range = if let Some(env_num) = env_num {
136            env_num..env_num + 1
137        } else {
138            empty_range()
139        };
140
141        // if `iterations` is 1 and !(`explicit_seeds` is non-empty || `SEED` is set), then add     the run `0`
142        // if `iterations` is 1 and  (`explicit_seeds` is non-empty || `SEED` is set), then discard the run `0`
143        // if `iterations` isn't 1 and `SEED` is set, do `SEED..SEED+iterations`
144        // otherwise, do `0..iterations`
145        let iterations_range = match (iterations, env_num) {
146            (1, None) if explicit_seeds.is_empty() => 0..1,
147            (1, None) | (1, Some(_)) => empty_range(),
148            (iterations, Some(env)) => env..env + iterations,
149            (iterations, None) => 0..iterations,
150        };
151
152        // if `SEED` is set, ignore `explicit_seeds`
153        let explicit_seeds = if env_num.is_some() {
154            &[]
155        } else {
156            explicit_seeds
157        };
158
159        env_range
160            .chain(iterations_range)
161            .chain(explicit_seeds.iter().copied())
162    };
163    let is_multiple_runs = iter.clone().nth(1).is_some();
164    (iter, is_multiple_runs)
165}
166
167/// A test struct for converting an observation callback into a stream.
168pub struct Observation<T> {
169    rx: Pin<Box<async_channel::Receiver<T>>>,
170    _subscription: Subscription,
171}
172
173impl<T: 'static> futures::Stream for Observation<T> {
174    type Item = T;
175
176    fn poll_next(
177        mut self: std::pin::Pin<&mut Self>,
178        cx: &mut std::task::Context<'_>,
179    ) -> std::task::Poll<Option<Self::Item>> {
180        self.rx.poll_next_unpin(cx)
181    }
182}
183
184/// observe returns a stream of the change events from the given `Entity`
185pub fn observe<T: 'static>(entity: &Entity<T>, cx: &mut TestAppContext) -> Observation<()> {
186    let (tx, rx) = async_channel::unbounded();
187    let _subscription = cx.update(|cx| {
188        cx.observe(entity, move |_, _| {
189            let _ = pollster::block_on(tx.send(()));
190        })
191    });
192    let rx = Box::pin(rx);
193
194    Observation { rx, _subscription }
195}