use crate::{Entity, Subscription, TestAppContext, TestDispatcher, calculate_seeds};
use futures::StreamExt as _;
use proptest::prelude::{Just, Strategy, any};
use std::{
env,
panic::{self, RefUnwindSafe, UnwindSafe},
pin::Pin,
};
pub fn seed_strategy() -> impl Strategy<Value = u64> {
match std::env::var("SEED") {
Ok(val) => Just(val.parse().unwrap()).boxed(),
Err(_) => any::<u64>().no_shrink().boxed(),
}
}
pub fn apply_seed_to_proptest_config(
mut config: proptest::test_runner::Config,
) -> proptest::test_runner::Config {
let seed = env::var("SEED")
.ok()
.and_then(|val| val.parse::<u64>().ok())
.unwrap_or(0);
config.rng_seed = proptest::test_runner::RngSeed::Fixed(seed);
config
}
pub fn run_test_once<R>(
seed: u64,
test_fn: Box<dyn UnwindSafe + FnOnce(TestDispatcher) -> R>,
) -> R {
let result = panic::catch_unwind(|| {
let dispatcher = TestDispatcher::new(seed);
let scheduler = dispatcher.scheduler().clone();
let res = test_fn(dispatcher);
scheduler.end_test();
res
});
match result {
Ok(r) => r,
Err(e) => panic::resume_unwind(e),
}
}
pub fn run_test(
num_iterations: usize,
explicit_seeds: &[u64],
max_retries: usize,
test_fn: &mut (dyn RefUnwindSafe + Fn(TestDispatcher, u64)),
on_fail_fn: Option<fn()>,
) {
let (seeds, is_multiple_runs) = calculate_seeds(num_iterations as u64, explicit_seeds);
for seed in seeds {
let mut attempt = 0;
loop {
if is_multiple_runs {
eprintln!("seed = {seed}");
}
let result = panic::catch_unwind(|| {
let dispatcher = TestDispatcher::new(seed);
let scheduler = dispatcher.scheduler().clone();
test_fn(dispatcher, seed);
scheduler.end_test();
});
match result {
Ok(_) => break,
Err(error) => {
if attempt < max_retries {
println!("attempt {} failed, retrying", attempt);
attempt += 1;
std::mem::forget(error);
} else {
if is_multiple_runs {
eprintln!("failing seed: {seed}");
eprintln!(
"You can rerun from this seed by setting the environmental variable SEED to {seed}"
);
}
if let Some(on_fail_fn) = on_fail_fn {
on_fail_fn()
}
panic::resume_unwind(error);
}
}
}
}
}
}
pub struct Observation<T> {
rx: Pin<Box<async_channel::Receiver<T>>>,
_subscription: Subscription,
}
impl<T: 'static> futures::Stream for Observation<T> {
type Item = T;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
self.rx.poll_next_unpin(cx)
}
}
pub fn observe<T: 'static>(entity: &Entity<T>, cx: &mut TestAppContext) -> Observation<()> {
let (tx, rx) = async_channel::unbounded();
let _subscription = cx.update(|cx| {
cx.observe(entity, move |_, _| {
let _ = gpui::block_on(tx.send(()));
})
});
let rx = Box::pin(rx);
Observation { rx, _subscription }
}