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