Skip to main content

sui_testing/
expect.rs

1use std::path::Path;
2
3use sui_core::{Error, Result, SemanticsValue};
4
5use crate::{
6    diagnostics::format_failure,
7    locator::Locator,
8    screenshot::{diff_screenshot, read_png, screenshot_mismatch_paths, screenshots_match},
9};
10
11#[derive(Clone)]
12pub struct Expectation {
13    locator: Locator,
14    timeout: Option<f64>,
15}
16
17impl Expectation {
18    pub(crate) fn new(locator: Locator) -> Self {
19        Self {
20            locator,
21            timeout: None,
22        }
23    }
24
25    pub fn with_timeout(mut self, timeout: f64) -> Self {
26        self.timeout = Some(timeout.max(0.0));
27        self
28    }
29
30    pub fn to_be_visible(&self) -> Result<()> {
31        self.wait_for("to_be_visible", |locator, harness| {
32            let nodes = locator.resolve_all(harness)?;
33            Ok(nodes
34                .iter()
35                .find(|node| locator.selector().is_visible(node))
36                .map(|_| ()))
37        })
38    }
39
40    pub fn to_be_hidden(&self) -> Result<()> {
41        self.wait_for("to_be_hidden", |locator, harness| {
42            let nodes = locator.resolve_all(harness)?;
43            if nodes.is_empty()
44                || nodes
45                    .iter()
46                    .all(|node| !locator.selector().is_visible(node))
47            {
48                Ok(Some(()))
49            } else {
50                Ok(None)
51            }
52        })
53    }
54
55    pub fn to_be_focused(&self) -> Result<()> {
56        self.wait_for("to_be_focused", |locator, harness| {
57            let node = locator.resolve_unique(harness).ok();
58            Ok(node.filter(|node| node.state.focused).map(|_| ()))
59        })
60    }
61
62    pub fn to_have_text(&self, expected: impl AsRef<str>) -> Result<()> {
63        let expected = expected.as_ref().to_string();
64        self.wait_for("to_have_text", move |locator, harness| {
65            let node = locator.resolve_unique(harness).ok();
66            Ok(node
67                .filter(|node| {
68                    locator.selector().node_text(node).as_deref() == Some(expected.as_str())
69                })
70                .map(|_| ()))
71        })
72    }
73
74    pub fn to_have_value(&self, expected: impl AsRef<str>) -> Result<()> {
75        let expected = expected.as_ref().to_string();
76        self.wait_for("to_have_value", move |locator, harness| {
77            let node = locator.resolve_unique(harness).ok();
78            Ok(node
79                .filter(|node| {
80                    value_as_string(node.value.as_ref()).as_deref() == Some(expected.as_str())
81                })
82                .map(|_| ()))
83        })
84    }
85
86    pub fn to_have_count(&self, expected: usize) -> Result<()> {
87        self.wait_for("to_have_count", move |locator, harness| {
88            let count = locator.resolve_all(harness)?.len();
89            Ok((count == expected).then_some(()))
90        })
91    }
92
93    pub fn to_match_screenshot(&self, path: impl AsRef<Path>) -> Result<()> {
94        let path = path.as_ref().to_path_buf();
95        let expected = read_png(&path).map_err(|error| {
96            Error::new(format!(
97                "failed to read screenshot baseline {}: {}",
98                path.display(),
99                error.message()
100            ))
101        })?;
102        let timeout = self
103            .timeout
104            .unwrap_or_else(|| self.locator.default_timeout());
105        let mut harness = self.locator.harness().borrow_mut();
106        let actual = harness
107            .run_until(timeout, |harness| {
108                let actual = self.locator.capture_screenshot_from(harness)?;
109                Ok(screenshots_match(&expected, &actual).then_some(actual))
110            })
111            .or_else(|_| self.locator.capture_screenshot_from(&harness))?;
112
113        if screenshots_match(&expected, &actual) {
114            return Ok(());
115        }
116
117        let (actual_path, diff_path) = screenshot_mismatch_paths(&path);
118        actual.write_png(&actual_path)?;
119        diff_screenshot(&expected, &actual)?.write_png(&diff_path)?;
120        Err(Error::new(format!(
121            "screenshot assertion failed for {}. Wrote actual screenshot to {} and diff image to {}",
122            path.display(),
123            actual_path.display(),
124            diff_path.display()
125        )))
126    }
127
128    fn wait_for<F>(&self, action: &str, mut predicate: F) -> Result<()>
129    where
130        F: FnMut(&Locator, &crate::harness::Harness) -> Result<Option<()>>,
131    {
132        let timeout = self
133            .timeout
134            .unwrap_or_else(|| self.locator.default_timeout());
135        let mut harness = self.locator.harness().borrow_mut();
136        harness
137            .run_until(timeout, |harness| predicate(&self.locator, harness))
138            .map_err(|_| {
139                let snapshot = harness
140                    .snapshot(self.locator.window_id())
141                    .unwrap_or_else(|_| harness.fallback_snapshot(self.locator.window_id()));
142                Error::new(format_failure(
143                    action,
144                    &self.locator.describe(),
145                    &snapshot,
146                    &format!("timed out after {timeout:.3}s"),
147                ))
148            })
149    }
150}
151
152fn value_as_string(value: Option<&SemanticsValue>) -> Option<String> {
153    match value {
154        Some(SemanticsValue::Text(text)) => Some(text.clone()),
155        Some(SemanticsValue::Number(number)) => Some(number.to_string()),
156        Some(SemanticsValue::Range { value, .. }) => Some(value.to_string()),
157        None => None,
158    }
159}