Skip to main content

yew_e2e/
lib.rs

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