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