Skip to main content

yew_e2e/test_driver/
capture.rs

1//! Screenshots and downloads.
2
3use anyhow::Result;
4
5use crate::TestDriver;
6
7impl TestDriver {
8    /// A screenshot of the whole page as the PNG the browser hands back, for a
9    /// test that reads a frame rather than writing one out. Taken whether or
10    /// not `E2E_SHOTS` is set, since an assertion that measures a frame has to
11    /// have one on every run rather than only when somebody is looking.
12    pub async fn screenshot_png(&self) -> Result<Vec<u8>> {
13        tracing::trace!("Taking a screenshot");
14        Ok(self.inner.screenshot_as_png().await?)
15    }
16
17    /// Write a screenshot of the whole page to `path`.
18    pub async fn screenshot(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
19        std::fs::write(path, self.screenshot_png().await?)?;
20        Ok(())
21    }
22
23    /// The same, into `$E2E_SHOTS/<name>.png`, and nothing at all when that is
24    /// unset. Left in a test rather than added and removed, since it costs nothing
25    /// on an ordinary run.
26    ///
27    /// **`E2E_SHOTS` is a directory, and it reads like a flag.** A relative one
28    /// is taken under `target/e2e-shots`, where everything else the suite leaves
29    /// behind goes — so `E2E_SHOTS=1`, which is what a hand types when it means
30    /// *yes*, writes to `target/e2e-shots/1` rather than making a directory
31    /// called `1` in whatever the test process's working directory happens to
32    /// be, which under cargo is the package, in the checkout.
33    ///
34    /// ```text
35    /// E2E_SHOTS=1 cargo test -p app-e2e -- cart::
36    /// E2E_SHOTS=/tmp/shots cargo test -p app-e2e -- cart::
37    /// ```
38    pub async fn snapshot(&self, name: &str) -> Result<()> {
39        let Some(dir) = std::env::var_os("E2E_SHOTS") else {
40            return Ok(());
41        };
42
43        let dir = std::path::PathBuf::from(dir);
44
45        let dir = match dir.is_absolute() {
46            true => dir,
47            false => crate::dist::target_dir()?.join("e2e-shots").join(dir),
48        };
49
50        std::fs::create_dir_all(&dir)?;
51
52        let path = dir.join(format!("{name}.png"));
53        tracing::info!(path = %path.display(), "Writing snapshot");
54        self.screenshot(&path).await
55    }
56}