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