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