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`, named for the Chrome build it matches so that
116//! an updated Chrome fetches a new one. Two suites sharing one build directory give
117//! each other room with [`Config::sessions_dir`] and [`Config::lock_name`].
118//!
119//! <br>
120//!
121//! ## Running
122//!
123//! ```sh
124//! cargo test -p app-e2e # everything
125//! cargo test -p app-e2e -- cart:: # everything whose name contains cart::
126//! cargo test -p app-e2e -- --exact cart::adds_an_item
127//! cargo test -p app-e2e -- --list # the names, one per line, on stdout
128//! cargo test -p app-e2e -- --last-session # what did not pass last time
129//! ```
130//!
131//! | Flag | |
132//! |---|---|
133//! | `-j`, `--parallel N` | How many tests run at once, each in its own browser. Defaults to 2. |
134//! | `--headed` | Show the browsers. |
135//! | `--browser firefox\|chrome` | Which browser to drive. Detected where not given. |
136//! | `--exact` | Filters match whole names rather than parts of them. |
137//! | `--list` | List the selected tests and run nothing. |
138//! | `--allow-empty` | A run that selects nothing passes rather than fails. |
139//! | `--last-session`, `--session NAME` | Run only what did not pass in that session. |
140//! | `--timeout SECONDS` | How long one test may run. Defaults to 30; 0 waits for ever. |
141//! | `--grace SECONDS` | How long a running test is given to finish after Ctrl-C or SIGTERM. |
142//! | `--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. |
143//! | `--lock-wait SECONDS` | How long to wait for that lock. |
144//!
145//! | Variable | |
146//! |---|---|
147//! | `E2E_HEADED` | As `--headed`. |
148//! | `E2E_BROWSER` | As `--browser`. |
149//! | `E2E_DIST` | A frontend that is already built, served in place of building one. |
150//! | `E2E_THEME` | `dark` or `light`, for the colour scheme the browser reports (Firefox). |
151//! | `E2E_MOTION` | `reduce` or `normal`, for the motion preference the browser reports (Firefox). |
152//! | `E2E_SCALE` | The device pixel ratio the browser reports. |
153//! | `E2E_SHOTS` | Where [`TestDriver::snapshot`] writes; relative to `target/e2e-shots`. |
154//!
155//! [`Config::lock_name`]: https://docs.rs/yew-e2e/latest/yew_e2e/struct.Config.html#method.lock_name
156//! [`Config::sessions_dir`]: https://docs.rs/yew-e2e/latest/yew_e2e/struct.Config.html#method.sessions_dir
157//! [`dist()`]: https://docs.rs/yew-e2e/latest/yew_e2e/fn.dist.html
158//! [`examples/static_page.rs`]: https://github.com/udoprog/yew-e2e/blob/main/examples/static_page.rs
159//! [`Fixture`]: https://docs.rs/yew-e2e/latest/yew_e2e/trait.Fixture.html
160//! [`Frontend::None`]: https://docs.rs/yew-e2e/latest/yew_e2e/enum.Frontend.html#variant.None
161//! [`Frontend::Trunk(dir)`]: https://docs.rs/yew-e2e/latest/yew_e2e/enum.Frontend.html#variant.Trunk
162//! [`harness!`]: https://docs.rs/yew-e2e/latest/yew_e2e/macro.harness.html
163//! [`TestDriver::snapshot`]: https://docs.rs/yew-e2e/latest/yew_e2e/struct.TestDriver.html#method.snapshot
164//! [`TestDriver`]: https://docs.rs/yew-e2e/latest/yew_e2e/struct.TestDriver.html
165//! [Trunk]: https://trunkrs.dev
166//! [Yew]: https://yew.rs
167
168#![warn(missing_docs)]
169#![deny(rustdoc::broken_intra_doc_links)]
170
171use std::future::Future;
172use std::path::PathBuf;
173
174use anyhow::Result;
175
176mod browser;
177mod dist;
178mod driver;
179mod element;
180mod fetch;
181mod finding;
182pub mod harness;
183#[cfg(test)]
184mod lib_tests;
185mod run_lock;
186mod sessions;
187mod test_driver;
188
189pub use self::dist::{dist, target_dir, workspace_root};
190pub use self::driver::Engine;
191pub use self::element::TestElement;
192pub use self::finding::{IntoBy, POLL_INTERVAL};
193pub use self::test_driver::{CanvasSize, TestDriver};
194
195pub(crate) use self::browser::{Browser, Holding, WINDOW, Waiting, overran, run_one};
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}