Skip to main content

yew_e2e/
lib.rs

1//! [<img alt="github" src="https://img.shields.io/badge/github-udoprog/yew--e2e-8da0cb?style=for-the-badge&logo=github" height="20">](https://github.com/udoprog/yew-e2e)
2//! [<img alt="crates.io" src="https://img.shields.io/crates/v/yew-e2e.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/yew-e2e)
3//! [<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-yew--e2e-66c2a5?style=for-the-badge&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K" height="20">](https://docs.rs/yew-e2e)
4//!
5//! Browser tests for web applications, and the runner that drives them.
6//!
7//! Written for [Yew] applications built with [Trunk], though nothing here depends
8//! on either: a suite names the [`Fixture`] that starts the application under test
9//! for every test, and each test is handed a [`TestDriver`] pointed at it.
10//!
11//! What the runner takes care of:
12//!
13//! * One binary and one entrypoint in place of libtest, declared with
14//!   [`harness!`], running several browsers at once (`--parallel`).
15//! * Firefox through `geckodriver` or Chrome through `chromedriver`, with a
16//!   `chromedriver` matching the installed Chrome fetched when none is on the
17//!   `PATH`.
18//! * The frontend built once per run with `trunk build`, or served from `E2E_DIST`
19//!   when it is already built.
20//! * A record of every run, so `--last-session` runs only what did not pass.
21//! * One run at a time per build directory (`--lock`).
22//! * Waits that say what they were waiting for when they give up, and a report of
23//!   what the page was doing when it never came up.
24//!
25//! <br>
26//!
27//! ## Example
28//!
29//! A test is an `async fn` taking the driver and the fixture. The fixture starts
30//! the application for one test and says where the browser should go:
31//!
32//! ```no_run
33//! use yew_e2e::prelude::*;
34//! use yew_e2e::{Config, Fixture, Frontend};
35//!
36//! struct App {
37//!     url: String,
38//! }
39//!
40//! impl Fixture for App {
41//!     type Setup = ();
42//!
43//!     fn config() -> Config {
44//!         Config::default().frontend(Frontend::None)
45//!     }
46//!
47//!     async fn start((): ()) -> Result<Self> {
48//!         // Start the application here, on a port of its own.
49//!         Ok(App { url: String::from("http://127.0.0.1:8080") })
50//!     }
51//!
52//!     fn url(&self) -> String {
53//!         self.url.clone()
54//!     }
55//!
56//!     async fn quit(self) -> Result<()> {
57//!         Ok(())
58//!     }
59//! }
60//!
61//! mod greeting {
62//!     use yew_e2e::prelude::*;
63//!
64//!     pub async fn says_hello<F>(driver: &mut TestDriver, _: &mut F) -> Result<()> {
65//!         driver.wait_texts("h1", ["Hello"]).await
66//!     }
67//! }
68//!
69//! yew_e2e::harness! {
70//!     App;
71//!     greeting::{says_hello},
72//! }
73//! ```
74//!
75//! The suite is registered as a test without libtest's harness:
76//!
77//! ```toml
78//! [[test]]
79//! name = "e2e"
80//! path = "tests/e2e/main.rs"
81//! harness = false
82//! ```
83//!
84//! A test that needs something other than the bare fixture names it in
85//! parentheses after its name, each word setting a `bool` field of the fixture's
86//! `Setup`:
87//!
88//! ```ignore
89//! yew_e2e::harness! {
90//!     App;
91//!     cart::{adds_an_item, removes_an_item},
92//!     login::{remembers_the_user(signed_in)},
93//! }
94//! ```
95//!
96//! [`examples/static_page.rs`] is a suite that runs as it is, against a page its
97//! fixture serves itself:
98//!
99//! ```sh
100//! cargo run -p yew-e2e --example static_page
101//! ```
102//!
103//! <br>
104//!
105//! ## The frontend
106//!
107//! By default the fixture's frontend is built once per run with `trunk build`, in
108//! the workspace root, into `target/e2e-dist`. [`dist()`] says where it is, for
109//! the fixture to serve. [`Frontend::Trunk(dir)`] runs it somewhere else under
110//! the workspace root, and [`Frontend::None`] builds nothing, for a fixture that
111//! serves its own pages.
112//!
113//! Everything else a run leaves behind goes under the build directory too: the
114//! record of every run in `target/e2e-sessions`, the run lock, a fetched
115//! `chromedriver` in `target/e2e`. Two suites sharing one build directory give
116//! each other room with [`Config::sessions_dir`] and [`Config::lock_name`].
117//!
118//! <br>
119//!
120//! ## Running
121//!
122//! ```sh
123//! cargo test -p app-e2e                      # everything
124//! cargo test -p app-e2e -- cart::            # everything whose name contains cart::
125//! cargo test -p app-e2e -- --exact cart::adds_an_item
126//! cargo test -p app-e2e -- --list            # the names, one per line, on stdout
127//! cargo test -p app-e2e -- --last-session    # what did not pass last time
128//! ```
129//!
130//! | Flag | |
131//! |---|---|
132//! | `-j`, `--parallel N` | How many tests run at once, each in its own browser. Defaults to 2. |
133//! | `--headed` | Show the browsers. |
134//! | `--browser firefox\|chrome` | Which browser to drive. Detected where not given. |
135//! | `--exact` | Filters match whole names rather than parts of them. |
136//! | `--list` | List the selected tests and run nothing. |
137//! | `--allow-empty` | A run that selects nothing passes rather than fails. |
138//! | `--last-session`, `--session NAME` | Run only what did not pass in that session. |
139//! | `--timeout SECONDS` | How long one test may run. Defaults to 30; 0 waits for ever. |
140//! | `--grace SECONDS` | How long a running test is given to finish after Ctrl-C or SIGTERM. |
141//! | `--lock target\|project\|none` | Which other runs this one waits for: those in the same build directory (the default), every worktree of the Git project, or none. |
142//! | `--lock-wait SECONDS` | How long to wait for that lock. |
143//!
144//! | Variable | |
145//! |---|---|
146//! | `E2E_HEADED` | As `--headed`. |
147//! | `E2E_BROWSER` | As `--browser`. |
148//! | `E2E_DIST` | A frontend that is already built, served in place of building one. |
149//! | `E2E_THEME` | `dark` or `light`, for the colour scheme the browser reports (Firefox). |
150//! | `E2E_MOTION` | `reduce` or `normal`, for the motion preference the browser reports (Firefox). |
151//! | `E2E_SCALE` | The device pixel ratio the browser reports. |
152//! | `E2E_SHOTS` | Where [`TestDriver::snapshot`] writes; relative to `target/e2e-shots`. |
153//!
154//! [`Config::lock_name`]: https://docs.rs/yew-e2e/latest/yew_e2e/struct.Config.html#method.lock_name
155//! [`Config::sessions_dir`]: https://docs.rs/yew-e2e/latest/yew_e2e/struct.Config.html#method.sessions_dir
156//! [`dist()`]: https://docs.rs/yew-e2e/latest/yew_e2e/fn.dist.html
157//! [`examples/static_page.rs`]: https://github.com/udoprog/yew-e2e/blob/main/examples/static_page.rs
158//! [`Fixture`]: https://docs.rs/yew-e2e/latest/yew_e2e/trait.Fixture.html
159//! [`Frontend::None`]: https://docs.rs/yew-e2e/latest/yew_e2e/enum.Frontend.html#variant.None
160//! [`Frontend::Trunk(dir)`]: https://docs.rs/yew-e2e/latest/yew_e2e/enum.Frontend.html#variant.Trunk
161//! [`harness!`]: https://docs.rs/yew-e2e/latest/yew_e2e/macro.harness.html
162//! [`TestDriver::snapshot`]: https://docs.rs/yew-e2e/latest/yew_e2e/struct.TestDriver.html#method.snapshot
163//! [`TestDriver`]: https://docs.rs/yew-e2e/latest/yew_e2e/struct.TestDriver.html
164//! [Trunk]: https://trunkrs.dev
165//! [Yew]: https://yew.rs
166
167#![warn(missing_docs)]
168#![deny(rustdoc::broken_intra_doc_links)]
169
170use std::fmt::Write;
171use std::future::Future;
172use std::panic::AssertUnwindSafe;
173use std::path::{Path, PathBuf};
174use std::pin::pin;
175use std::sync::{Arc, Mutex};
176
177use anyhow::{Context, Result, anyhow, bail, ensure};
178use futures_util::FutureExt;
179use thirtyfour::common::types::ElementRect;
180use thirtyfour::prelude::*;
181use tokio::time::{self, Duration};
182
183mod dist;
184mod driver;
185mod fetch;
186pub mod harness;
187#[cfg(test)]
188mod lib_tests;
189mod run_lock;
190mod sandbox;
191mod sessions;
192
193pub use self::dist::{dist, target_dir, workspace_root};
194pub use self::driver::Engine;
195
196use self::driver::{Driver, QUIT_TIMEOUT, STARTUP_TIMEOUT, with_cleanup};
197
198/// What a test file needs in scope, in one `use yew_e2e::prelude::*;`.
199///
200/// That is [`anyhow`](mod@anyhow)'s [`Result`] and error macros, the whole of
201/// `thirtyfour`'s prelude (among it [`By`], [`Key`] and [`WebDriver`]), and
202/// the [`TestDriver`] and [`TestElement`] a test is handed.
203///
204/// [`Result`]: anyhow::Result
205/// [`By`]: thirtyfour::By
206/// [`Key`]: thirtyfour::Key
207/// [`WebDriver`]: thirtyfour::WebDriver
208pub mod prelude {
209    pub use anyhow::{Context, Result, anyhow, bail, ensure};
210    pub use thirtyfour::prelude::*;
211
212    /// What every test is handed, so its signature can be written without a
213    /// `use` per file saying so.
214    pub use crate::{TestDriver, TestElement};
215}
216
217/// **The application under test**, started afresh for every test and taken
218/// down after it.
219///
220/// A suite names one fixture in [`harness!`], and every test is handed the one
221/// started for it beside the browser, so whatever a test needs to reach behind
222/// the page (a database, a port, a channel into the server) is its own.
223pub trait Fixture: Sized + 'static {
224    /// What one test asks of the fixture started for it. [`harness!`] sets a
225    /// `bool` field of this for every word in the parentheses after a test's
226    /// name; `()` where no test asks for anything.
227    type Setup: Default;
228
229    /// How this suite is run: its name, its frontend and its lock.
230    fn config() -> Config {
231        Config::default()
232    }
233
234    /// Install the run's tracing subscriber. The default prints `INFO` and
235    /// above.
236    fn init_tracing() {
237        _ = tracing_subscriber::fmt()
238            .with_max_level(tracing::Level::INFO)
239            .try_init();
240    }
241
242    /// Confine the application to `root`, a directory made fresh for this run
243    /// under the build directory, before any fixture starts. The run fails if
244    /// anything new is under `root` when it finishes; see [`Fixture::check`]
245    /// for failing the one test that reached outside it.
246    fn enter_sandbox(root: &Path) -> Result<()> {
247        _ = root;
248        Ok(())
249    }
250
251    /// Asked after every test: whatever the application did during it that
252    /// fails the test even though the test itself passed.
253    fn check() -> Result<()> {
254        Ok(())
255    }
256
257    /// Start the application for one test.
258    fn start(setup: Self::Setup) -> impl Future<Output = Result<Self>>;
259
260    /// Where the browser is pointed for this test.
261    fn url(&self) -> String;
262
263    /// Take the application down once its test has finished.
264    fn quit(self) -> impl Future<Output = Result<()>>;
265}
266
267/// How a suite is run; see [`Fixture::config`].
268#[derive(Debug, Clone)]
269pub struct Config {
270    pub(crate) about: String,
271    pub(crate) frontend: Frontend,
272    pub(crate) lock: String,
273    pub(crate) sessions: String,
274}
275
276impl Default for Config {
277    fn default() -> Self {
278        Self {
279            about: String::from("A browser suite."),
280            frontend: Frontend::Trunk(PathBuf::new()),
281            lock: String::from("yew-e2e.lock"),
282            sessions: String::from("e2e-sessions"),
283        }
284    }
285}
286
287impl Config {
288    /// The one line `--help` opens with.
289    pub fn about(mut self, about: impl Into<String>) -> Self {
290        self.about = about.into();
291        self
292    }
293
294    /// What the suite serves, and how it is built.
295    pub fn frontend(mut self, frontend: Frontend) -> Self {
296        self.frontend = frontend;
297        self
298    }
299
300    /// What the run lock is called inside whichever directory `--lock` names.
301    pub fn lock_name(mut self, name: impl Into<String>) -> Self {
302        self.lock = name.into();
303        self
304    }
305
306    /// Where under the build directory the record of every run is kept, which
307    /// is what `--last-session` reads the newest of. Two suites sharing a
308    /// build directory name one each, or each picks up the other's runs.
309    pub fn sessions_dir(mut self, name: impl Into<String>) -> Self {
310        self.sessions = name.into();
311        self
312    }
313}
314
315/// The frontend a suite serves, built once for the whole run; [`dist`] is
316/// where it ends up.
317#[derive(Debug, Clone)]
318pub enum Frontend {
319    /// Nothing to build: the fixture serves its own pages.
320    None,
321    /// `trunk build` run in this directory, relative to the workspace root,
322    /// into `e2e-dist` under the build directory. `E2E_DIST` names a frontend
323    /// already built in its place.
324    Trunk(PathBuf),
325}
326
327/// **What a test last asked to wait for**, in the words the test used.
328///
329/// A test that is given up on has to say what it was doing, and how long it
330/// took says nothing: the run is left reading a name and a number of seconds
331/// against a suite of tests that all wait on something. One browser carries one
332/// test at a time, so this hangs off the browser's driver and is that test's
333/// own; it is cleared as each test begins so that a test which never waited on
334/// anything does not inherit the last one's words.
335#[derive(Clone, Default)]
336pub(crate) struct Waiting(Arc<Mutex<Option<String>>>);
337
338impl Waiting {
339    /// Note what is being waited for now.
340    fn on(&self, what: impl std::fmt::Display) {
341        *self.held() = Some(what.to_string());
342    }
343
344    /// Forget it, which is what the start of a test does.
345    fn clear(&self) {
346        *self.held() = None;
347    }
348
349    /// **The clause a report hangs off a timeout**, and nothing at all where
350    /// the test never named a wait.
351    pub(crate) fn clause(&self) -> String {
352        match &*self.held() {
353            Some(what) => format!(", last waiting for {what}"),
354            None => String::new(),
355        }
356    }
357
358    /// A panic while a test held this says nothing about the words in it, which
359    /// are only ever replaced whole.
360    fn held(&self) -> std::sync::MutexGuard<'_, Option<String>> {
361        self.0.lock().unwrap_or_else(|held| held.into_inner())
362    }
363}
364
365/// One browser, kept for as long as there are tests to run in it.
366pub(crate) struct Browser {
367    webdriver: Driver,
368    driver: TestDriver,
369}
370
371impl Browser {
372    /// Start a WebDriver server and the one browser it drives.
373    pub(crate) async fn open() -> Result<Self> {
374        let engine = crate::harness::engine();
375        let deadline = time::Instant::now() + STARTUP_TIMEOUT;
376        let caps = engine.capabilities(crate::harness::headed())?;
377        let webdriver = Driver::new(engine, deadline).await?;
378        Self::connect(webdriver, caps, deadline).await
379    }
380
381    async fn connect(
382        mut webdriver: Driver,
383        mut caps: Capabilities,
384        deadline: time::Instant,
385    ) -> Result<Self> {
386        let downloads = tempfile::tempdir().context("creating browser download directory")?;
387        let directory = downloads.path().to_string_lossy().into_owned();
388        let key = match webdriver.engine() {
389            Engine::Firefox => "moz:firefoxOptions",
390            Engine::Chrome => "goog:chromeOptions",
391        };
392        if !caps.contains_key(key) {
393            caps.set(key, serde_json::json!({}))?;
394        }
395        match webdriver.engine() {
396            Engine::Firefox => {
397                let options = caps
398                    .get_mut("moz:firefoxOptions")
399                    .context("Firefox capabilities have no options")?;
400                let prefs = options
401                    .as_object_mut()
402                    .context("Firefox options")?
403                    .entry("prefs")
404                    .or_insert_with(|| serde_json::json!({}));
405                let prefs = prefs.as_object_mut().context("Firefox preferences")?;
406                prefs.insert("browser.download.folderList".into(), 2.into());
407                prefs.insert("browser.download.dir".into(), directory.into());
408                prefs.insert("browser.download.useDownloadDir".into(), true.into());
409                prefs.insert(
410                    "browser.helperApps.neverAsk.saveToDisk".into(),
411                    "audio/wav,application/zip,application/json".into(),
412                );
413            }
414            Engine::Chrome => {
415                let options = caps
416                    .get_mut("goog:chromeOptions")
417                    .context("Chrome capabilities have no options")?;
418                options["prefs"] = serde_json::json!({
419                    "download.default_directory": directory,
420                    "download.prompt_for_download": false,
421                });
422            }
423        }
424        tracing::info!(
425            "{} address: {:?}",
426            webdriver.engine().driver(),
427            webdriver.address
428        );
429
430        let url = format!("http://{}", webdriver.address);
431        let connected = webdriver
432            .during(deadline, "startup", async {
433                Ok(WebDriver::new(&url, caps).await?)
434            })
435            .await;
436        let driver = match connected {
437            Ok(driver) => driver,
438            Err(error) => return Err(with_cleanup(error, webdriver.terminate().await)),
439        };
440
441        Ok(Self {
442            webdriver,
443            driver: TestDriver {
444                inner: driver,
445                wait_timeout: WAIT_TIMEOUT,
446                load_timeout: LOAD_TIMEOUT,
447                waiting: Waiting::default(),
448                downloads,
449            },
450        })
451    }
452
453    /// Put the browser on a fresh tab, then go to `url`.
454    ///
455    /// The preceding document is closed rather than navigated away from. A
456    /// WebDriver navigation leaves session history behind; long runs showed
457    /// memory growth that closing the previous tab removed.
458    async fn reset(&mut self, url: &str) -> Result<()> {
459        self.driver.waiting.clear();
460        for file in std::fs::read_dir(self.driver.downloads.path())? {
461            std::fs::remove_file(file?.path())?;
462        }
463        let old = self.driver.inner.window().await?;
464        let fresh = self.driver.inner.new_tab().await?;
465        self.driver.inner.switch_to_window(fresh.clone()).await?;
466        self.driver.inner.switch_to_window(old).await?;
467        self.driver.inner.close_window().await?;
468        self.driver.inner.switch_to_window(fresh).await?;
469        self.driver.set_window_size(WINDOW.0, WINDOW.1).await?;
470        self.driver.inner.goto(url).await?;
471        Ok(())
472    }
473
474    /// Take the browser and its driver down.
475    ///
476    /// A quit that only timed out comes back as `Ok(Some(_))` once the
477    /// driver's process group is reaped: nothing is left running, so it is a
478    /// warning for the caller to say rather than a failure.
479    pub(crate) async fn close(mut self) -> Result<Option<anyhow::Error>> {
480        // Keep the original handle alive until Drop marks it leaked. Otherwise
481        // cancelling quit would invoke thirtyfour's synchronous fallback before
482        // the timeout future could return and before we could kill the driver.
483        let driver = self.driver.inner.clone();
484        let quit = self
485            .webdriver
486            .during(time::Instant::now() + QUIT_TIMEOUT, "quit", async {
487                Ok(driver.quit().await?)
488            })
489            .await;
490        let reaped = self.webdriver.terminate().await;
491        match (quit, reaped) {
492            (Ok(()), reaped) => reaped.map(|()| None),
493            (Err(error), Ok(())) if error.downcast_ref::<driver::TimedOut>().is_some() => {
494                Ok(Some(error))
495            }
496            (Err(error), reaped) => Err(with_cleanup(error, reaped)),
497        }
498    }
499}
500
501impl Drop for Browser {
502    fn drop(&mut self) {
503        // `leak` marks the shared session as already quit; it leaks no memory.
504        // Our Driver owns process teardown, including cancellation and crashes.
505        let _ = self.driver.inner.clone().leak();
506    }
507}
508
509#[cfg(test)]
510mod browser_tests {
511    use anyhow::{Context, Result, ensure};
512
513    use super::Browser;
514
515    /// Each test gets a document with no predecessor retained in its browser.
516    ///
517    /// This uses the real WebDriver because only a browser can say which tabs
518    /// and history entries survived. Replacing `Browser::reset` with a plain
519    /// `goto` makes the second URL retain the first tab and add a history entry.
520    #[tokio::test]
521    #[ignore = "requires a real WebDriver"]
522    async fn a_reset_discards_the_preceding_document() -> Result<()> {
523        let mut browser = Browser::open().await?;
524
525        let result = async {
526            browser.reset("data:text/html,first").await?;
527            let first = browser.driver.inner.window().await?;
528
529            browser.reset("data:text/html,second").await?;
530            let second = browser.driver.inner.window().await?;
531            let windows = browser.driver.inner.windows().await?;
532            let history = browser
533                .driver
534                .inner
535                .execute("return history.length", Vec::new())
536                .await?
537                .json()
538                .as_u64()
539                .context("browser history length")?;
540
541            ensure!(first != second, "the second reset kept the first tab");
542            ensure!(windows == [second], "reset left tabs behind: {windows:?}");
543            ensure!(history <= 2, "the fresh tab has {history} history entries");
544            Ok(())
545        }
546        .await;
547
548        match (result, browser.close().await) {
549            (Ok(()), Ok(_)) => Ok(()),
550            (Err(error), Ok(_)) | (Ok(()), Err(error)) => Err(error),
551            (Err(error), Err(cleanup)) => Err(super::driver::with_cleanup(error, Err(cleanup))),
552        }
553    }
554}
555
556/// The window every test starts with; see [`Browser::reset`].
557const WINDOW: (u32, u32) = (1600, 1000);
558
559/// The words a session or a connection that is no longer there says, matched
560/// against every link of an error's chain. `invalid session id` is the
561/// WebDriver protocol's own answer to a command for a session that is gone,
562/// and `session id is invalid` is thirtyfour's wrapper over it; the page
563/// crash and the terminated session are the two ways the session dies without
564/// a command naming it; the last two are this side of the connection - the
565/// runner's own answer when the driver process has ended, and what the HTTP
566/// client answers once that driver cannot be reached. Anything else an error
567/// can say stays an ordinary failure, because a session death is the one
568/// failure here that is not the test's.
569const SESSION_DEATH: &[&str] = &[
570    "invalid session id",
571    "session id is invalid",
572    "session deleted because of page crash",
573    "session terminated",
574    "the webdriver server's output ended",
575    "error sending request",
576];
577
578/// Whether an error is the browser or its driver being gone, and the words
579/// that said so.
580pub(crate) fn browser_death(error: &anyhow::Error) -> Option<&'static str> {
581    let mut source: Option<&dyn std::error::Error> = Some(error.as_ref());
582
583    while let Some(error) = source {
584        let said = error.to_string().to_lowercase();
585
586        if let Some(mark) = SESSION_DEATH.iter().find(|mark| said.contains(**mark)) {
587            return Some(mark);
588        }
589
590        source = error.source();
591    }
592
593    None
594}
595
596/// The one error a dead browser reports: what said the session was gone, and
597/// what the driver had to say for itself, which the runner was reading all
598/// along. The ordinary report is what a session death otherwise reads as -
599/// whatever the test was last waiting for - which is how one dead browser
600/// becomes two wrong tests.
601fn went_away(browser: &Browser, mark: &str) -> anyhow::Error {
602    let name = browser.webdriver.engine().driver();
603
604    anyhow!(
605        "the browser went away ({mark}); {name} last said: {}",
606        driver_said(browser)
607    )
608}
609
610/// The tail of what the driver said, stderr first, for the one line the report
611/// has room for.
612fn driver_said(browser: &Browser) -> String {
613    let said = browser.webdriver.diagnostics();
614
615    said.lines()
616        .rev()
617        .take(3)
618        .collect::<Vec<_>>()
619        .into_iter()
620        .rev()
621        .collect::<Vec<_>>()
622        .join(" | ")
623}
624
625/// Start the fixture for one test, run it, and take the fixture down again.
626pub(crate) async fn run_one<F: Fixture>(
627    browser: &mut Browser,
628    start: crate::harness::Start<F>,
629    setup: F::Setup,
630    limit: Option<Duration>,
631) -> Result<()> {
632    let mut fixture = F::start(setup).await?;
633
634    let mut errors = String::new();
635
636    let result = match browser.reset(&fixture.url()).await {
637        Ok(()) => drive_one(browser, &mut fixture, start, limit).await,
638        Err(error) => Err(error),
639    };
640
641    let fixture_result = fixture.quit().await;
642
643    if let Err(error) = result.as_ref() {
644        if let Some(mark) = browser_death(error) {
645            let mut error = went_away(browser, mark);
646
647            if let Err(quit) = fixture_result {
648                error = error.context(format!("the fixture also failed to quit: {quit}"));
649            }
650
651            return Err(error);
652        }
653
654        writeln!(errors, "Test error: {error}")?;
655
656        let mut source = error.source();
657
658        while let Some(e) = source.take() {
659            writeln!(errors, "  Caused by: {e}")?;
660            source = e.source();
661        }
662    }
663
664    if let Err(error) = fixture_result {
665        writeln!(errors, "Fixture error: {error}")?;
666
667        let mut source = error.source();
668
669        while let Some(e) = source.take() {
670            writeln!(errors, "  Caused by: {e}")?;
671            source = e.source();
672        }
673    }
674
675    if let Err(error) = F::check() {
676        writeln!(errors, "Check error: {error}")?;
677    }
678
679    if !errors.is_empty() {
680        return Err(anyhow!("{errors}"));
681    }
682
683    Ok(())
684}
685
686/// **The test itself, against `--timeout` and with the driver's output being
687/// read the whole time.**
688///
689/// The cap is here rather than around the whole run so that a test which
690/// overruns is still followed by the fixture being taken down: a run that
691/// dropped the fixture where it stood would leave its application serving for
692/// the rest of the suite. What the report says is the same either way, and names
693/// what the test was last waiting for, which is the only thing on hand to say
694/// where it stopped.
695async fn drive_one<F: Fixture>(
696    browser: &mut Browser,
697    fixture: &mut F,
698    start: crate::harness::Start<F>,
699    limit: Option<Duration>,
700) -> Result<()> {
701    let mut timeout = pin!(async move {
702        match limit {
703            Some(limit) => time::sleep(limit).await,
704            None => std::future::pending::<()>().await,
705        }
706    });
707
708    let Browser { webdriver, driver } = browser;
709
710    let waiting = driver.waiting.clone();
711
712    let outcome = {
713        let task = AssertUnwindSafe(start(driver, fixture)).catch_unwind();
714        let mut task = pin!(task);
715
716        loop {
717            tokio::select! {
718                _ = timeout.as_mut() => {
719                    break Err(overran(limit, &waiting));
720                }
721                result = task.as_mut() => {
722                    break Ok(result);
723                }
724                result = webdriver.io() => {
725                    if !result? {
726                        break Err("the WebDriver server's output ended".to_string());
727                    }
728                }
729            }
730        }
731    };
732
733    match outcome {
734        Ok(Ok(Ok(()))) => match driver.error_seen().await? {
735            Some(threw) => bail!("the page threw: {threw}"),
736            None => Ok(()),
737        },
738        Ok(Ok(result)) => result,
739        Ok(Err(panicked)) => bail!("the test panicked: {}", panic_message(&panicked)),
740        Err(error) => bail!(error),
741    }
742}
743
744/// **What a test that ran out of time is reported as.** The runner and the run
745/// itself both have a way of giving up on a test, and both say it this way.
746pub(crate) fn overran(limit: Option<Duration>, waiting: &Waiting) -> String {
747    let seconds = limit.map_or(0, |limit| limit.as_secs());
748
749    format!(
750        "the test was still running after {seconds}s, which is --timeout{}",
751        waiting.clause()
752    )
753}
754
755/// What a caught panic said, for the one line the report has room for.
756fn panic_message(payload: &Box<dyn std::any::Any + Send>) -> &str {
757    if let Some(message) = payload.downcast_ref::<&'static str>() {
758        return message;
759    }
760
761    if let Some(message) = payload.downcast_ref::<String>() {
762        return message;
763    }
764
765    "a payload that is neither a string nor a &str"
766}
767
768/// The first step of a drag along one axis: up to 8px towards `offset`, never
769/// past it, so that the rest of the drag moves `offset` less this.
770fn drag_nudge(offset: i64) -> i64 {
771    offset.clamp(-8, 8)
772}
773
774/// How often a pending observation is repeated.
775pub const POLL_INTERVAL: Duration = Duration::from_millis(25);
776
777/// How long any one observation of a page that is already up may take to agree.
778const WAIT_TIMEOUT: Duration = Duration::from_secs(5);
779
780/// How long the first look at a page may take: the browser starting, the bundle
781/// being fetched, the wasm compiled and the application connected, none of
782/// which has happened when a test first asks for the page; see
783/// [`TestDriver::load_timeout`].
784const LOAD_TIMEOUT: Duration = Duration::from_secs(15);
785
786macro_rules! common {
787    () => {
788        /// Repeat `condition` until it holds, or the wait timeout passes.
789        pub async fn wait_until(
790            &self,
791            what: impl std::fmt::Display,
792            condition: impl AsyncFnMut() -> Result<bool>,
793        ) -> Result<()> {
794            self.wait_for(self.wait_timeout, what, condition).await
795        }
796
797        /// [`Self::wait_until`] where the default deadline is the wrong one,
798        /// because what is being waited for has a length of its own that is
799        /// known and is close to it. A wait that habitually lands just inside
800        /// its cap is not passing, it is winning a race.
801        pub async fn wait_until_within(
802            &self,
803            timeout: Duration,
804            what: impl std::fmt::Display,
805            condition: impl AsyncFnMut() -> Result<bool>,
806        ) -> Result<()> {
807            self.wait_for(timeout, what, condition).await
808        }
809
810        /// [`Self::wait_until`] against a deadline of the caller's choosing.
811        async fn wait_for(
812            &self,
813            timeout: Duration,
814            what: impl std::fmt::Display,
815            mut condition: impl AsyncFnMut() -> Result<bool>,
816        ) -> Result<()> {
817            let deadline = time::Instant::now() + timeout;
818
819            self.waiting.on(&what);
820
821            loop {
822                if condition().await? {
823                    return Ok(());
824                }
825
826                if time::Instant::now() >= deadline {
827                    bail!("Timed out after {timeout:?} waiting for {what}");
828                }
829
830                time::sleep(POLL_INTERVAL).await;
831            }
832        }
833
834        /// Wait until the text of every node matching `by` reads `expected`.
835        pub async fn wait_texts<const N: usize>(
836            &self,
837            by: impl IntoBy,
838            expected: [&str; N],
839        ) -> Result<()> {
840            let by = by.into_by();
841
842            tracing::trace!(?by, ?expected, "Waiting for texts");
843
844            let seen = std::cell::RefCell::new(Vec::new());
845
846            let result = self
847                .wait_until(format_args!("{by} to read {expected:?}"), async || {
848                    let texts = self.find_all_texts(by.clone()).await?;
849                    let matched = texts == expected;
850                    *seen.borrow_mut() = texts;
851                    Ok(matched)
852                })
853                .await;
854
855            match result {
856                Ok(()) => Ok(()),
857                Err(error) => {
858                    let seen = seen.into_inner();
859                    Err(error.context(format!("last read {seen:?}")))
860                }
861            }
862        }
863
864        /// Wait until exactly `expected` nodes match `by`.
865        ///
866        /// **Exact equality, polled, starting immediately -- which is a trap
867        /// directly after an action.** A call whose `expected` is the count that
868        /// was already on screen is answered by the very first poll, before the
869        /// action it is meant to be checking can have landed, so it asserts only
870        /// that the page has not caught up yet. It stays green for months and
871        /// then turns into a hard timeout the first time anything, however
872        /// unrelated, makes the page a few milliseconds slower to lay out --
873        /// and blames that change. Where the count is supposed to have *changed*,
874        /// read it before the action and say so with [`Self::wait_count_from`],
875        /// which refuses the degenerate case instead of passing it. Plain
876        /// `wait_count` belongs where a count is being established rather than
877        /// changed: a page just loaded, a selector first asserted.
878        pub async fn wait_count(&self, by: impl IntoBy, expected: usize) -> Result<()> {
879            let by = by.into_by();
880
881            tracing::trace!(?by, expected, "Waiting for count");
882
883            self.wait_until(format_args!("{by} to match {expected} nodes"), async || {
884                Ok(self.find_all(by.clone()).await?.len() == expected)
885            })
886            .await
887        }
888
889        /// How many nodes match `by` right now, without waiting for any
890        /// particular number of them. The before-read [`Self::wait_count_from`]
891        /// asks for.
892        #[inline]
893        pub async fn count(&self, by: impl IntoBy) -> Result<usize> {
894            Ok(self.find_all(by.into_by()).await?.len())
895        }
896
897        /// Wait until exactly `expected` nodes match `by`, having been told the
898        /// `before` count that the action in between was supposed to change.
899        ///
900        /// **The before-read is the whole point.** [`Self::wait_count`] cannot
901        /// tell "the action landed" apart from "the action has not started",
902        /// because both of those look exactly like the number it was given; this
903        /// can, because it knows which number meant "not yet". When `before`
904        /// already equals `expected` it refuses outright rather than passing on
905        /// the first poll, so the assertion that verifies nothing fails loudly
906        /// the day it is written instead of years later on somebody else's
907        /// change. Take `before` with [`Self::count`] immediately before the
908        /// action -- at the top of the test it is a different question, and
909        /// anything landing in between makes it a lie.
910        pub async fn wait_count_from(
911            &self,
912            by: impl IntoBy,
913            before: usize,
914            expected: usize,
915        ) -> Result<()> {
916            let by = by.into_by();
917
918            ensure!(
919                before != expected,
920                "Waiting for {by} to match {expected} nodes verifies nothing: \
921                 {expected} is also the count read before the action, so the \
922                 first poll agrees whether or not the action has landed. Assert \
923                 the count this action is supposed to produce, or if it really \
924                 is meant to leave the count alone, assert what it did change.",
925            );
926
927            tracing::trace!(?by, before, expected, "Waiting for count to change");
928
929            self.wait_until(
930                format_args!("{by} to go from {before} to {expected} nodes"),
931                async || Ok(self.find_all(by.clone()).await?.len() == expected),
932            )
933            .await
934        }
935
936        /// Find the text contents of all nodes match the given [`By`].
937        #[inline]
938        pub async fn find_all_texts(&self, by: impl IntoBy) -> Result<Vec<String>> {
939            let mut texts = Vec::new();
940
941            for item in self.find_all(by.into_by()).await? {
942                texts.push(item.text().await?);
943            }
944
945            Ok(texts)
946        }
947
948        /// Find an element by xpath.
949        #[inline]
950        pub async fn find_one_by_xpath(&self, xpath: &str) -> Result<TestElement> {
951            self.find_one_by(By::XPath(xpath)).await
952        }
953
954        /// Find the one element matching `by`, waiting for it to appear.
955        ///
956        /// **Refusing a second match is the point.** A selector that was meant
957        /// to name one thing and now names three is the way a guard goes quiet,
958        /// so this says so instead of picking. Where several *is* what the page
959        /// is, the question was never "the one": see [`Self::find_nth`].
960        pub async fn find_one_by(&self, by: impl IntoBy) -> Result<TestElement> {
961            let by = by.into_by();
962
963            tracing::trace!(?by, "Finding one element");
964
965            let deadline = time::Instant::now() + self.wait_timeout;
966
967            loop {
968                let items = self.find_all(by.clone()).await?;
969
970                ensure!(
971                    items.len() <= 1,
972                    "Expected exactly one by {by}, but got {}: where several is \
973                     what the page is, ask for one of them by index with \
974                     find_nth, or for the first of them with find_first",
975                    items.len()
976                );
977
978                if let Some(item) = items.into_iter().next() {
979                    return Ok(item);
980                }
981
982                if time::Instant::now() >= deadline {
983                    bail!(
984                        "Timed out after {:?} waiting for {by}",
985                        self.wait_timeout
986                    );
987                }
988
989                time::sleep(POLL_INTERVAL).await;
990            }
991        }
992
993        /// Find the `index`th element matching `by`, waiting for that many to
994        /// appear.
995        ///
996        /// **What a test asks when several is the answer**, and the reading twin
997        /// of [`TestDriver::press_nth`]: the row a test appended is the one at
998        /// the end, three related buttons are three whatever is measured, and
999        /// neither is a broken selector for [`Self::find_one_by`] to refuse.
1000        /// Asked here rather than by reaching for [`Self::find_all`] and
1001        /// indexing the answer, which drops the wait along with the sentence
1002        /// saying which one was wanted.
1003        ///
1004        /// A wait polling for an element to *arrive* still wants
1005        /// [`Self::find_all`]: nothing there is an answer to that question, and
1006        /// this has a deadline of its own to spend before it says so.
1007        pub async fn find_nth(&self, by: impl IntoBy, index: usize) -> Result<TestElement> {
1008            let by = by.into_by();
1009
1010            tracing::trace!(?by, index, "Finding one of several elements");
1011
1012            let deadline = time::Instant::now() + self.wait_timeout;
1013
1014            loop {
1015                if let Some(item) = self.find_all(by.clone()).await?.into_iter().nth(index) {
1016                    return Ok(item);
1017                }
1018
1019                if time::Instant::now() >= deadline {
1020                    bail!(
1021                        "Timed out after {:?} waiting for {by} at {index}",
1022                        self.wait_timeout
1023                    );
1024                }
1025
1026                time::sleep(POLL_INTERVAL).await;
1027            }
1028        }
1029
1030        /// The first element matching `by`, however many there turn out to be.
1031        /// [`Self::find_nth`] says when that is the question.
1032        #[inline]
1033        pub async fn find_first(&self, by: impl IntoBy) -> Result<TestElement> {
1034            self.find_nth(by, 0).await
1035        }
1036
1037        /// Find all elements matching `by`.
1038        pub async fn find_all(&self, by: impl Into<By>) -> Result<Vec<TestElement>> {
1039            self.find_all_within(self.wait_timeout, by).await
1040        }
1041
1042        /// [`Self::find_all`] with a bound of the caller's choosing on the call
1043        /// itself, for putting the question to a browser which is still
1044        /// starting. See [`TestDriver::load_timeout`].
1045        pub async fn find_all_within(
1046            &self,
1047            timeout: Duration,
1048            by: impl Into<By>,
1049        ) -> Result<Vec<TestElement>> {
1050            let by = by.into();
1051            tracing::trace!(?by, "Finding all elements");
1052
1053            let task = self.inner.find_all(by.clone());
1054            let sleep = time::sleep(timeout);
1055
1056            tokio::select! {
1057                _ = sleep => {
1058                    Err(anyhow!("find_elements({by:?}) timed out after {timeout:?}"))
1059                }
1060                result = task => {
1061                    Ok(result?.into_iter().map(|inner| TestElement { inner, wait_timeout: self.wait_timeout, waiting: self.waiting.clone() }).collect::<Vec<_>>())
1062                }
1063            }
1064        }
1065    }
1066}
1067
1068/// A canvas's own reported size -- see [`TestDriver::canvas_size`].
1069#[derive(Debug, Clone, Copy)]
1070pub struct CanvasSize {
1071    /// The backing buffer's width, in device pixels.
1072    pub device_width: f64,
1073    /// The backing buffer's height, in device pixels.
1074    pub device_height: f64,
1075    /// The element's own layout box width, in CSS pixels.
1076    pub css_width: f64,
1077    /// The element's own layout box height, in CSS pixels.
1078    pub css_height: f64,
1079    /// What the browser itself reports for `window.devicePixelRatio`.
1080    pub device_pixel_ratio: f64,
1081}
1082
1083/// A wrapped WebElement.
1084pub struct TestElement {
1085    inner: WebElement,
1086    wait_timeout: Duration,
1087    waiting: Waiting,
1088}
1089
1090impl TestElement {
1091    /// The WebDriver element underneath, for what this wrapper has no method
1092    /// for.
1093    pub fn element(&self) -> &WebElement {
1094        &self.inner
1095    }
1096
1097    /// Click the element.
1098    pub async fn click(&self) -> Result<()> {
1099        tracing::trace!("Clicking element");
1100        self.inner.click().await?;
1101        Ok(())
1102    }
1103
1104    /// **Press the element with control held**, which is how a selection is
1105    /// commonly extended by one item.
1106    pub async fn extend_click(&self) -> Result<()> {
1107        tracing::trace!("Extend-clicking element");
1108
1109        self.inner.scroll_into_view().await?;
1110
1111        self.inner
1112            .handle()
1113            .action_chain()
1114            .key_down(thirtyfour::Key::Control)
1115            .click_element(&self.inner)
1116            .key_up(thirtyfour::Key::Control)
1117            .perform()
1118            .await?;
1119
1120        Ok(())
1121    }
1122
1123    /// **Press the element with shift held**, which picks the run from the
1124    /// last item picked to this one in a list that has an order.
1125    pub async fn shift_click(&self) -> Result<()> {
1126        tracing::trace!("Shift-clicking element");
1127
1128        self.inner.scroll_into_view().await?;
1129
1130        self.inner
1131            .handle()
1132            .action_chain()
1133            .key_down(thirtyfour::Key::Shift)
1134            .click_element(&self.inner)
1135            .key_up(thirtyfour::Key::Shift)
1136            .perform()
1137            .await?;
1138
1139        Ok(())
1140    }
1141
1142    /// Rest the pointer on the element without pressing anything.
1143    pub async fn hover(&self) -> Result<()> {
1144        tracing::trace!("Hovering element");
1145
1146        self.inner.scroll_into_view().await?;
1147
1148        self.inner
1149            .handle()
1150            .action_chain()
1151            .move_to_element_center(&self.inner)
1152            .perform()
1153            .await?;
1154
1155        Ok(())
1156    }
1157
1158    /// Press the element twice, as one gesture.
1159    pub async fn double_click(&self) -> Result<()> {
1160        tracing::trace!("Double-clicking element");
1161
1162        self.inner.scroll_into_view().await?;
1163
1164        self.inner
1165            .handle()
1166            .action_chain()
1167            .double_click_element(&self.inner)
1168            .perform()
1169            .await?;
1170
1171        Ok(())
1172    }
1173
1174    /// **The same, a given offset from the element's centre**, for one element
1175    /// covering a whole surface, where on it a gesture lands being what the
1176    /// gesture is about.
1177    pub async fn double_click_by(&self, dx: i64, dy: i64) -> Result<()> {
1178        tracing::trace!(dx, dy, "Double-clicking element off centre");
1179
1180        self.inner.scroll_into_view().await?;
1181
1182        self.inner
1183            .handle()
1184            .action_chain()
1185            .move_to_element_center(&self.inner)
1186            .move_by_offset(dx, dy)
1187            .double_click()
1188            .perform()
1189            .await?;
1190
1191        Ok(())
1192    }
1193
1194    /// **Press the element once, a given offset from its centre.** A slider is
1195    /// one element covering its whole travel, so where on it a press lands is
1196    /// the whole of what the press says.
1197    pub async fn click_by(&self, dx: i64, dy: i64) -> Result<()> {
1198        tracing::trace!(dx, dy, "Clicking element off centre");
1199
1200        self.inner.scroll_into_view().await?;
1201
1202        self.inner
1203            .handle()
1204            .action_chain()
1205            .move_to_element_center(&self.inner)
1206            .move_by_offset(dx, dy)
1207            .click()
1208            .perform()
1209            .await?;
1210
1211        Ok(())
1212    }
1213
1214    /// Right-click the element.
1215    pub async fn context_click(&self) -> Result<()> {
1216        tracing::trace!("Context-clicking element");
1217
1218        self.inner.scroll_into_view().await?;
1219
1220        self.inner
1221            .handle()
1222            .action_chain()
1223            .context_click_element(&self.inner)
1224            .perform()
1225            .await?;
1226
1227        Ok(())
1228    }
1229
1230    /// Press on this element and drag `dx`, `dy` from where it is, **leaving
1231    /// the button down**.
1232    ///
1233    /// The pointer first steps up to 8px towards the offset, so the page sees
1234    /// a drag begin, and then moves the rest of the way: it comes to rest
1235    /// exactly `dx`, `dy` from where it was pressed.
1236    pub async fn drag_by(&self, dx: i64, dy: i64) -> Result<()> {
1237        tracing::trace!(dx, dy, "Dragging element");
1238
1239        let (nx, ny) = (drag_nudge(dx), drag_nudge(dy));
1240
1241        self.inner.scroll_into_view().await?;
1242
1243        self.inner
1244            .handle()
1245            .action_chain()
1246            .move_to_element_center(&self.inner)
1247            .click_and_hold()
1248            .move_by_offset(nx, ny)
1249            .move_by_offset(dx - nx, dy - ny)
1250            .perform()
1251            .await?;
1252
1253        Ok(())
1254    }
1255
1256    /// The same begun at a point of the element's own choosing rather than at
1257    /// its centre, `at_x` and `at_y` being pixels from that centre.
1258    ///
1259    /// A sweep that has to begin in one row of a grid cannot begin wherever the
1260    /// element happens to be halved.
1261    pub async fn drag_from_by(&self, at_x: i64, at_y: i64, dx: i64, dy: i64) -> Result<()> {
1262        tracing::trace!(at_x, at_y, dx, dy, "Dragging from a point in an element");
1263
1264        let (nx, ny) = (drag_nudge(dx), drag_nudge(dy));
1265
1266        self.inner.scroll_into_view().await?;
1267
1268        self.inner
1269            .handle()
1270            .action_chain()
1271            .move_to_element_center(&self.inner)
1272            .move_by_offset(at_x, at_y)
1273            .click_and_hold()
1274            .move_by_offset(nx, ny)
1275            .move_by_offset(dx - nx, dy - ny)
1276            .perform()
1277            .await?;
1278
1279        Ok(())
1280    }
1281
1282    /// The same with `alt` held.
1283    pub async fn alt_drag_by(&self, dx: i64, dy: i64) -> Result<()> {
1284        tracing::trace!(dx, dy, "Dragging element with alt held");
1285
1286        let (nx, ny) = (drag_nudge(dx), drag_nudge(dy));
1287
1288        self.inner.scroll_into_view().await?;
1289
1290        self.inner
1291            .handle()
1292            .action_chain()
1293            .key_down(thirtyfour::Key::Alt)
1294            .move_to_element_center(&self.inner)
1295            .click_and_hold()
1296            .move_by_offset(nx, ny)
1297            .move_by_offset(dx - nx, dy - ny)
1298            .perform()
1299            .await?;
1300
1301        Ok(())
1302    }
1303
1304    /// Get the text contents for this element.
1305    pub async fn text(&self) -> Result<String> {
1306        tracing::trace!("Getting element text");
1307        Ok(self.inner.text().await?)
1308    }
1309
1310    /// One of the element's DOM properties.
1311    pub async fn prop(&self, name: &str) -> Result<String> {
1312        tracing::trace!(name, "Getting element property");
1313        Ok(self.inner.prop(name).await?.unwrap_or_default())
1314    }
1315
1316    /// One of the element's DOM *attributes*, or the empty string when it has
1317    /// none.
1318    pub async fn attr(&self, name: &str) -> Result<String> {
1319        tracing::trace!(name, "Getting element attribute");
1320        Ok(self.inner.attr(name).await?.unwrap_or_default())
1321    }
1322
1323    /// Bring the element into view.
1324    pub async fn scroll_into_view(&self) -> Result<()> {
1325        tracing::trace!("Scrolling element into view");
1326        self.inner.scroll_into_view().await?;
1327        Ok(())
1328    }
1329
1330    /// Put keyboard focus here without pressing anything.
1331    pub async fn focus(&self) -> Result<()> {
1332        tracing::trace!("Focusing element");
1333        self.inner.focus().await?;
1334        Ok(())
1335    }
1336
1337    /// Whether the element is displayed, as WebDriver judges it: present in
1338    /// the page is not enough, it must also not be hidden by CSS
1339    /// (`display: none`, `visibility: hidden`) or have no size.
1340    ///
1341    /// Answers once, at the time of asking; it does not wait.
1342    pub async fn visible(&self) -> Result<bool> {
1343        Ok(self.inner.is_displayed().await?)
1344    }
1345
1346    /// Where this element is on screen, and how big it is.
1347    pub async fn rect(&self) -> Result<ElementRect> {
1348        tracing::trace!("Measuring element");
1349        Ok(self.inner.rect().await?)
1350    }
1351
1352    /// One of the element's *computed* CSS properties.
1353    pub async fn css(&self, name: &str) -> Result<String> {
1354        tracing::trace!(name, "Getting element style");
1355        Ok(self.inner.css_value(name).await?)
1356    }
1357
1358    /// The element's `value` property.
1359    pub async fn value(&self) -> Result<String> {
1360        tracing::trace!("Getting element value");
1361        Ok(self.inner.prop("value").await?.unwrap_or_default())
1362    }
1363
1364    /// Clear the element contents.
1365    pub async fn clear(&self) -> Result<()> {
1366        tracing::trace!("Clearing element text");
1367        self.inner.clear().await?;
1368        Ok(())
1369    }
1370
1371    /// Send the specified input targeting the element.
1372    pub async fn send_keys(&self, keys: &str) -> Result<()> {
1373        tracing::trace!(?keys, "Sending keys to element");
1374        self.inner.send_keys(keys).await?;
1375        Ok(())
1376    }
1377
1378    /// Whether the element is currently pressed, by `aria-pressed`.
1379    pub async fn pressed(&self) -> Result<bool> {
1380        Ok(self.prop("ariaPressed").await? == "true")
1381    }
1382
1383    /// Whether the control can be worked at all.
1384    pub async fn enabled(&self) -> Result<bool> {
1385        Ok(self.inner.is_enabled().await?)
1386    }
1387
1388    /// Whether the control says it is out of play, by `aria-disabled`. This is
1389    /// the question to ask of a custom control: `enabled` reads the form
1390    /// control's `disabled`, which an element that is not a form control
1391    /// cannot carry, so it answers `true` for one however dead it is.
1392    pub async fn disabled(&self) -> Result<bool> {
1393        Ok(self.prop("ariaDisabled").await? == "true")
1394    }
1395
1396    common!();
1397}
1398
1399/// Wrapper for `WebDriver` which adds convenience methods for testing.
1400pub struct TestDriver {
1401    inner: WebDriver,
1402    downloads: tempfile::TempDir,
1403    wait_timeout: Duration,
1404    load_timeout: Duration,
1405    waiting: Waiting,
1406}
1407
1408impl TestDriver {
1409    /// **`epoch_ms` on the browser's own clock**: its month (from one), day,
1410    /// hour and minute, for a test reading a time the page shows in the
1411    /// reader's zone.
1412    pub async fn local_clock(&self, epoch_ms: u64) -> Result<[u32; 4]> {
1413        let read = self
1414            .inner
1415            .execute(
1416                "const d = new Date(arguments[0]); \
1417                 return [d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes()]",
1418                vec![serde_json::json!(epoch_ms)],
1419            )
1420            .await?;
1421        let parts = read.json().as_array().context("clock array")?;
1422        let mut clock = [0; 4];
1423
1424        for (slot, part) in clock.iter_mut().zip(parts) {
1425            *slot = u32::try_from(part.as_u64().context("clock part")?)?;
1426        }
1427
1428        Ok(clock)
1429    }
1430
1431    /// **Every matching rendered text in one browser observation.**
1432    ///
1433    /// A live viewer can replace its rows while WebDriver walks a list of
1434    /// element handles. Read the list inside the document when the
1435    /// observation itself is the assertion, so it is one snapshot rather
1436    /// than a handle per row.
1437    pub async fn rendered_texts(&self, selector: &str) -> Result<Vec<String>> {
1438        let read = self
1439            .inner
1440            .execute(
1441                "return Array.from(document.querySelectorAll(arguments[0])) \
1442                 .map(n => n.innerText)",
1443                vec![serde_json::json!(selector)],
1444            )
1445            .await?;
1446        let rows = read.json().as_array().context("rendered text array")?;
1447
1448        rows.iter()
1449            .map(|row| row.as_str().context("rendered text").map(str::to_owned))
1450            .collect()
1451    }
1452
1453    /// Files saved by this browser, cleared before each test and removed when it closes.
1454    pub fn downloads(&self) -> &std::path::Path {
1455        self.downloads.path()
1456    }
1457
1458    /// What this browser's test was last waiting for, for the runner to hang
1459    /// off a report of giving up on it.
1460    pub(crate) fn waiting(&self) -> Waiting {
1461        self.waiting.clone()
1462    }
1463
1464    /// The WebDriver session underneath, for what this wrapper has no method
1465    /// for.
1466    pub fn webdriver(&self) -> &WebDriver {
1467        &self.inner
1468    }
1469
1470    /// How long one observation of a page that is already up may take to
1471    /// agree: the deadline [`Self::wait_until`] and the finds wait against.
1472    pub fn wait_timeout(&self) -> Duration {
1473        self.wait_timeout
1474    }
1475
1476    /// How long the first look at a page may take: the browser starting, the
1477    /// bundle being fetched, the wasm compiled, none of which has happened
1478    /// when a page is first asked for.
1479    pub fn load_timeout(&self) -> Duration {
1480        self.load_timeout
1481    }
1482
1483    /// Resize the browser window.
1484    pub async fn set_window_size(&self, width: u32, height: u32) -> Result<()> {
1485        tracing::trace!(width, height, "Sizing the window");
1486        self.inner.set_window_rect(0, 0, width, height).await?;
1487        Ok(())
1488    }
1489
1490    /// **Force one inline CSS property on an element**, the same lever a
1491    /// hand-typed `style=""` pulls, for a size no real window is narrow
1492    /// enough to produce on its own, such as a popover's own row.
1493    pub async fn set_style(
1494        &self,
1495        element: &TestElement,
1496        property: &str,
1497        value: &str,
1498    ) -> Result<()> {
1499        tracing::trace!(property, value, "Setting an inline style property");
1500
1501        let script = format!("arguments[0].style.setProperty({property:?}, {value:?});");
1502
1503        self.inner
1504            .execute(script, vec![element.inner.to_json()?])
1505            .await?;
1506
1507        Ok(())
1508    }
1509
1510    /// **Force one class on or off an element**, for a state the app has no
1511    /// way to put that element in yet but a stylesheet rule already answers
1512    /// for, such as a record button that is capturing and unavailable at once.
1513    pub async fn set_class(&self, element: &TestElement, class: &str, on: bool) -> Result<()> {
1514        tracing::trace!(class, on, "Forcing a class");
1515
1516        let script = format!("arguments[0].classList.toggle({class:?}, {on});");
1517
1518        self.inner
1519            .execute(script, vec![element.inner.to_json()?])
1520            .await?;
1521
1522        Ok(())
1523    }
1524
1525    /// **Give a field a value the way a native control would**, then fire
1526    /// `event` on it, for fields such as `<input type="color">` whose own
1527    /// picker the driver cannot reach.
1528    pub async fn set_value(&self, element: &TestElement, value: &str, event: &str) -> Result<()> {
1529        tracing::trace!(value, event, "Setting a field's value");
1530
1531        self.inner
1532            .execute(
1533                "arguments[0].value = arguments[1]; \
1534                 arguments[0].dispatchEvent(new Event(arguments[2], {bubbles: true}));",
1535                vec![
1536                    element.inner.to_json()?,
1537                    serde_json::json!(value),
1538                    serde_json::json!(event),
1539                ],
1540            )
1541            .await?;
1542
1543        Ok(())
1544    }
1545
1546    /// **Replace the text an element already shows**, for content the test
1547    /// machine cannot be relied on to produce, such as a very long name. Only the existing text node's data changes, so the
1548    /// page keeps owning the node.
1549    pub async fn set_text(&self, element: &TestElement, text: &str) -> Result<()> {
1550        tracing::trace!(text, "Replacing an element's text");
1551
1552        let script = format!(
1553            "const node = arguments[0].firstChild; \
1554             if (!node || node.nodeType !== Node.TEXT_NODE) throw new Error('no text node'); \
1555             node.data = {text:?};"
1556        );
1557
1558        self.inner
1559            .execute(script, vec![element.inner.to_json()?])
1560            .await?;
1561
1562        Ok(())
1563    }
1564
1565    /// **Every box inside an element that has more to show than it has room
1566    /// for**, one line each: a scroller with something to scroll, or a box
1567    /// that clips what it holds. Empty when everything in it fits. A box a
1568    /// pixel or less across is passed over, since that is how a control is
1569    /// hidden from sight while staying reachable, and it clips by design.
1570    pub async fn overflowing(&self, element: &TestElement) -> Result<Vec<String>> {
1571        tracing::trace!("Finding what overflows inside an element");
1572
1573        let script = "const out = []; \
1574             for (const el of [arguments[0], ...arguments[0].querySelectorAll('*')]) { \
1575                 if (el.clientHeight <= 1 || el.clientWidth <= 1) continue; \
1576                 const cs = getComputedStyle(el); \
1577                 const y = el.scrollHeight - el.clientHeight; \
1578                 const x = el.scrollWidth - el.clientWidth; \
1579                 const shows = v => v === 'auto' || v === 'scroll' || v === 'hidden' || v === 'clip'; \
1580                 if ((y > 1 && shows(cs.overflowY)) || (x > 1 && shows(cs.overflowX))) { \
1581                     const test = el.getAttribute('data-test'); \
1582                     out.push(el.localName + (el.className ? '.' + String(el.className).trim().split(/\\s+/).join('.') : '') \
1583                         + (test ? `[data-test=${test}]` : '') \
1584                         + ` ${cs.overflowX}/${cs.overflowY} over by ${x}x${y}`); \
1585                 } \
1586             } \
1587             return out;";
1588
1589        let found = self
1590            .inner
1591            .execute(script, vec![element.inner.to_json()?])
1592            .await?;
1593
1594        Ok(found
1595            .json()
1596            .as_array()
1597            .into_iter()
1598            .flatten()
1599            .filter_map(|line| line.as_str().map(str::to_owned))
1600            .collect())
1601    }
1602
1603    /// **Every piece of text inside an element set smaller than `floor`
1604    /// pixels**, one line each, passing over whatever sits inside `marks`: the
1605    /// numbers of a scale or a badge's count, which are read at a glance rather
1606    /// than as words. Text nobody can see is passed over too.
1607    pub async fn small_text(
1608        &self,
1609        element: &TestElement,
1610        floor: f64,
1611        marks: &str,
1612    ) -> Result<Vec<String>> {
1613        tracing::trace!(floor, marks, "Finding text set below a size");
1614
1615        let script = format!(
1616            "const out = []; \
1617             for (const el of [arguments[0], ...arguments[0].querySelectorAll('*')]) {{ \
1618                 if (el.closest({marks:?})) continue; \
1619                 const words = Array.from(el.childNodes) \
1620                     .filter(n => n.nodeType === Node.TEXT_NODE) \
1621                     .map(n => n.textContent.trim()).join(' ').trim(); \
1622                 if (!words) continue; \
1623                 const rect = el.getBoundingClientRect(); \
1624                 if (rect.width <= 1 || rect.height <= 1) continue; \
1625                 const cs = getComputedStyle(el); \
1626                 if (cs.visibility !== 'visible') continue; \
1627                 const size = parseFloat(cs.fontSize); \
1628                 if (size < {floor}) {{ \
1629                     const test = el.getAttribute('data-test'); \
1630                     out.push(el.localName + (el.className ? '.' + String(el.className).trim().split(/\\s+/).join('.') : '') \
1631                         + (test ? `[data-test=${{test}}]` : '') \
1632                         + ` at ${{cs.fontSize}}: ${{JSON.stringify(words.slice(0, 32))}}`); \
1633                 }} \
1634             }} \
1635             return out;"
1636        );
1637
1638        let found = self
1639            .inner
1640            .execute(script, vec![element.inner.to_json()?])
1641            .await?;
1642
1643        Ok(found
1644            .json()
1645            .as_array()
1646            .into_iter()
1647            .flatten()
1648            .filter_map(|line| line.as_str().map(str::to_owned))
1649            .collect())
1650    }
1651
1652    /// **Turn the wheel and report whether anything consumed it.**
1653    ///
1654    /// Dispatches the same event as [`Self::wheel`], and returns `true` when a
1655    /// listener called `preventDefault()` on it.
1656    pub async fn wheel_consumed(&self, element: &TestElement, delta: f64) -> Result<bool> {
1657        tracing::trace!(delta, "Turning the wheel and asking who took it");
1658
1659        let script = format!(
1660            "return !arguments[0].dispatchEvent(new WheelEvent('wheel', \
1661             {{ deltaY: {delta}, bubbles: true, cancelable: true }}))"
1662        );
1663
1664        let taken = self
1665            .inner
1666            .execute(script, vec![element.inner.to_json()?])
1667            .await?;
1668
1669        Ok(taken.json().as_bool().unwrap_or(false))
1670    }
1671
1672    /// Turn the wheel over an element: a cancelable, bubbling `wheel` event
1673    /// with `deltaY` set to `delta` (positive scrolls down), dispatched on it.
1674    ///
1675    /// The event is synthesized in the page rather than sent through
1676    /// WebDriver, so it reaches the element's listeners but the browser does
1677    /// not scroll anything by itself. Returns once the event is dispatched;
1678    /// see [`Self::wheel_consumed`] to learn whether anything handled it.
1679    pub async fn wheel(&self, element: &TestElement, delta: f64) -> Result<()> {
1680        tracing::trace!(delta, "Turning the wheel over an element");
1681
1682        let script = format!(
1683            "arguments[0].dispatchEvent(new WheelEvent('wheel', \
1684             {{ deltaY: {delta}, bubbles: true, cancelable: true }}))"
1685        );
1686
1687        self.inner
1688            .execute(script, vec![element.inner.to_json()?])
1689            .await?;
1690
1691        Ok(())
1692    }
1693
1694    /// **Turn the wheel with `alt` held**, and `shift` too where asked.
1695    ///
1696    /// The pointer is put at the middle of the element rather than left at the
1697    /// origin a fresh `WheelEvent` carries: this zoom holds still whatever is
1698    /// under the pointer, so a notch at `clientY` zero anchors on the top edge
1699    /// and walks what is shown straight out of the window.
1700    pub async fn wheel_alt(&self, element: &TestElement, delta: f64, shift: bool) -> Result<()> {
1701        tracing::trace!(delta, shift, "Turning the wheel with alt held");
1702
1703        let script = format!(
1704            "const box = arguments[0].getBoundingClientRect(); \
1705             arguments[0].dispatchEvent(new WheelEvent('wheel', \
1706             {{ deltaY: {delta}, altKey: true, shiftKey: {shift}, \
1707             clientX: box.left + box.width / 2, \
1708             clientY: box.top + box.height / 2, \
1709             bubbles: true, cancelable: true }}))"
1710        );
1711
1712        self.inner
1713            .execute(script, vec![element.inner.to_json()?])
1714            .await?;
1715
1716        Ok(())
1717    }
1718
1719    /// **Turn the wheel over an element and say whether the page took it.**
1720    ///
1721    /// Both axes and `ctrl` are given, because that is what tells one turn from
1722    /// another where an element answers for more than one of them, and the
1723    /// pointer is put in the middle of the element so a zoom that holds still
1724    /// whatever is under it has something to hold.
1725    ///
1726    /// What comes back is whether the default was prevented, which is the only
1727    /// thing that separates a gesture the window answered from one it answered
1728    /// *and* let fall through to scroll the box it landed in.
1729    pub async fn wheel_over(
1730        &self,
1731        element: &TestElement,
1732        across: f64,
1733        down: f64,
1734        ctrl: bool,
1735    ) -> Result<bool> {
1736        tracing::trace!(across, down, ctrl, "Turning the wheel over both axes");
1737
1738        let script = format!(
1739            "const box = arguments[0].getBoundingClientRect(); \
1740             return !arguments[0].dispatchEvent(new WheelEvent('wheel', \
1741             {{ deltaX: {across}, deltaY: {down}, ctrlKey: {ctrl}, \
1742             clientX: box.left + box.width / 2, \
1743             clientY: box.top + box.height / 2, \
1744             bubbles: true, cancelable: true }}))"
1745        );
1746
1747        let taken = self
1748            .inner
1749            .execute(script, vec![element.inner.to_json()?])
1750            .await?;
1751
1752        Ok(taken.json().as_bool().unwrap_or(false))
1753    }
1754
1755    /// **Turn the wheel sideways**, reading as `deltaX`: the gesture a trackpad
1756    /// makes to pan, and not the one `wheel` makes.
1757    pub async fn wheel_across(&self, element: &TestElement, delta: f64) -> Result<()> {
1758        tracing::trace!(delta, "Turning the wheel sideways over an element");
1759
1760        let script = format!(
1761            "arguments[0].dispatchEvent(new WheelEvent('wheel', \
1762             {{ deltaX: {delta}, bubbles: true, cancelable: true }}))"
1763        );
1764
1765        self.inner
1766            .execute(script, vec![element.inner.to_json()?])
1767            .await?;
1768
1769        Ok(())
1770    }
1771
1772    /// Capture clipboard writes in this page without accessing the system clipboard.
1773    ///
1774    /// Replaces `navigator.clipboard.writeText` so the text it is handed is
1775    /// kept on the page instead, where [`Self::wait_copied`] reads it. Lasts
1776    /// until the page is next loaded.
1777    pub async fn capture_clipboard(&self) -> Result<()> {
1778        self.inner
1779            .execute(
1780                "const inject = document.createElement('script'); \
1781                 inject.textContent = `navigator.clipboard.writeText = async text => { \
1782                     document.body.setAttribute('data-copied', text); \
1783                 };`; \
1784                 document.documentElement.appendChild(inject); inject.remove();",
1785                Vec::new(),
1786            )
1787            .await?;
1788        Ok(())
1789    }
1790
1791    /// Delay every `WebSocket` send in this page by `millis`, so what the page
1792    /// shows while a request is in flight can be observed. Lasts until
1793    /// [`Self::stop_delaying_websocket_sends`] or the page is next loaded.
1794    ///
1795    /// This defers the call into the real `WebSocket.send`, which means it
1796    /// must not defer with the caller's own bytes: `send_with_u8_array` hands
1797    /// JS a raw view over wasm linear memory, not a copy, and musli-web's
1798    /// client reuses one scratch buffer for every request, clearing it the
1799    /// moment `send` returns. A connection something else keeps sending on
1800    /// (a poll on a timer, say) would otherwise overwrite
1801    /// that memory before a long enough delay's deferred call ever reads it,
1802    /// corrupting the frame it finally sends. `data.slice()` copies the
1803    /// bytes out synchronously, before this function returns control to the
1804    /// caller -- the same moment a real, un-shimmed `send()` would -- so the
1805    /// delay only ever holds a snapshot, the way a slow network holds bytes
1806    /// already handed off, never a live alias into memory the caller is free
1807    /// to keep mutating.
1808    pub async fn delay_websocket_sends(&self, millis: u64) -> Result<()> {
1809        self.inner.execute(format!(
1810            "const inject = document.createElement('script'); \
1811             inject.textContent = `(() => {{ \
1812                 WebSocket.__e2eOriginalSend = WebSocket.__e2eOriginalSend \
1813                     || WebSocket.prototype.send; \
1814                 const send = WebSocket.__e2eOriginalSend; \
1815                 WebSocket.prototype.send = function(data) {{ \
1816                     const copy = data && typeof data.slice === 'function' \
1817                         ? data.slice() : data; \
1818                     setTimeout(() => {{ if (this.readyState === 1) send.call(this, copy); }}, {millis}); \
1819                 }}; \
1820             }})();`; \
1821             document.documentElement.appendChild(inject); inject.remove();"
1822        ), Vec::new()).await?;
1823        Ok(())
1824    }
1825
1826    /// Undo [`Self::delay_websocket_sends`], now that whatever it was
1827    /// installed to slow down has been observed. The patched `send` stays in
1828    /// effect for the rest of the page's life otherwise, taxing every later
1829    /// request on the same connection by the same delay -- fine for a test
1830    /// that stops looking right after, a trap for one that keeps going and
1831    /// pays it on every send from here to the next page load.
1832    pub async fn stop_delaying_websocket_sends(&self) -> Result<()> {
1833        self.inner
1834            .execute(
1835                "const inject = document.createElement('script'); \
1836                 inject.textContent = `(() => { \
1837                     if (WebSocket.__e2eOriginalSend) { \
1838                         WebSocket.prototype.send = WebSocket.__e2eOriginalSend; \
1839                         delete WebSocket.__e2eOriginalSend; \
1840                     } \
1841                 })();`; \
1842                 document.documentElement.appendChild(inject); inject.remove();"
1843                    .to_owned(),
1844                Vec::new(),
1845            )
1846            .await?;
1847        Ok(())
1848    }
1849
1850    /// Wait until the text last written to the clipboard since
1851    /// [`Self::capture_clipboard`] is exactly `text`.
1852    pub async fn wait_copied(&self, text: &str) -> Result<()> {
1853        self.wait_until("the full text to be copied", async || {
1854            Ok(self.find_one_by("body").await?.attr("data-copied").await? == text)
1855        })
1856        .await
1857    }
1858
1859    /// Start watching for anything the page throws.
1860    ///
1861    /// The listener is installed by a script that keeps its names to itself,
1862    /// so it neither collides with the page's globals nor claims any the page
1863    /// declares later. It marks the body `data-watching` once it is in place,
1864    /// and this fails if that mark does not appear, since a watch that never
1865    /// started would let every throw pass unheard.
1866    ///
1867    /// What it records for a thrown error is its message followed by its
1868    /// stack, since some browsers (Firefox) keep only the frames in the stack.
1869    pub async fn watch_for_errors(&self) -> Result<()> {
1870        tracing::trace!("Listening for uncaught errors in the page");
1871
1872        let script = "if (!document.body.hasAttribute('data-watching')) { \
1873                 const inject = document.createElement('script'); \
1874                 inject.textContent = `(() => { \
1875                     const say = what => document.body.setAttribute( \
1876                         'data-threw', String(what).slice(0, 6000)); \
1877                     const told = (thrown, otherwise) => { \
1878                         if (!(thrown instanceof Error)) { return otherwise; } \
1879                         const head = String(thrown); \
1880                         const stack = thrown.stack || ''; \
1881                         return stack.startsWith(head) ? stack : head + '\\\\n' + stack; \
1882                     }; \
1883                     window.addEventListener('error', e => say(told(e.error, e.message))); \
1884                     window.addEventListener('unhandledrejection', \
1885                         e => say(told(e.reason, e.reason))); \
1886                     const was = console.error; \
1887                     console.error = (...a) => { say(a.join(' ')); was(...a); }; \
1888                     document.body.setAttribute('data-watching', ''); \
1889                 })();`; \
1890                 document.documentElement.appendChild(inject); \
1891                 inject.remove(); \
1892             } \
1893             return document.body.hasAttribute('data-watching');";
1894
1895        let watching = self.inner.execute(script, Vec::new()).await?;
1896
1897        ensure!(
1898            watching.json().as_bool() == Some(true),
1899            "the script that watches the page for errors did not run"
1900        );
1901        Ok(())
1902    }
1903
1904    /// What a page that did not become what was asked for has to say for
1905    /// itself, as a sentence to hang off a timeout: whether anything is
1906    /// mounted, what `data-page` the body carries, what it threw, and how the
1907    /// document and its bundle loaded.
1908    pub async fn what_the_page_says(&self) -> Result<String> {
1909        let script = "const b = document.body; \
1910             if (!b) { return 'and the document has no body at all'; } \
1911             const page = b.getAttribute('data-page'); \
1912             const threw = b.getAttribute('data-threw'); \
1913             const mounted = b.children.length; \
1914             let out = page ? `; the page showing is '${page}'` \
1915                 : '; nothing has claimed the page yet'; \
1916             out += `, ${mounted} element(s) are mounted under the body`; \
1917             if (threw) { out += `, and the page threw: ${threw}`; } \
1918             out += `, the document is ${document.readyState}`; \
1919             out += `, the bundle's exports are ${typeof window.wasmBindings}`; \
1920             try { new WebAssembly.Module( \
1921                 new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])); \
1922                 out += ', an empty module still compiles'; } \
1923             catch (e) { out += ', and an empty module will not compile: ' + e; } \
1924             out += ', history=' + history.length; \
1925             const nav = performance.getEntriesByType('navigation')[0]; \
1926             if (nav) { out += `, the document was answered after \
1927                 ${Math.max(0, Math.round(nav.responseEnd))}ms`; } \
1928             for (const got of performance.getEntriesByType('resource')) { \
1929                 if (!/\\.(wasm|js)(\\?|$)/.test(got.name)) { continue; } \
1930                 out += `, ${got.name.split('/').pop()} was fetched in \
1931                     ${Math.round(got.duration)}ms`; } \
1932             return out;";
1933
1934        let told = self.inner.execute(script, Vec::new()).await?;
1935        Ok(told.json().as_str().unwrap_or_default().to_owned())
1936    }
1937
1938    /// What the page threw since [`Self::watch_for_errors`], if anything did.
1939    pub async fn error_seen(&self) -> Result<Option<String>> {
1940        let body = self.find_one_by("body").await?;
1941        let seen = body.attr("data-threw").await?;
1942
1943        Ok((!seen.is_empty()).then_some(seen))
1944    }
1945
1946    /// Carry one element onto another and let go.
1947    pub async fn pointer_drag_onto(&self, from: &TestElement, to: &TestElement) -> Result<()> {
1948        from.inner.scroll_into_view().await?;
1949        self.inner
1950            .action_chain()
1951            .move_to_element_center(&from.inner)
1952            .click_and_hold()
1953            .move_by_offset(8, 0)
1954            .release_on_element(&to.inner)
1955            .perform()
1956            .await?;
1957        Ok(())
1958    }
1959
1960    /// **Carry one element over another with the pointer, the way a hand
1961    /// does, and keep hold**: press on it, move off in small steps so the
1962    /// browser starts its own drag, and come to rest over the target. Unlike
1963    /// [`Self::drag_over`] nothing is dispatched, so whatever stops the browser
1964    /// starting a drag, or a target taking one, stops this too. Let go with
1965    /// [`Self::native_release`].
1966    pub async fn native_drag_over(&self, from: &TestElement, to: &TestElement) -> Result<()> {
1967        tracing::trace!("Carrying one element over another with the pointer");
1968
1969        from.inner.scroll_into_view().await?;
1970
1971        self.inner
1972            .action_chain()
1973            .move_to_element_center(&from.inner)
1974            .click_and_hold()
1975            .move_by_offset(4, 0)
1976            .move_by_offset(8, 2)
1977            .move_by_offset(16, 4)
1978            .move_to_element_center(&to.inner)
1979            .move_by_offset(2, 0)
1980            .perform()
1981            .await?;
1982
1983        Ok(())
1984    }
1985
1986    /// Let go of every key and button the actions above hold, the WebDriver
1987    /// way, which also puts down a drag an engine would otherwise keep
1988    /// carrying into the next test.
1989    pub async fn release_all_input(&self) -> Result<()> {
1990        self.inner.action_chain().reset_actions().await?;
1991        Ok(())
1992    }
1993
1994    /// Let go of what [`Self::native_drag_over`] is holding, where it is.
1995    pub async fn native_release(&self) -> Result<()> {
1996        self.inner
1997            .action_chain()
1998            .move_by_offset(1, 0)
1999            .release()
2000            .perform()
2001            .await?;
2002        Ok(())
2003    }
2004
2005    /// **Start counting what changes in the document under `element`**: every
2006    /// node added or removed, attribute set and text changed there, and the
2007    /// element itself taken out of the page (moving it does that), and every
2008    /// canvas in it cleared to be drawn again, read back with
2009    /// [`Self::mutations`]. Watching again starts the count over.
2010    pub async fn watch_mutations(&self, element: &TestElement) -> Result<()> {
2011        self.inner
2012            .execute(
2013                "if (window.__e2eMutations) { \
2014                   window.__e2eMutations.observer.disconnect(); \
2015                   window.__e2eMutations.outer.disconnect(); \
2016                 } \
2017                 const watch = { count: 0, kinds: [] }; \
2018                 watch.observer = new MutationObserver(records => { \
2019                   watch.count += records.length; \
2020                   for (const r of records) watch.kinds.push(r.type + ':' + (r.attributeName || '') + ':' + (r.target.className || r.target.nodeName)); \
2021                 }); \
2022                 watch.observer.observe(arguments[0], \
2023                   { subtree: true, childList: true, attributes: true, characterData: true }); \
2024                 const node = arguments[0]; \
2025                 watch.outer = new MutationObserver(records => { \
2026                   for (const r of records) for (const n of r.removedNodes) \
2027                     if (n === node || n.contains(node)) { watch.count += 1; watch.kinds.push('removed'); } \
2028                 }); \
2029                 watch.outer.observe(document.body, { subtree: true, childList: true }); \
2030                 if (!window.__e2eClearRect) { \
2031                   window.__e2eClearRect = CanvasRenderingContext2D.prototype.clearRect; \
2032                   CanvasRenderingContext2D.prototype.clearRect = function (...args) { \
2033                     const watch = window.__e2eMutations; \
2034                     if (watch && watch.node.contains(this.canvas)) { watch.count += 1; watch.kinds.push('redrawn'); } \
2035                     return window.__e2eClearRect.apply(this, args); \
2036                   }; \
2037                 } \
2038                 watch.node = node; \
2039                 window.__e2eMutations = watch;",
2040                vec![element.inner.to_json()?],
2041            )
2042            .await?;
2043        Ok(())
2044    }
2045
2046    /// How many changes [`Self::watch_mutations`] has seen, and what each was:
2047    /// its kind, the attribute where it was one, and the class of the node.
2048    pub async fn mutations(&self) -> Result<(u64, Vec<String>)> {
2049        let value = self
2050            .inner
2051            .execute(
2052                "const watch = window.__e2eMutations; \
2053                 return watch ? [watch.count, watch.kinds] : [0, []];",
2054                Vec::new(),
2055            )
2056            .await?;
2057        Ok(serde_json::from_value(value.json().clone())?)
2058    }
2059
2060    /// Load real local files into a browser FileList without starting an import.
2061    pub async fn external_files(&self, paths: &str) -> Result<TestElement> {
2062        self.inner.execute("const input = document.createElement('input'); input.type = 'file'; input.multiple = true; input.hidden = true; input.dataset.test = 'external-files'; document.body.appendChild(input);", Vec::new()).await?;
2063        let input = self.find_one_by("[data-test='external-files']").await?;
2064        input.send_keys(paths).await?;
2065        Ok(input)
2066    }
2067
2068    /// Dispatch the browser file payload onto a drop target; report cancellation.
2069    pub async fn drag_external_files(
2070        &self,
2071        files: &TestElement,
2072        to: &TestElement,
2073        kind: &str,
2074    ) -> Result<bool> {
2075        let result = self.inner.execute("const data = new DataTransfer(); for (const file of arguments[0].files) data.items.add(file); const event = new DragEvent(arguments[2], {dataTransfer: data, bubbles: true, cancelable: true}); arguments[1].dispatchEvent(event); return event.defaultPrevented;", vec![files.inner.to_json()?, to.inner.to_json()?, kind.into()]).await?;
2076        Ok(serde_json::from_value(result.json().clone())?)
2077    }
2078
2079    /// Carry one element onto another through its HTML drag handlers.
2080    pub async fn drag_onto(&self, from: &TestElement, to: &TestElement) -> Result<()> {
2081        tracing::trace!("Carrying one element onto another");
2082
2083        let script = "const data = new DataTransfer(); \
2084             const fire = (node, kind) => node.dispatchEvent( \
2085                 new DragEvent(kind, \
2086                     { dataTransfer: data, bubbles: true, cancelable: true })); \
2087             fire(arguments[0], 'dragstart'); \
2088             fire(arguments[1], 'dragover'); \
2089             fire(arguments[1], 'drop'); \
2090             fire(arguments[0], 'dragend');";
2091
2092        self.inner
2093            .execute(script, vec![from.inner.to_json()?, to.inner.to_json()?])
2094            .await?;
2095
2096        Ok(())
2097    }
2098
2099    /// Carry one element over another without letting go, so that what the
2100    /// controller says about the offer can be read.
2101    pub async fn drag_over(&self, from: &TestElement, to: &TestElement) -> Result<()> {
2102        tracing::trace!("Carrying one element over another");
2103
2104        let script = "const data = new DataTransfer(); \
2105             const fire = (node, kind) => node.dispatchEvent( \
2106                 new DragEvent(kind, \
2107                     { dataTransfer: data, bubbles: true, cancelable: true })); \
2108             fire(arguments[0], 'dragstart'); \
2109             fire(arguments[1], 'dragover');";
2110
2111        self.inner
2112            .execute(script, vec![from.inner.to_json()?, to.inner.to_json()?])
2113            .await?;
2114
2115        Ok(())
2116    }
2117
2118    /// Carry a drag in progress back off the element it was over, which is the
2119    /// `dragleave` a browser sends and neither [`Self::drag_over`] nor
2120    /// [`Self::drag_onto`] does: both begin their own drag, so this is handed
2121    /// the element the carry is leaving and nothing else.
2122    pub async fn drag_off(&self, left: &TestElement) -> Result<()> {
2123        tracing::trace!("Carrying a drag back off an element");
2124
2125        let script = "const data = new DataTransfer(); \
2126             arguments[0].dispatchEvent( \
2127                 new DragEvent('dragleave', \
2128                     { dataTransfer: data, bubbles: true, cancelable: true }));";
2129
2130        self.inner
2131            .execute(script, vec![left.inner.to_json()?])
2132            .await?;
2133
2134        Ok(())
2135    }
2136
2137    /// Set a container's vertical scroll, letting the browser emit its scroll event.
2138    pub async fn scroll_top(&self, element: &TestElement, top: i32) -> Result<()> {
2139        self.inner
2140            .execute(
2141                "arguments[0].scrollTop = arguments[1];",
2142                vec![element.inner.to_json()?, serde_json::json!(top)],
2143            )
2144            .await?;
2145        Ok(())
2146    }
2147
2148    /// Pin whatever scrolls this element sideways to the far end of its travel.
2149    pub async fn scroll_to_far_end(&self, element: &TestElement) -> Result<()> {
2150        tracing::trace!("Scrolling an element's box to the end of its travel");
2151
2152        let script = "let node = arguments[0].parentElement; \
2153             while (node) { \
2154                 const how = getComputedStyle(node).overflowX; \
2155                 if ((how === 'auto' || how === 'scroll') \
2156                     && node.scrollWidth > node.clientWidth) { \
2157                     break; \
2158                 } \
2159                 node = node.parentElement; \
2160             } \
2161             if (node) { node.scrollLeft = node.scrollWidth; }";
2162
2163        self.inner
2164            .execute(script, vec![element.inner.to_json()?])
2165            .await?;
2166
2167        Ok(())
2168    }
2169
2170    /// **What the browser settled on, rather than what a rule says.**
2171    pub async fn computed(
2172        &self,
2173        element: &TestElement,
2174        pseudo: &str,
2175        property: &str,
2176    ) -> Result<String> {
2177        tracing::trace!(pseudo, property, "Asking what a property computed to");
2178
2179        let script = "return getComputedStyle(arguments[0], arguments[1] || null) \
2180             .getPropertyValue(arguments[2]);";
2181
2182        let value = self
2183            .inner
2184            .execute(
2185                script,
2186                vec![
2187                    element.inner.to_json()?,
2188                    serde_json::json!(pseudo),
2189                    serde_json::json!(property),
2190                ],
2191            )
2192            .await?;
2193
2194        Ok(value.json().as_str().unwrap_or_default().trim().to_string())
2195    }
2196
2197    /// Whether the page matches `prefers-reduced-motion: reduce`.
2198    ///
2199    /// Where `E2E_MOTION` is set this is an error when the browser disagrees
2200    /// with it, so a run meant to exercise one preference cannot quietly get
2201    /// the other. Set it (Firefox only) to test the browser's own media
2202    /// preference rather than a replacement stylesheet.
2203    pub async fn reduced_motion(&self) -> Result<bool> {
2204        let value = self
2205            .inner
2206            .execute(
2207                "return matchMedia('(prefers-reduced-motion: reduce)').matches;",
2208                Vec::new(),
2209            )
2210            .await?;
2211        let reduced = value
2212            .json()
2213            .as_bool()
2214            .context("reduced-motion media query")?;
2215        if let Ok(requested) = std::env::var("E2E_MOTION") {
2216            anyhow::ensure!(
2217                reduced == (requested == "reduce"),
2218                "browser did not honor E2E_MOTION={requested}"
2219            );
2220        }
2221        Ok(reduced)
2222    }
2223
2224    /// Pause an actual CSS animation at a deterministic phase before reading its
2225    /// computed presentation. Missing animations are failures, not idle samples.
2226    pub async fn animation_time(
2227        &self,
2228        element: &TestElement,
2229        name: &str,
2230        millis: f64,
2231    ) -> Result<()> {
2232        self.inner.execute(
2233            "const animation = arguments[0].getAnimations().find(a => a.animationName === arguments[1]); \
2234             if (!animation) throw new Error('Missing animation: ' + arguments[1]); \
2235             animation.pause(); animation.currentTime = arguments[2];",
2236            vec![element.inner.to_json()?, serde_json::json!(name), serde_json::json!(millis)],
2237        ).await?;
2238        Ok(())
2239    }
2240
2241    /// Read a computed color's alpha through the browser's color parser so both
2242    /// legacy rgba() and CSS Color 4 serialization describe the same measurement.
2243    pub async fn color_alpha(&self, element: &TestElement, property: &str) -> Result<f64> {
2244        let value = self.inner.execute(
2245            "const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; \
2246             const context = canvas.getContext('2d'); context.fillStyle = 'transparent'; \
2247             context.fillStyle = getComputedStyle(arguments[0]).getPropertyValue(arguments[1]); \
2248             context.fillRect(0, 0, 1, 1); return context.getImageData(0, 0, 1, 1).data[3] / 255;",
2249            vec![element.inner.to_json()?, serde_json::json!(property)],
2250        ).await?;
2251        value.json().as_f64().context("computed color alpha")
2252    }
2253
2254    /// **Which way a computed colour moves what is painted under it.** The
2255    /// property is filled over mid grey by the browser itself and the result
2256    /// compared with it, so a band's direction is measured rather than read off
2257    /// a serialization: negative darkens, positive lightens, zero paints
2258    /// nothing. `color-mix()` and a legacy `rgba()` are the same measurement.
2259    pub async fn color_shift(&self, element: &TestElement, property: &str) -> Result<f64> {
2260        let [red, green, blue] = self.painted(element, property).await?;
2261        Ok((red + green + blue) / 3.0 - 128.0)
2262    }
2263
2264    /// **What a computed colour actually paints**, as red, green and blue.
2265    ///
2266    /// The browser fills the property over mid grey and the pixel is read back,
2267    /// so a `color-mix()`, a legacy `rgba()` and a translucent wash all answer
2268    /// as the colour that is seen rather than as whatever the property happens
2269    /// to serialize to.
2270    pub async fn painted(&self, element: &TestElement, property: &str) -> Result<[f64; 3]> {
2271        let value = self.inner.execute(
2272            "const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; \
2273             const context = canvas.getContext('2d'); \
2274             context.fillStyle = '#808080'; context.fillRect(0, 0, 1, 1); \
2275             context.fillStyle = 'transparent'; \
2276             context.fillStyle = getComputedStyle(arguments[0]).getPropertyValue(arguments[1]); \
2277             context.fillRect(0, 0, 1, 1); \
2278             const painted = context.getImageData(0, 0, 1, 1).data; \
2279             return [painted[0], painted[1], painted[2]];",
2280            vec![element.inner.to_json()?, serde_json::json!(property)],
2281        ).await?;
2282
2283        let read = value.json();
2284        let read = read.as_array().context("what a computed colour paints")?;
2285
2286        let mut rgb = [0.0; 3];
2287
2288        for (channel, value) in rgb.iter_mut().zip(read) {
2289            *channel = value.as_f64().context("a painted channel")?;
2290        }
2291
2292        Ok(rgb)
2293    }
2294
2295    /// **A canvas's own drawn envelope**, read from its actual pixel buffer
2296    /// rather than any DOM or SVG geometry: a `<canvas>` carries no
2297    /// `points`/`viewBox` attribute a test could read instead. Samples up to `columns` evenly
2298    /// spaced points across the canvas's backing-buffer width; each entry is
2299    /// `(x, top, bottom)`, all fractions (0.0..=1.0) of the canvas's own box
2300    /// -- `x` across its width, `top`/`bottom` the first and last drawn
2301    /// (non-transparent) pixel row down its height. A sampled column with
2302    /// nothing drawn reads `(x, -1.0, -1.0)`.
2303    pub async fn canvas_columns(
2304        &self,
2305        canvas: &TestElement,
2306        columns: usize,
2307    ) -> Result<Vec<(f64, f64, f64)>> {
2308        let script = "const canvas = arguments[0]; \
2309             const columns = Math.max(1, arguments[1]); \
2310             const w = canvas.width, h = canvas.height; \
2311             if (w === 0 || h === 0) return []; \
2312             const ctx = canvas.getContext('2d'); \
2313             const data = ctx.getImageData(0, 0, w, h).data; \
2314             const step = Math.max(1, Math.floor(w / columns)); \
2315             const out = []; \
2316             for (let x = 0; x < w; x += step) { \
2317                 let top = -1, bottom = -1; \
2318                 for (let y = 0; y < h; y++) { \
2319                     if (data[(y * w + x) * 4 + 3] > 0) { \
2320                         if (top === -1) top = y; \
2321                         bottom = y; \
2322                     } \
2323                 } \
2324                 out.push([x / w, top === -1 ? -1 : top / h, bottom === -1 ? -1 : bottom / h]); \
2325             } \
2326             return out;";
2327
2328        let value = self
2329            .inner
2330            .execute(
2331                script,
2332                vec![canvas.inner.to_json()?, serde_json::json!(columns)],
2333            )
2334            .await?;
2335
2336        let read = value.json();
2337        let read = read.as_array().context("canvas column scan")?;
2338        let mut out = Vec::with_capacity(read.len());
2339
2340        for row in read {
2341            let row = row.as_array().context("a canvas column")?;
2342            let field = |at: usize, name: &str| {
2343                row.get(at)
2344                    .and_then(serde_json::Value::as_f64)
2345                    .with_context(|| format!("a canvas column's {name}"))
2346            };
2347            out.push((field(0, "x")?, field(1, "top")?, field(2, "bottom")?));
2348        }
2349
2350        Ok(out)
2351    }
2352
2353    /// A canvas's backing-buffer size in device pixels alongside its
2354    /// own CSS box and the browser's reported device pixel ratio, so a caller
2355    /// can check the three agree -- that the buffer is sized for the actual
2356    /// visible box and pixel density, not a fixed or stale guess.
2357    pub async fn canvas_size(&self, canvas: &TestElement) -> Result<CanvasSize> {
2358        let script = "const c = arguments[0]; const r = c.getBoundingClientRect(); \
2359             return [c.width, c.height, r.width, r.height, window.devicePixelRatio];";
2360
2361        let value = self
2362            .inner
2363            .execute(script, vec![canvas.inner.to_json()?])
2364            .await?;
2365        let read = value.json();
2366        let read = read.as_array().context("canvas size read")?;
2367        let field = |at: usize, name: &str| {
2368            read.get(at)
2369                .and_then(serde_json::Value::as_f64)
2370                .with_context(|| format!("canvas size's {name}"))
2371        };
2372
2373        Ok(CanvasSize {
2374            device_width: field(0, "device_width")?,
2375            device_height: field(1, "device_height")?,
2376            css_width: field(2, "css_width")?,
2377            css_height: field(3, "css_height")?,
2378            device_pixel_ratio: field(4, "device_pixel_ratio")?,
2379        })
2380    }
2381
2382    /// Press the middle button over an element.
2383    pub async fn middle_click(&self, element: &TestElement) -> Result<()> {
2384        tracing::trace!("Middle-clicking an element");
2385
2386        let script = "for (const type of ['mousedown', 'mouseup', 'auxclick']) {\
2387             arguments[0].dispatchEvent(new MouseEvent(type, \
2388             { button: 1, buttons: 4, bubbles: true, cancelable: true })); \
2389         }";
2390
2391        self.inner
2392            .execute(script, vec![element.inner.to_json()?])
2393            .await?;
2394
2395        Ok(())
2396    }
2397
2398    /// Pan with a native middle-button drag, releasing the button at the end.
2399    pub async fn middle_drag_by(&self, element: &TestElement, dx: i64) -> Result<()> {
2400        use thirtyfour::common::command::Command;
2401
2402        let actions = serde_json::json!([{
2403            "type": "pointer", "id": "pointer", "parameters": {"pointerType": "mouse"},
2404            "actions": [
2405                {"type": "pointerMove", "duration": 0, "origin": element.inner.to_json()?, "x": 0, "y": 0},
2406                {"type": "pointerDown", "button": 1},
2407                {"type": "pointerMove", "duration": 150, "origin": "pointer", "x": dx, "y": 0},
2408                {"type": "pointerUp", "button": 1}
2409            ]
2410        }]);
2411        self.inner
2412            .cmd(Command::PerformActions(actions.into()))
2413            .await?;
2414        Ok(())
2415    }
2416
2417    /// Carry a held drag somewhere else without letting go of it.
2418    pub async fn move_held(&self, dx: i64, dy: i64) -> Result<()> {
2419        tracing::trace!(dx, dy, "Carrying a held drag");
2420
2421        self.inner
2422            .action_chain()
2423            .move_by_offset(dx, dy)
2424            .perform()
2425            .await?;
2426
2427        Ok(())
2428    }
2429
2430    /// Let go of whatever [`TestElement::drag_by`] is holding.
2431    pub async fn drop_held(&self) -> Result<()> {
2432        tracing::trace!("Releasing a held drag");
2433        self.inner.action_chain().release().perform().await?;
2434        Ok(())
2435    }
2436
2437    /// Cancel a captured pointer without releasing the test's held button, so
2438    /// a later mouse-up can prove that cancelled work is not committed.
2439    pub async fn cancel_pointer(&self, element: &TestElement) -> Result<()> {
2440        self.inner
2441            .execute(
2442                "arguments[0].dispatchEvent(new PointerEvent('pointercancel', { bubbles: true }));",
2443                vec![element.inner.to_json()?],
2444            )
2445            .await?;
2446        Ok(())
2447    }
2448
2449    /// The same for a drag that was begun with `alt` held, which has to give
2450    /// the key back as well as the button.
2451    pub async fn drop_held_alt(&self) -> Result<()> {
2452        tracing::trace!("Releasing a held drag and the alt key with it");
2453
2454        self.inner
2455            .action_chain()
2456            .release()
2457            .key_up(thirtyfour::Key::Alt)
2458            .perform()
2459            .await?;
2460
2461        Ok(())
2462    }
2463
2464    /// Whether what is drawn at one point of the page belongs to `selector` and
2465    /// nothing is standing over it. A frame says what is drawn somewhere but
2466    /// not what drew it, so a test measuring a window's own content has to be
2467    /// able to tell that content from whatever floats in front of it.
2468    ///
2469    /// Two questions, because one does not do. Hit testing says which element
2470    /// is uppermost at the point, which settles the ordinary case. But a menu,
2471    /// a drag ghost or a help bubble is drawn through a portal into the
2472    /// document body, over the top of a window and often wider than it, and a
2473    /// bubble takes no pointer events at all -- hit testing looks straight
2474    /// through it and answers with the window underneath. So anything portaled
2475    /// beside the application is asked separately whether it covers the point.
2476    ///
2477    /// The point is in the page's own pixels, not the frame's.
2478    pub async fn drawn_inside(&self, selector: &str, x: f64, y: f64) -> Result<bool> {
2479        tracing::trace!(selector, x, y, "Asking what is drawn at a point");
2480
2481        let script = "const [selector, x, y] = arguments; \
2482             const host = document.querySelector(selector); \
2483             const found = document.elementFromPoint(x, y); \
2484             if (!host || !found || !host.contains(found)) return false; \
2485             for (const over of document.body.children) { \
2486                 if (over.contains(host) || host.contains(over)) continue; \
2487                 const box = over.getBoundingClientRect(); \
2488                 if (x >= box.left && x <= box.right && y >= box.top && y <= box.bottom) \
2489                     return false; \
2490             } \
2491             return true;";
2492
2493        let value = self
2494            .inner
2495            .execute(
2496                script,
2497                vec![
2498                    serde_json::json!(selector),
2499                    serde_json::json!(x),
2500                    serde_json::json!(y),
2501                ],
2502            )
2503            .await?;
2504
2505        Ok(value.json().as_bool().unwrap_or_default())
2506    }
2507
2508    /// A screenshot of the whole page as the PNG the browser hands back, for a
2509    /// test that reads a frame rather than writing one out. Taken whether or
2510    /// not `E2E_SHOTS` is set, since an assertion that measures a frame has to
2511    /// have one on every run rather than only when somebody is looking.
2512    pub async fn screenshot_png(&self) -> Result<Vec<u8>> {
2513        tracing::trace!("Taking a screenshot");
2514        Ok(self.inner.screenshot_as_png().await?)
2515    }
2516
2517    /// Write a screenshot of the whole page to `path`.
2518    pub async fn screenshot(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
2519        std::fs::write(path, self.screenshot_png().await?)?;
2520        Ok(())
2521    }
2522
2523    /// The same, into `$E2E_SHOTS/<name>.png`, and nothing at all when that is
2524    /// unset. Left in a test rather than added and removed, since it costs nothing
2525    /// on an ordinary run.
2526    ///
2527    /// **`E2E_SHOTS` is a directory, and it reads like a flag.** A relative one
2528    /// is taken under `target/e2e-shots`, where everything else the suite leaves
2529    /// behind goes — so `E2E_SHOTS=1`, which is what a hand types when it means
2530    /// *yes*, writes to `target/e2e-shots/1` rather than making a directory
2531    /// called `1` in whatever the test process's working directory happens to
2532    /// be, which under cargo is the package, in the checkout.
2533    ///
2534    /// ```text
2535    /// E2E_SHOTS=1 cargo test -p app-e2e -- cart::
2536    /// E2E_SHOTS=/tmp/shots cargo test -p app-e2e -- cart::
2537    /// ```
2538    pub async fn snapshot(&self, name: &str) -> Result<()> {
2539        let Some(dir) = std::env::var_os("E2E_SHOTS") else {
2540            return Ok(());
2541        };
2542
2543        let dir = std::path::PathBuf::from(dir);
2544
2545        let dir = match dir.is_absolute() {
2546            true => dir,
2547            false => crate::dist::target_dir()?.join("e2e-shots").join(dir),
2548        };
2549
2550        std::fs::create_dir_all(&dir)?;
2551
2552        let path = dir.join(format!("{name}.png"));
2553        tracing::info!(path = %path.display(), "Writing snapshot");
2554        self.screenshot(&path).await
2555    }
2556
2557    /// Press the `index`th element matching `by`, re-finding it if the page
2558    /// moves underneath.
2559    pub async fn press_nth(&self, by: impl IntoBy, index: usize) -> Result<()> {
2560        let by = by.into_by();
2561
2562        tracing::trace!(?by, index, "Pressing element");
2563
2564        let deadline = time::Instant::now() + self.wait_timeout;
2565
2566        loop {
2567            let found = self.find_all(by.clone()).await?;
2568
2569            if let Some(item) = found.get(index)
2570                && item.click().await.is_ok()
2571            {
2572                return Ok(());
2573            }
2574
2575            if time::Instant::now() >= deadline {
2576                bail!(
2577                    "Timed out after {:?} pressing {by} at {index}",
2578                    self.wait_timeout
2579                );
2580            }
2581
2582            time::sleep(POLL_INTERVAL).await;
2583        }
2584    }
2585
2586    /// The same as [`TestDriver::press_nth`], right-handed. A context menu that
2587    /// belongs to a thing is opened on the thing itself, so there is no button
2588    /// to press and this is how a test reaches one.
2589    pub async fn context_press_nth(&self, by: impl IntoBy, index: usize) -> Result<()> {
2590        let by = by.into_by();
2591
2592        tracing::trace!(?by, index, "Right-clicking element");
2593
2594        let deadline = time::Instant::now() + self.wait_timeout;
2595
2596        loop {
2597            let found = self.find_all(by.clone()).await?;
2598
2599            if let Some(item) = found.get(index)
2600                && item.context_click().await.is_ok()
2601            {
2602                return Ok(());
2603            }
2604
2605            if time::Instant::now() >= deadline {
2606                bail!(
2607                    "Timed out after {:?} right-clicking {by} at {index}",
2608                    self.wait_timeout
2609                );
2610            }
2611
2612            time::sleep(POLL_INTERVAL).await;
2613        }
2614    }
2615
2616    /// Read a browser-persisted setting without changing it.
2617    pub async fn local_storage(&self, key: &str) -> Result<Option<String>> {
2618        let value = self
2619            .inner
2620            .execute(
2621                "return localStorage.getItem(arguments[0]);",
2622                vec![serde_json::json!(key)],
2623            )
2624            .await?;
2625        Ok(value.json().as_str().map(str::to_owned))
2626    }
2627
2628    /// Seed a persisted setting before mounting the component that reads it.
2629    pub async fn set_local_storage(&self, key: &str, value: &str) -> Result<()> {
2630        self.inner
2631            .execute(
2632                "localStorage.setItem(arguments[0], arguments[1]);",
2633                vec![serde_json::json!(key), serde_json::json!(value)],
2634            )
2635            .await?;
2636        Ok(())
2637    }
2638
2639    /// Deny access for the current document, as when browser policy blocks storage.
2640    pub async fn block_local_storage(&self) -> Result<()> {
2641        self.inner.execute(
2642            "const script = document.createElement('script'); \
2643             script.textContent = `Object.defineProperty(window, 'localStorage', {configurable: true, get() { throw new DOMException('Storage blocked by test', 'SecurityError'); }});`; \
2644             document.documentElement.appendChild(script); script.remove();",
2645            vec![],
2646        ).await?;
2647        Ok(())
2648    }
2649
2650    /// Reload the page, which is the only way to ask what the *server* holds.
2651    pub async fn reload(&self) -> Result<()> {
2652        tracing::trace!("Reloading the page");
2653        self.inner.refresh().await?;
2654
2655        let _ = self.watch_for_errors().await;
2656        Ok(())
2657    }
2658
2659    /// Open the page again with `query` in the address.
2660    pub async fn reopen_with(&self, query: &str) -> Result<()> {
2661        tracing::trace!(query, "Reopening the page");
2662
2663        let mut url = self.inner.current_url().await?;
2664        url.set_query(Some(query));
2665        self.inner.goto(url.as_str()).await?;
2666        Ok(())
2667    }
2668
2669    /// Run `run` in a second tab showing the page this one shows, then close
2670    /// it and come back. The tab is sized as every test's first one is, and
2671    /// `run` is what waits for the page to come up; what the page threw fails
2672    /// it as it would the test.
2673    pub async fn in_second_tab(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
2674        self.in_second_context(true, run).await
2675    }
2676
2677    /// The same in a second window.
2678    pub async fn in_second_window(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
2679        self.in_second_context(false, run).await
2680    }
2681
2682    async fn in_second_context(
2683        &self,
2684        tab: bool,
2685        run: impl AsyncFnOnce() -> Result<()>,
2686    ) -> Result<()> {
2687        let original = self.inner.window().await?;
2688        let url = self.inner.current_url().await?;
2689        let opened = if tab {
2690            self.inner.new_tab().await?
2691        } else {
2692            self.inner.new_window().await?
2693        };
2694
2695        let result = async {
2696            self.inner.switch_to_window(opened.clone()).await?;
2697            self.set_window_size(WINDOW.0, WINDOW.1).await?;
2698            self.inner.goto(url.as_str()).await?;
2699            run().await?;
2700            match self.error_seen().await? {
2701                Some(threw) => bail!("the page threw: {threw}"),
2702                None => Ok(()),
2703            }
2704        }
2705        .await;
2706
2707        let cleanup = async {
2708            self.inner.switch_to_window(opened).await?;
2709            self.inner.close_window().await?;
2710            self.inner.switch_to_window(original).await?;
2711            Ok(())
2712        }
2713        .await;
2714
2715        match result {
2716            Ok(()) => cleanup,
2717            Err(error) => Err(with_cleanup(error, cleanup)),
2718        }
2719    }
2720
2721    /// Press a key with nothing in particular focused, the way a hand does when
2722    /// it has just opened something with the pointer.
2723    pub async fn press_key(&self, key: Key) -> Result<()> {
2724        tracing::trace!(?key, "Pressing a key");
2725        self.inner.action_chain().send_keys(key).perform().await?;
2726        Ok(())
2727    }
2728
2729    /// Hold a real WebDriver key across observations, rather than sending a
2730    /// down/up pair too quickly for an animation frame to show it.
2731    pub async fn hold_key(&self, key: char) -> Result<()> {
2732        self.inner.action_chain().key_down(key).perform().await?;
2733        Ok(())
2734    }
2735
2736    /// Let go of a key held with [`Self::hold_key`].
2737    pub async fn release_key(&self, key: char) -> Result<()> {
2738        self.inner.action_chain().key_up(key).perform().await?;
2739        Ok(())
2740    }
2741
2742    /// **Every match's attribute, read in one pass.** Reading them one handle
2743    /// at a time is how a test goes stale against a window that redraws on the
2744    /// animation frame: the elements it is holding are replaced between two reads
2745    /// and the second one throws.
2746    pub async fn find_all_attrs(&self, selector: &str, attr: &str) -> Result<Vec<String>> {
2747        let script = format!(
2748            "return Array.from(document.querySelectorAll({})) \
2749             .map(n => n.getAttribute({}) ?? '')",
2750            serde_json::to_string(selector)?,
2751            serde_json::to_string(attr)?,
2752        );
2753
2754        let read = self.inner.execute(script, Vec::new()).await?;
2755
2756        Ok(read
2757            .json()
2758            .as_array()
2759            .map(|rows| {
2760                rows.iter()
2761                    .map(|row| row.as_str().unwrap_or_default().to_owned())
2762                    .collect()
2763            })
2764            .unwrap_or_default())
2765    }
2766
2767    /// **Where every match sits down the page, with the attribute that names
2768    /// it, in one pass.** A band is a top and a height, which is all two things
2769    /// drawn in different columns have to agree about.
2770    ///
2771    /// Measuring a hundred elements one handle at a time is a round trip each
2772    /// for the attribute and another for the box, which is a test that runs out
2773    /// of time rather than one that fails. A node the browser is not drawing has
2774    /// no box and is left out, so a count is also an answer to what is shown.
2775    pub async fn bands(&self, selector: &str, attr: &str) -> Result<Vec<(String, f64, f64)>> {
2776        let script = format!(
2777            "return Array.from(document.querySelectorAll({})) \
2778             .filter(n => n.getClientRects().length > 0) \
2779             .map(n => [n.getAttribute({}) ?? '', \
2780             n.getBoundingClientRect().top, n.getBoundingClientRect().height])",
2781            serde_json::to_string(selector)?,
2782            serde_json::to_string(attr)?,
2783        );
2784
2785        let read = self.inner.execute(script, Vec::new()).await?;
2786        let read = read.json();
2787
2788        let rows = read.as_array().context("a list of bands")?;
2789        let mut bands = Vec::with_capacity(rows.len());
2790
2791        for row in rows {
2792            let row = row.as_array().context("a band")?;
2793
2794            bands.push((
2795                row.first()
2796                    .and_then(|name| name.as_str())
2797                    .unwrap_or_default()
2798                    .to_owned(),
2799                row.get(1).and_then(|top| top.as_f64()).context("a top")?,
2800                row.get(2)
2801                    .and_then(|height| height.as_f64())
2802                    .context("a height")?,
2803            ));
2804        }
2805
2806        Ok(bands)
2807    }
2808
2809    /// Dispatch a named key on a focused element, including keys WebDriver cannot encode.
2810    pub async fn press_key_on(&self, selector: &str, key: &str) -> Result<()> {
2811        let script = format!(
2812            "const at = document.querySelector({}); \
2813             if (!at) throw new Error('No element for keyboard press'); \
2814             at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
2815             {{ key: {}, bubbles: true, cancelable: true }}));",
2816            serde_json::to_string(selector)?,
2817            serde_json::to_string(key)?,
2818        );
2819        self.inner.execute(script, Vec::new()).await?;
2820        Ok(())
2821    }
2822
2823    /// **Press a key on one element with `control` held**, which is how undo,
2824    /// redo and select-all are reached.
2825    ///
2826    /// Dispatched on the element so the press lands where the test says. The
2827    /// event carries the `code` a real letter key does, since a listener on
2828    /// the document may read the code and a press without one would never
2829    /// reach it.
2830    pub async fn press_key_with_ctrl(&self, selector: &str, key: &str) -> Result<()> {
2831        tracing::trace!(selector, key, "Pressing a key with control held");
2832
2833        let code = match key.chars().collect::<Vec<_>>().as_slice() {
2834            [c] if c.is_ascii_alphabetic() => format!("Key{}", c.to_ascii_uppercase()),
2835            _ => key.to_owned(),
2836        };
2837
2838        let script = format!(
2839            "const at = document.querySelector({}); \
2840             if (at) {{ at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
2841             {{ key: {}, code: {}, ctrlKey: true, bubbles: true, cancelable: true }})); }}",
2842            serde_json::to_string(selector)?,
2843            serde_json::to_string(key)?,
2844            serde_json::to_string(&code)?,
2845        );
2846
2847        self.inner.execute(script, Vec::new()).await?;
2848        Ok(())
2849    }
2850
2851    /// **Press a key on one element with shift held**, dispatched for the
2852    /// same reason [`Self::press_key_with_ctrl`] is.
2853    pub async fn press_key_with_shift(&self, selector: &str, key: &str) -> Result<()> {
2854        tracing::trace!(selector, key, "Pressing a key with shift held");
2855
2856        let script = format!(
2857            "const at = document.querySelector({}); \
2858             if (at) {{ at.focus(); at.dispatchEvent(new KeyboardEvent('keydown', \
2859             {{ key: {}, shiftKey: true, bubbles: true, cancelable: true }})); }}",
2860            serde_json::to_string(selector)?,
2861            serde_json::to_string(key)?,
2862        );
2863
2864        self.inner.execute(script, Vec::new()).await?;
2865        Ok(())
2866    }
2867
2868    /// Take keyboard focus off whatever has it, so the next key lands on the
2869    /// page rather than on a control.
2870    pub async fn blur(&self) -> Result<()> {
2871        tracing::trace!("Blurring the focused element");
2872
2873        self.inner
2874            .execute(
2875                "document.activeElement && document.activeElement.blur();",
2876                Vec::new(),
2877            )
2878            .await?;
2879
2880        Ok(())
2881    }
2882
2883    /// One attribute of whatever element has keyboard focus, or `None` when
2884    /// it has no such attribute. Where nothing is focused, that is the
2885    /// document's `<body>`.
2886    ///
2887    /// Answers once, at the time of asking; it does not wait.
2888    pub async fn focused_attr(&self, name: &str) -> Result<Option<String>> {
2889        let found = self
2890            .inner
2891            .execute(
2892                "return document.activeElement \
2893                 && document.activeElement.getAttribute(arguments[0])",
2894                vec![serde_json::json!(name)],
2895            )
2896            .await?;
2897
2898        Ok(found.json().as_str().map(str::to_owned))
2899    }
2900
2901    common!();
2902}
2903
2904/// **Anything that names elements to find**, taken by every lookup on
2905/// [`TestDriver`] that says `by`.
2906///
2907/// A string (`&str` or `&String`) is a CSS selector; any other way of finding
2908/// elements is written out as a [`By`].
2909///
2910/// # Examples
2911///
2912/// ```no_run
2913/// use yew_e2e::prelude::*;
2914///
2915/// async fn lookups(driver: &TestDriver) -> Result<()> {
2916///     // A CSS selector.
2917///     driver.wait_count("li.item", 3).await?;
2918///
2919///     // One that was built rather than written out.
2920///     let id = 7;
2921///     driver.find_one_by(&format!("[data-test=row-{id}]")).await?;
2922///
2923///     // Any other `By`.
2924///     driver.find_first(By::XPath("//button[text()='Save']")).await?;
2925///     Ok(())
2926/// }
2927/// ```
2928pub trait IntoBy {
2929    /// The [`By`] this names.
2930    fn into_by(self) -> By;
2931}
2932
2933impl IntoBy for &str {
2934    #[inline]
2935    fn into_by(self) -> By {
2936        By::Css(self)
2937    }
2938}
2939
2940/// A selector that was built rather than written out, such as one naming a
2941/// control whose `data-test` carries an identifier in it.
2942impl IntoBy for &String {
2943    #[inline]
2944    fn into_by(self) -> By {
2945        By::Css(self.as_str())
2946    }
2947}
2948
2949impl IntoBy for By {
2950    #[inline]
2951    fn into_by(self) -> By {
2952        self
2953    }
2954}