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                        }
 74                        if let Some(on_fail_fn) = on_fail_fn {
 75                            on_fail_fn()
 76                        }
 77                        panic::resume_unwind(error);
 78                    }
 79                }
 80            }
 81        }
 82    }
 83}
 84
 85fn calculate_seeds(
 86    iterations: u64,
 87    explicit_seeds: &[u64],
 88) -> (impl Iterator<Item = u64> + '_, bool) {
 89    let iterations = env::var("ITERATIONS")
 90        .ok()
 91        .map(|var| var.parse().expect("invalid ITERATIONS variable"))
 92        .unwrap_or(iterations);
 93
 94    let env_num = env::var("SEED")
 95        .map(|seed| seed.parse().expect("invalid SEED variable as integer"))
 96        .ok();
 97
 98    let empty_range = || 0..0;
 99
100    let iter = {
101        let env_range = if let Some(env_num) = env_num {
102            env_num..env_num + 1
103        } else {
104            empty_range()
105        };
106
107        // if `iterations` is 1 and !(`explicit_seeds` is non-empty || `SEED` is set), then add     the run `0`
108        // if `iterations` is 1 and  (`explicit_seeds` is non-empty || `SEED` is set), then discard the run `0`
109        // if `iterations` isn't 1 and `SEED` is set, do `SEED..SEED+iterations`
110        // otherwise, do `0..iterations`
111        let iterations_range = match (iterations, env_num) {
112            (1, None) if explicit_seeds.is_empty() => 0..1,
113            (1, None) | (1, Some(_)) => empty_range(),
114            (iterations, Some(env)) => env..env + iterations,
115            (iterations, None) => 0..iterations,
116        };
117
118        // if `SEED` is set, ignore `explicit_seeds`
119        let explicit_seeds = if env_num.is_some() {
120            &[]
121        } else {
122            explicit_seeds
123        };
124
125        env_range
126            .chain(iterations_range)
127            .chain(explicit_seeds.iter().copied())
128    };
129    let is_multiple_runs = iter.clone().nth(1).is_some();
130    (iter, is_multiple_runs)
131}
132
133/// A test struct for converting an observation callback into a stream.
134pub struct Observation<T> {
135    rx: Pin<Box<channel::Receiver<T>>>,
136    _subscription: Subscription,
137}
138
139impl<T: 'static> futures::Stream for Observation<T> {
140    type Item = T;
141
142    fn poll_next(
143        mut self: std::pin::Pin<&mut Self>,
144        cx: &mut std::task::Context<'_>,
145    ) -> std::task::Poll<Option<Self::Item>> {
146        self.rx.poll_next_unpin(cx)
147    }
148}
149
150/// observe returns a stream of the change events from the given `Entity`
151pub fn observe<T: 'static>(entity: &Entity<T>, cx: &mut TestAppContext) -> Observation<()> {
152    let (tx, rx) = smol::channel::unbounded();
153    let _subscription = cx.update(|cx| {
154        cx.observe(entity, move |_, _| {
155            let _ = smol::block_on(tx.send(()));
156        })
157    });
158    let rx = Box::pin(rx);
159
160    Observation { rx, _subscription }
161}