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