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 if detect_nondeterminism {
76 deterministic.enable_runnable_backtrace();
77 }
78
79 let leak_detector = Arc::new(Mutex::new(LeakDetector::default()));
80 let mut cx = TestAppContext::new(
81 foreground_platform.clone(),
82 platform.clone(),
83 deterministic.build_foreground(usize::MAX),
84 deterministic.build_background(),
85 font_cache.clone(),
86 leak_detector.clone(),
87 0,
88 fn_name.clone(),
89 );
90 cx.update(|cx| {
91 test_fn(cx, foreground_platform.clone(), deterministic.clone(), seed);
92 });
93
94 cx.update(|cx| cx.remove_all_windows());
95 deterministic.run_until_parked();
96 cx.update(|cx| cx.clear_globals());
97
98 leak_detector.lock().detect();
99
100 if detect_nondeterminism {
101 let curr_runnable_history = deterministic.runnable_history();
102 if let Some(prev_runnable_history) = prev_runnable_history {
103 let mut prev_entries = prev_runnable_history.iter().fuse();
104 let mut curr_entries = curr_runnable_history.iter().fuse();
105
106 let mut nondeterministic = false;
107 let mut common_history_prefix = Vec::new();
108 let mut prev_history_suffix = Vec::new();
109 let mut curr_history_suffix = Vec::new();
110 loop {
111 match (prev_entries.next(), curr_entries.next()) {
112 (None, None) => break,
113 (None, Some(curr_id)) => curr_history_suffix.push(*curr_id),
114 (Some(prev_id), None) => prev_history_suffix.push(*prev_id),
115 (Some(prev_id), Some(curr_id)) => {
116 if nondeterministic {
117 prev_history_suffix.push(*prev_id);
118 curr_history_suffix.push(*curr_id);
119 } else if prev_id == curr_id {
120 common_history_prefix.push(*curr_id);
121 } else {
122 nondeterministic = true;
123 prev_history_suffix.push(*prev_id);
124 curr_history_suffix.push(*curr_id);
125 }
126 }
127 }
128 }
129
130 if nondeterministic {
131 let mut error = String::new();
132 writeln!(&mut error, "Common prefix: {:?}", common_history_prefix)
133 .unwrap();
134 writeln!(&mut error, "Previous suffix: {:?}", prev_history_suffix)
135 .unwrap();
136 writeln!(&mut error, "Current suffix: {:?}", curr_history_suffix)
137 .unwrap();
138
139 let last_common_backtrace = common_history_prefix
140 .last()
141 .map(|runnable_id| deterministic.runnable_backtrace(*runnable_id));
142
143 writeln!(
144 &mut error,
145 "Last future that ran on both executions: {:?}",
146 last_common_backtrace.as_ref().map(CwdBacktrace)
147 )
148 .unwrap();
149 panic!("Detected non-determinism.\n{}", error);
150 }
151 }
152 prev_runnable_history = Some(curr_runnable_history);
153 }
154
155 if !detect_nondeterminism {
156 atomic_seed.fetch_add(1, SeqCst);
157 }
158 }
159 });
160
161 match result {
162 Ok(_) => {
163 break;
164 }
165 Err(error) => {
166 if retries < max_retries {
167 retries += 1;
168 println!("retrying: attempt {}", retries);
169 } else {
170 if is_randomized {
171 eprintln!("failing seed: {}", atomic_seed.load(SeqCst));
172 }
173 panic::resume_unwind(error);
174 }
175 }
176 }
177 }
178}
179
180pub struct Observation<T> {
181 rx: channel::Receiver<T>,
182 _subscription: Subscription,
183}
184
185impl<T> futures::Stream for Observation<T> {
186 type Item = T;
187
188 fn poll_next(
189 mut self: std::pin::Pin<&mut Self>,
190 cx: &mut std::task::Context<'_>,
191 ) -> std::task::Poll<Option<Self::Item>> {
192 self.rx.poll_next_unpin(cx)
193 }
194}
195
196pub fn observe<T: Entity>(entity: &impl Handle<T>, cx: &mut TestAppContext) -> Observation<()> {
197 let (tx, rx) = smol::channel::unbounded();
198 let _subscription = cx.update(|cx| {
199 cx.observe(entity, move |_, _| {
200 let _ = smol::block_on(tx.send(()));
201 })
202 });
203
204 Observation { rx, _subscription }
205}
206
207pub fn subscribe<T: Entity>(
208 entity: &impl Handle<T>,
209 cx: &mut TestAppContext,
210) -> Observation<T::Event>
211where
212 T::Event: Clone,
213{
214 let (tx, rx) = smol::channel::unbounded();
215 let _subscription = cx.update(|cx| {
216 cx.subscribe(entity, move |_, event, _| {
217 let _ = smol::block_on(tx.send(event.clone()));
218 })
219 });
220
221 Observation { rx, _subscription }
222}
223
224pub struct EmptyView;
225
226impl Entity for EmptyView {
227 type Event = ();
228}
229
230impl View for EmptyView {
231 fn ui_name() -> &'static str {
232 "empty view"
233 }
234
235 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
236 Element::boxed(Empty::new())
237 }
238}