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