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