Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T02:34:45.509Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

test.rs

221 lines · 7.7 KB · rust
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 proptest::prelude::{Just, Strategy, any};
31use std::{
32    env,
33    panic::{self, RefUnwindSafe, UnwindSafe},
34    pin::Pin,
35};
36
37/// Strategy injected into `#[gpui::property_test]` tests to control the seed
38/// given to the scheduler. Doesn't shrink, since all scheduler seeds are
39/// equivalent in complexity. If `$SEED` is set, it always uses that value.
40///
41/// Note: this function is not intended to be used directly. Rather, it is
42/// public so that it can be used from the `property_test` macro.
43pub fn seed_strategy() -> impl Strategy<Value = u64> {
44    match std::env::var("SEED") {
45        Ok(val) => Just(val.parse().unwrap()).boxed(),
46        Err(_) => any::<u64>().no_shrink().boxed(),
47    }
48}
49
50/// Applies a fixed RNG seed to a proptest config so that case generation
51/// is deterministic. Uses `$SEED` if set, otherwise defaults to `0`.
52/// This bridges the GPUI `SEED` env var to proptest's RNG seed, so that
53/// a single variable controls both the scheduler seed and case generation.
54///
55/// Note: this function is not intended to be used directly. Rather, it is
56/// public so that it can be used from the `property_test` macro.
57pub fn apply_seed_to_proptest_config(
58    mut config: proptest::test_runner::Config,
59) -> proptest::test_runner::Config {
60    let seed = env::var("SEED")
61        .ok()
62        .and_then(|val| val.parse::<u64>().ok())
63        .unwrap_or(0);
64    config.rng_seed = proptest::test_runner::RngSeed::Fixed(seed);
65    config
66}
67
68/// Similar to [`run_test`], but only runs the callback once, allowing
69/// [`FnOnce`] callbacks. This is intended for use with the
70/// `gpui::property_test` macro and generally should not be used directly.
71///
72/// Doesn't support many features of [`run_test`], since these are provided by
73/// proptest.
74pub fn run_test_once<R>(
75    seed: u64,
76    test_fn: Box<dyn UnwindSafe + FnOnce(TestDispatcher) -> R>,
77) -> R {
78    let result = panic::catch_unwind(|| {
79        let dispatcher = TestDispatcher::new(seed);
80        let scheduler = dispatcher.scheduler().clone();
81        let res = test_fn(dispatcher);
82        scheduler.end_test();
83        res
84    });
85
86    match result {
87        Ok(r) => r,
88        Err(e) => panic::resume_unwind(e),
89    }
90}
91
92/// Run the given test function with the configured parameters.
93/// This is intended for use with the `gpui::test` macro
94/// and generally should not be used directly.
95pub fn run_test(
96    num_iterations: usize,
97    explicit_seeds: &[u64],
98    max_retries: usize,
99    test_fn: &mut (dyn RefUnwindSafe + Fn(TestDispatcher, u64)),
100    on_fail_fn: Option<fn()>,
101) {
102    let (seeds, is_multiple_runs) = calculate_seeds(num_iterations as u64, explicit_seeds);
103
104    for seed in seeds {
105        let mut attempt = 0;
106        loop {
107            if is_multiple_runs {
108                eprintln!("seed = {seed}");
109            }
110            let result = panic::catch_unwind(|| {
111                let dispatcher = TestDispatcher::new(seed);
112                let scheduler = dispatcher.scheduler().clone();
113                test_fn(dispatcher, seed);
114                scheduler.end_test();
115            });
116
117            match result {
118                Ok(_) => break,
119                Err(error) => {
120                    if attempt < max_retries {
121                        println!("attempt {} failed, retrying", attempt);
122                        attempt += 1;
123                        // The panic payload might itself trigger an unwind on drop:
124                        // https://doc.rust-lang.org/std/panic/fn.catch_unwind.html#notes
125                        std::mem::forget(error);
126                    } else {
127                        if is_multiple_runs {
128                            eprintln!("failing seed: {seed}");
129                            eprintln!(
130                                "You can rerun from this seed by setting the environmental variable SEED to {seed}"
131                            );
132                        }
133                        if let Some(on_fail_fn) = on_fail_fn {
134                            on_fail_fn()
135                        }
136                        panic::resume_unwind(error);
137                    }
138                }
139            }
140        }
141    }
142}
143
144fn calculate_seeds(
145    iterations: u64,
146    explicit_seeds: &[u64],
147) -> (impl Iterator<Item = u64> + '_, bool) {
148    let iterations = env::var("ITERATIONS")
149        .ok()
150        .map(|var| var.parse().expect("invalid ITERATIONS variable"))
151        .unwrap_or(iterations);
152
153    let env_num = env::var("SEED")
154        .map(|seed| seed.parse().expect("invalid SEED variable as integer"))
155        .ok();
156
157    let empty_range = || 0..0;
158
159    let iter = {
160        let env_range = if let Some(env_num) = env_num {
161            env_num..env_num + 1
162        } else {
163            empty_range()
164        };
165
166        // if `iterations` is 1 and !(`explicit_seeds` is non-empty || `SEED` is set), then add     the run `0`
167        // if `iterations` is 1 and  (`explicit_seeds` is non-empty || `SEED` is set), then discard the run `0`
168        // if `iterations` isn't 1 and `SEED` is set, do `SEED..SEED+iterations`
169        // otherwise, do `0..iterations`
170        let iterations_range = match (iterations, env_num) {
171            (1, None) if explicit_seeds.is_empty() => 0..1,
172            (1, None) | (1, Some(_)) => empty_range(),
173            (iterations, Some(env)) => env..env + iterations,
174            (iterations, None) => 0..iterations,
175        };
176
177        // if `SEED` is set, ignore `explicit_seeds`
178        let explicit_seeds = if env_num.is_some() {
179            &[]
180        } else {
181            explicit_seeds
182        };
183
184        env_range
185            .chain(iterations_range)
186            .chain(explicit_seeds.iter().copied())
187    };
188    let is_multiple_runs = iter.clone().nth(1).is_some();
189    (iter, is_multiple_runs)
190}
191
192/// A test struct for converting an observation callback into a stream.
193pub struct Observation<T> {
194    rx: Pin<Box<async_channel::Receiver<T>>>,
195    _subscription: Subscription,
196}
197
198impl<T: 'static> futures::Stream for Observation<T> {
199    type Item = T;
200
201    fn poll_next(
202        mut self: std::pin::Pin<&mut Self>,
203        cx: &mut std::task::Context<'_>,
204    ) -> std::task::Poll<Option<Self::Item>> {
205        self.rx.poll_next_unpin(cx)
206    }
207}
208
209/// observe returns a stream of the change events from the given `Entity`
210pub fn observe<T: 'static>(entity: &Entity<T>, cx: &mut TestAppContext) -> Observation<()> {
211    let (tx, rx) = async_channel::unbounded();
212    let _subscription = cx.update(|cx| {
213        cx.observe(entity, move |_, _| {
214            let _ = gpui::block_on(tx.send(()));
215        })
216    });
217    let rx = Box::pin(rx);
218
219    Observation { rx, _subscription }
220}
221
Served at tenant.openagents/omega Member data and write actions are omitted.