test.rs

  1use crate::{
  2    elements::Empty, executor, platform, util::CwdBacktrace, Element, ElementBox, Entity,
  3    FontCache, Handle, LeakDetector, MutableAppContext, Platform, RenderContext, Subscription,
  4    TestAppContext, View,
  5};
  6use futures::StreamExt;
  7use parking_lot::Mutex;
  8use smol::channel;
  9use std::{
 10    fmt::Write,
 11    panic::{self, RefUnwindSafe},
 12    rc::Rc,
 13    sync::{
 14        atomic::{AtomicU64, Ordering::SeqCst},
 15        Arc,
 16    },
 17};
 18
 19#[cfg(test)]
 20#[ctor::ctor]
 21fn init_logger() {
 22    if std::env::var("RUST_LOG").is_ok() {
 23        env_logger::init();
 24    }
 25}
 26
 27// #[global_allocator]
 28// static ALLOC: dhat::Alloc = dhat::Alloc;
 29
 30pub fn run_test(
 31    mut num_iterations: u64,
 32    mut starting_seed: u64,
 33    max_retries: usize,
 34    detect_nondeterminism: bool,
 35    test_fn: &mut (dyn RefUnwindSafe
 36              + Fn(
 37        &mut MutableAppContext,
 38        Rc<platform::test::ForegroundPlatform>,
 39        Arc<executor::Deterministic>,
 40        u64,
 41    )),
 42    fn_name: String,
 43) {
 44    // let _profiler = dhat::Profiler::new_heap();
 45
 46    let is_randomized = num_iterations > 1;
 47    if is_randomized {
 48        if let Ok(value) = std::env::var("SEED") {
 49            starting_seed = value.parse().expect("invalid SEED variable");
 50        }
 51        if let Ok(value) = std::env::var("ITERATIONS") {
 52            num_iterations = value.parse().expect("invalid ITERATIONS variable");
 53        }
 54    }
 55
 56    let atomic_seed = AtomicU64::new(starting_seed as u64);
 57    let mut retries = 0;
 58
 59    loop {
 60        let result = panic::catch_unwind(|| {
 61            let foreground_platform = Rc::new(platform::test::foreground_platform());
 62            let platform = Arc::new(platform::test::platform());
 63            let font_system = platform.fonts();
 64            let font_cache = Arc::new(FontCache::new(font_system));
 65            let mut prev_runnable_history: Option<Vec<usize>> = None;
 66
 67            for _ in 0..num_iterations {
 68                let seed = atomic_seed.load(SeqCst);
 69
 70                if is_randomized {
 71                    dbg!(seed);
 72                }
 73
 74                let deterministic = executor::Deterministic::new(seed);
 75                let leak_detector = Arc::new(Mutex::new(LeakDetector::default()));
 76                let mut cx = TestAppContext::new(
 77                    foreground_platform.clone(),
 78                    platform.clone(),
 79                    deterministic.build_foreground(usize::MAX),
 80                    deterministic.build_background(),
 81                    font_cache.clone(),
 82                    leak_detector.clone(),
 83                    0,
 84                    fn_name.clone(),
 85                );
 86                cx.update(|cx| {
 87                    test_fn(cx, foreground_platform.clone(), deterministic.clone(), seed);
 88                });
 89
 90                cx.update(|cx| cx.remove_all_windows());
 91                deterministic.run_until_parked();
 92                cx.update(|cx| cx.clear_globals());
 93
 94                leak_detector.lock().detect();
 95
 96                if detect_nondeterminism {
 97                    let curr_runnable_history = deterministic.runnable_history();
 98                    if let Some(prev_runnable_history) = prev_runnable_history {
 99                        let mut prev_entries = prev_runnable_history.iter().fuse();
100                        let mut curr_entries = curr_runnable_history.iter().fuse();
101
102                        let mut nondeterministic = false;
103                        let mut common_history_prefix = Vec::new();
104                        let mut prev_history_suffix = Vec::new();
105                        let mut curr_history_suffix = Vec::new();
106                        loop {
107                            match (prev_entries.next(), curr_entries.next()) {
108                                (None, None) => break,
109                                (None, Some(curr_id)) => curr_history_suffix.push(*curr_id),
110                                (Some(prev_id), None) => prev_history_suffix.push(*prev_id),
111                                (Some(prev_id), Some(curr_id)) => {
112                                    if nondeterministic {
113                                        prev_history_suffix.push(*prev_id);
114                                        curr_history_suffix.push(*curr_id);
115                                    } else if prev_id == curr_id {
116                                        common_history_prefix.push(*curr_id);
117                                    } else {
118                                        nondeterministic = true;
119                                        prev_history_suffix.push(*prev_id);
120                                        curr_history_suffix.push(*curr_id);
121                                    }
122                                }
123                            }
124                        }
125
126                        if nondeterministic {
127                            let mut error = String::new();
128                            writeln!(&mut error, "Common prefix: {:?}", common_history_prefix)
129                                .unwrap();
130                            writeln!(&mut error, "Previous suffix: {:?}", prev_history_suffix)
131                                .unwrap();
132                            writeln!(&mut error, "Current suffix: {:?}", curr_history_suffix)
133                                .unwrap();
134
135                            let last_common_backtrace = common_history_prefix
136                                .last()
137                                .map(|runnable_id| deterministic.runnable_backtrace(*runnable_id));
138
139                            writeln!(
140                                &mut error,
141                                "Last future that ran on both executions: {:?}",
142                                last_common_backtrace.as_ref().map(CwdBacktrace)
143                            )
144                            .unwrap();
145                            panic!("Detected non-determinism.\n{}", error);
146                        }
147                    }
148                    prev_runnable_history = Some(curr_runnable_history);
149                }
150
151                if !detect_nondeterminism {
152                    atomic_seed.fetch_add(1, SeqCst);
153                }
154            }
155        });
156
157        match result {
158            Ok(_) => {
159                break;
160            }
161            Err(error) => {
162                if retries < max_retries {
163                    retries += 1;
164                    println!("retrying: attempt {}", retries);
165                } else {
166                    if is_randomized {
167                        eprintln!("failing seed: {}", atomic_seed.load(SeqCst));
168                    }
169                    panic::resume_unwind(error);
170                }
171            }
172        }
173    }
174}
175
176pub struct Observation<T> {
177    rx: channel::Receiver<T>,
178    _subscription: Subscription,
179}
180
181impl<T> futures::Stream for Observation<T> {
182    type Item = T;
183
184    fn poll_next(
185        mut self: std::pin::Pin<&mut Self>,
186        cx: &mut std::task::Context<'_>,
187    ) -> std::task::Poll<Option<Self::Item>> {
188        self.rx.poll_next_unpin(cx)
189    }
190}
191
192pub fn observe<T: Entity>(entity: &impl Handle<T>, cx: &mut TestAppContext) -> Observation<()> {
193    let (tx, rx) = smol::channel::unbounded();
194    let _subscription = cx.update(|cx| {
195        cx.observe(entity, move |_, _| {
196            let _ = smol::block_on(tx.send(()));
197        })
198    });
199
200    Observation { rx, _subscription }
201}
202
203pub fn subscribe<T: Entity>(
204    entity: &impl Handle<T>,
205    cx: &mut TestAppContext,
206) -> Observation<T::Event>
207where
208    T::Event: Clone,
209{
210    let (tx, rx) = smol::channel::unbounded();
211    let _subscription = cx.update(|cx| {
212        cx.subscribe(entity, move |_, event, _| {
213            let _ = smol::block_on(tx.send(event.clone()));
214        })
215    });
216
217    Observation { rx, _subscription }
218}
219
220pub struct EmptyView;
221
222impl Entity for EmptyView {
223    type Event = ();
224}
225
226impl View for EmptyView {
227    fn ui_name() -> &'static str {
228        "empty view"
229    }
230
231    fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
232        Element::boxed(Empty::new())
233    }
234}