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