Skip to main content

sui_testing/
app.rs

1use std::{cell::RefCell, rc::Rc};
2
3use sui_core::{Error, MotionPreference, Result};
4use sui_render_wgpu::{DisplayCapabilities, WgpuExternalTextureRegistry};
5use sui_runtime::{
6    Runtime, set_app_motion_preference, set_motion_time_scale, set_window_render_options,
7};
8
9/// How far [`TestApp::settle_animations`] advances time per frame.
10const SETTLE_STEP: f64 = 1.0 / 60.0;
11
12use crate::{harness::Harness, window::TestWindow};
13
14/// Options for a [`TestApp`], from [`TestApp::builder`].
15///
16/// Apps run headless unless asked to run live: their windows render
17/// offscreen, sharing one GPU device, so tests run in parallel. A live app
18/// opens real windows on the platform's event loop, one app at a time; ask
19/// for one with [`Self::live`] or [`Self::visible`], or run every test live
20/// by setting `SUI_TEST_BACKEND=live`.
21pub struct TestAppBuilder<F> {
22    build: F,
23    vsync_enabled: bool,
24    visible: bool,
25    live: bool,
26    display_capabilities: Option<DisplayCapabilities>,
27}
28
29impl<F, A> TestAppBuilder<F>
30where
31    F: FnOnce() -> A + Send + 'static,
32    A: IntoTestRuntime,
33{
34    /// Wait for vertical sync when the app runs live and its windows are
35    /// shown. Hidden windows render offscreen and never present.
36    pub fn vsync(mut self, enabled: bool) -> Self {
37        self.vsync_enabled = enabled;
38        self
39    }
40
41    /// Show the app's windows on screen, which runs it live.
42    pub fn visible(mut self, visible: bool) -> Self {
43        self.visible = visible;
44        self
45    }
46
47    /// Run the app in real windows on the platform's event loop, as frame
48    /// pacing and native input tests need, rather than headless. Live apps
49    /// run one at a time. Where there is no display, the app runs headless.
50    pub fn live(mut self, live: bool) -> Self {
51        self.live = live;
52        self
53    }
54
55    /// Run the app as if its windows were on a display with `capabilities`,
56    /// whatever this machine's screens are: output strategies, diagnostics,
57    /// captures, and HDR theme styling follow them. The app runs headless,
58    /// so nothing but `capabilities` decides its output.
59    pub fn display_capabilities(mut self, capabilities: DisplayCapabilities) -> Self {
60        self.display_capabilities = Some(capabilities);
61        self
62    }
63
64    pub fn launch(self) -> Result<TestApp> {
65        let harness = match self.display_capabilities {
66            Some(capabilities) => Harness::new_headless_with_display(
67                (self.build)().into_test_runtime()?,
68                capabilities,
69                30.0,
70            )?,
71            None if (self.live || self.visible || live_by_default()) && display_available() => {
72                let build = self.build;
73                Harness::new_live_with_options(
74                    move || build().into_test_runtime(),
75                    self.vsync_enabled,
76                    self.visible,
77                )?
78            }
79            None => Harness::new_headless_with_timeout((self.build)().into_test_runtime()?, 30.0)?,
80        };
81        Ok(TestApp {
82            harness: Rc::new(RefCell::new(harness)),
83        })
84    }
85}
86
87pub trait IntoTestRuntime {
88    fn into_test_runtime(self) -> Result<Runtime>;
89}
90
91impl IntoTestRuntime for Runtime {
92    fn into_test_runtime(self) -> Result<Runtime> {
93        Ok(self)
94    }
95}
96
97impl IntoTestRuntime for sui_runtime::Application {
98    fn into_test_runtime(self) -> Result<Runtime> {
99        self.build()
100    }
101}
102
103impl IntoTestRuntime for sui::Application {
104    fn into_test_runtime(self) -> Result<Runtime> {
105        let initial_window_render_options = self.initial_window_render_options();
106        let runtime = self.build()?;
107        if let Some(options) = initial_window_render_options {
108            for window_id in runtime.window_ids() {
109                set_window_render_options(window_id, options);
110            }
111        }
112        Ok(runtime)
113    }
114}
115
116impl IntoTestRuntime for Result<Runtime> {
117    fn into_test_runtime(self) -> Result<Runtime> {
118        self
119    }
120}
121
122#[derive(Clone)]
123pub struct TestApp {
124    pub(crate) harness: Rc<RefCell<Harness>>,
125}
126
127impl TestApp {
128    pub fn new<F, A>(build: F) -> Result<Self>
129    where
130        F: FnOnce() -> A + Send + 'static,
131        A: IntoTestRuntime,
132    {
133        Self::new_with_options(build, true, false)
134    }
135
136    pub fn new_with_vsync<F, A>(build: F, vsync_enabled: bool) -> Result<Self>
137    where
138        F: FnOnce() -> A + Send + 'static,
139        A: IntoTestRuntime,
140    {
141        Self::new_with_options(build, vsync_enabled, false)
142    }
143
144    pub fn new_with_options<F, A>(build: F, vsync_enabled: bool, visible: bool) -> Result<Self>
145    where
146        F: FnOnce() -> A + Send + 'static,
147        A: IntoTestRuntime,
148    {
149        Self::builder(build)
150            .vsync(vsync_enabled)
151            .visible(visible)
152            .launch()
153    }
154
155    /// Start configuring a test app built by `build`.
156    pub fn builder<F, A>(build: F) -> TestAppBuilder<F>
157    where
158        F: FnOnce() -> A + Send + 'static,
159        A: IntoTestRuntime,
160    {
161        TestAppBuilder {
162            build,
163            vsync_enabled: true,
164            visible: false,
165            live: false,
166            display_capabilities: None,
167        }
168    }
169
170    pub fn new_no_vsync<F, A>(build: F) -> Result<Self>
171    where
172        F: FnOnce() -> A + Send + 'static,
173        A: IntoTestRuntime,
174    {
175        Self::new_with_vsync(build, false)
176    }
177
178    pub fn new_visible_no_vsync<F, A>(build: F) -> Result<Self>
179    where
180        F: FnOnce() -> A + Send + 'static,
181        A: IntoTestRuntime,
182    {
183        Self::new_with_options(build, false, true)
184    }
185
186    pub fn from_runtime(runtime: Runtime) -> Result<Self> {
187        let harness = Rc::new(RefCell::new(Harness::new_headless(runtime)?));
188        Ok(Self { harness })
189    }
190
191    /// Build a headless test harness that can resolve app-owned WGPU textures.
192    pub fn from_runtime_with_external_texture_registry(
193        runtime: Runtime,
194        registry: WgpuExternalTextureRegistry,
195    ) -> Result<Self> {
196        let harness = Rc::new(RefCell::new(
197            Harness::new_headless_with_external_texture_registry(runtime, registry)?,
198        ));
199        Ok(Self { harness })
200    }
201
202    pub fn from_runtime_with_frame_budget(runtime: Runtime, initial_frames: usize) -> Result<Self> {
203        let harness = Rc::new(RefCell::new(Harness::new_headless_with_frame_budget(
204            runtime,
205            initial_frames,
206        )?));
207        Ok(Self { harness })
208    }
209
210    /// How many seconds waits such as [`Self::run_until_idle`] allow before
211    /// failing. Infinity waits without a deadline.
212    pub fn set_default_timeout(&self, timeout: f64) -> Result<()> {
213        if timeout.is_nan() || timeout < 0.0 {
214            return Err(Error::new(format!(
215                "default timeout must be a number of seconds >= 0, not {timeout}"
216            )));
217        }
218
219        self.harness.borrow_mut().set_default_timeout(timeout);
220        Ok(())
221    }
222
223    pub fn default_timeout(&self) -> f64 {
224        self.harness.borrow().default_timeout()
225    }
226
227    pub fn run_until_idle(&self) -> Result<()> {
228        self.harness.borrow_mut().run_until_idle()
229    }
230
231    pub fn pump_frames(&self, frames: usize) -> Result<()> {
232        self.harness.borrow_mut().pump_frames(frames)
233    }
234
235    pub fn advance_time(&self, delta: f64) -> Result<()> {
236        self.harness.borrow_mut().advance_time(delta)
237    }
238
239    /// Override the motion preference of the app under test, or pass `None`
240    /// to follow the system preference, which tests treat as full motion.
241    pub fn set_motion_preference(&self, preference: Option<MotionPreference>) -> Result<()> {
242        self.harness
243            .borrow_mut()
244            .with_runtime(move |_| set_app_motion_preference(preference))
245    }
246
247    /// Play the app's transitions at `time_scale` speed.
248    pub fn set_motion_time_scale(&self, time_scale: f32) -> Result<()> {
249        self.harness
250            .borrow_mut()
251            .with_runtime(move |_| set_motion_time_scale(time_scale))
252    }
253
254    /// Whether any window still has a transition running.
255    pub fn has_running_animations(&self) -> Result<bool> {
256        self.harness.borrow_mut().with_runtime(|runtime| {
257            runtime.window_ids().into_iter().any(|window_id| {
258                runtime
259                    .has_pending_animation_frames(window_id)
260                    .unwrap_or(false)
261            })
262        })
263    }
264
265    /// Advance time frame by frame until every transition has finished, and
266    /// return how many seconds that took. Fails after ten seconds, which
267    /// usually means an animation repeats forever.
268    pub fn settle_animations(&self) -> Result<f64> {
269        self.settle_animations_within(10.0)
270    }
271
272    /// Like [`TestApp::settle_animations`], failing after `limit` seconds.
273    pub fn settle_animations_within(&self, limit: f64) -> Result<f64> {
274        let mut elapsed = 0.0;
275        while self.has_running_animations()? {
276            if elapsed >= limit {
277                return Err(Error::new(format!(
278                    "animations were still running after {limit} s"
279                )));
280            }
281            self.advance_time(SETTLE_STEP)?;
282            elapsed += SETTLE_STEP;
283        }
284        Ok(elapsed)
285    }
286
287    /// Sample `probe` now and then every `step` seconds for `duration`
288    /// seconds, returning `(elapsed, value)` pairs, to assert on the shape
289    /// of a transition rather than only its end state.
290    pub fn record_motion<T>(
291        &self,
292        duration: f64,
293        step: f64,
294        mut probe: impl FnMut() -> Result<T>,
295    ) -> Result<Vec<(f64, T)>> {
296        if step <= 0.0 || !step.is_finite() {
297            return Err(Error::new("motion sampling step must be > 0"));
298        }
299        if !(duration.is_finite() && duration >= 0.0) {
300            return Err(Error::new(format!(
301                "motion sampling duration must be a finite number of seconds >= 0, not {duration}"
302            )));
303        }
304        let mut samples = vec![(0.0, probe()?)];
305        let mut elapsed = 0.0;
306        while elapsed + step <= duration + step * 1.0e-6 {
307            self.advance_time(step)?;
308            elapsed += step;
309            samples.push((elapsed, probe()?));
310        }
311        Ok(samples)
312    }
313
314    pub fn windows(&self) -> Result<Vec<TestWindow>> {
315        let window_ids = self.harness.borrow().window_ids();
316        Ok(window_ids
317            .into_iter()
318            .map(|window_id| TestWindow::new(Rc::clone(&self.harness), window_id))
319            .collect())
320    }
321
322    pub fn main_window(&self) -> Result<TestWindow> {
323        let window_id = self
324            .harness
325            .borrow()
326            .window_ids()
327            .into_iter()
328            .next()
329            .ok_or_else(|| Error::new("test app did not create any windows"))?;
330        Ok(TestWindow::new(Rc::clone(&self.harness), window_id))
331    }
332
333    pub fn window_by_title(&self, title: &str) -> Result<TestWindow> {
334        let window_id = self
335            .harness
336            .borrow()
337            .window_id_by_title(title)
338            .ok_or_else(|| Error::new(format!("no test window found with title \"{title}\"")))?;
339        Ok(TestWindow::new(Rc::clone(&self.harness), window_id))
340    }
341}
342
343/// Whether `SUI_TEST_BACKEND=live` asks for every app to run live.
344fn live_by_default() -> bool {
345    std::env::var("SUI_TEST_BACKEND").as_deref() == Ok("live")
346}
347
348fn display_available() -> bool {
349    #[cfg(target_os = "linux")]
350    {
351        std::env::var_os("WAYLAND_DISPLAY").is_some()
352            || std::env::var_os("WAYLAND_SOCKET").is_some()
353            || std::env::var_os("DISPLAY").is_some()
354    }
355    #[cfg(not(target_os = "linux"))]
356    {
357        true
358    }
359}