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};
 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    mut num_iterations: u64,
 42    max_retries: usize,
 43    test_fn: &mut (dyn RefUnwindSafe + Fn(TestDispatcher, u64)),
 44    on_fail_fn: Option<fn()>,
 45) {
 46    let starting_seed = env::var("SEED")
 47        .map(|seed| seed.parse().expect("invalid SEED variable"))
 48        .unwrap_or(0);
 49    if let Ok(iterations) = env::var("ITERATIONS") {
 50        num_iterations = iterations.parse().expect("invalid ITERATIONS variable");
 51    }
 52    let is_randomized = num_iterations > 1;
 53
 54    for seed in starting_seed..starting_seed + num_iterations {
 55        let mut retry = 0;
 56        loop {
 57            if is_randomized {
 58                eprintln!("seed = {seed}");
 59            }
 60            let result = panic::catch_unwind(|| {
 61                let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(seed));
 62                test_fn(dispatcher, seed);
 63            });
 64
 65            match result {
 66                Ok(_) => break,
 67                Err(error) => {
 68                    if retry < max_retries {
 69                        println!("retrying: attempt {}", retry);
 70                        retry += 1;
 71                    } else {
 72                        if is_randomized {
 73                            eprintln!("failing seed: {}", seed);
 74                        }
 75                        if let Some(f) = on_fail_fn {
 76                            f()
 77                        }
 78                        panic::resume_unwind(error);
 79                    }
 80                }
 81            }
 82        }
 83    }
 84}
 85
 86/// A test struct for converting an observation callback into a stream.
 87pub struct Observation<T> {
 88    rx: channel::Receiver<T>,
 89    _subscription: Subscription,
 90}
 91
 92impl<T: 'static> futures::Stream for Observation<T> {
 93    type Item = T;
 94
 95    fn poll_next(
 96        mut self: std::pin::Pin<&mut Self>,
 97        cx: &mut std::task::Context<'_>,
 98    ) -> std::task::Poll<Option<Self::Item>> {
 99        self.rx.poll_next_unpin(cx)
100    }
101}
102
103/// observe returns a stream of the change events from the given `View` or `Model`
104pub fn observe<T: 'static>(entity: &impl Entity<T>, cx: &mut TestAppContext) -> Observation<()> {
105    let (tx, rx) = smol::channel::unbounded();
106    let _subscription = cx.update(|cx| {
107        cx.observe(entity, move |_, _| {
108            let _ = smol::block_on(tx.send(()));
109        })
110    });
111
112    Observation { rx, _subscription }
113}