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, [`Frontend::Trug(dir)`] does the same with `trug build`
111//! for an app built with [trug], and [`Frontend::None`] builds nothing, for a
112//! fixture that serves its own pages. `E2E_DIST` names a frontend already built,
113//! to serve in place of building one.
114//!
115//! Everything else a run leaves behind goes under the build directory too: the
116//! record of every run in `target/e2e-sessions`, the run lock, a fetched
117//! `chromedriver` in `target/e2e`, named for the Chrome build it matches so that
118//! an updated Chrome fetches a new one. Two suites sharing one build directory give
119//! each other room with [`Config::sessions_dir`] and [`Config::lock_name`].
120//!
121//! <br>
122//!
123//! ## Running
124//!
125//! ```sh
126//! cargo test -p app-e2e # everything
127//! cargo test -p app-e2e -- cart:: # everything whose name contains cart::
128//! cargo test -p app-e2e -- --exact cart::adds_an_item
129//! cargo test -p app-e2e -- --list # the names, one per line, on stdout
130//! cargo test -p app-e2e -- --last-session # what did not pass last time
131//! ```
132//!
133//! | Flag | |
134//! |---|---|
135//! | `-j`, `--parallel N` | How many tests run at once, each in its own browser. Defaults to 2. |
136//! | `--headed` | Show the browsers. |
137//! | `--browser firefox\|chrome` | Which browser to drive. Detected where not given. |
138//! | `--exact` | Filters match whole names rather than parts of them. |
139//! | `--list` | List the selected tests and run nothing. |
140//! | `--allow-empty` | A run that selects nothing passes rather than fails. |
141//! | `--last-session`, `--session NAME` | Run only what did not pass in that session. |
142//! | `--timeout SECONDS` | How long one test may run. Defaults to 30; 0 waits for ever. |
143//! | `--grace SECONDS` | How long a running test is given to finish after Ctrl-C or SIGTERM. |
144//! | `--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. |
145//! | `--lock-wait SECONDS` | How long to wait for that lock. |
146//!
147//! | Variable | |
148//! |---|---|
149//! | `E2E_HEADED` | As `--headed`. |
150//! | `E2E_BROWSER` | As `--browser`. |
151//! | `E2E_DIST` | A frontend that is already built, served in place of building one. |
152//! | `E2E_THEME` | `dark` or `light`, for the colour scheme the browser reports (Firefox). |
153//! | `E2E_MOTION` | `reduce` or `normal`, for the motion preference the browser reports (Firefox). |
154//! | `E2E_SCALE` | The device pixel ratio the browser reports. |
155//! | `E2E_SHOTS` | Where [`TestDriver::snapshot`] writes; relative to `target/e2e-shots`. |
156//!
157//! [`Config::lock_name`]: https://docs.rs/yew-e2e/latest/yew_e2e/struct.Config.html#method.lock_name
158//! [`Config::sessions_dir`]: https://docs.rs/yew-e2e/latest/yew_e2e/struct.Config.html#method.sessions_dir
159//! [`dist()`]: https://docs.rs/yew-e2e/latest/yew_e2e/fn.dist.html
160//! [`examples/static_page.rs`]: https://github.com/udoprog/yew-e2e/blob/main/examples/static_page.rs
161//! [`Fixture`]: https://docs.rs/yew-e2e/latest/yew_e2e/trait.Fixture.html
162//! [`Frontend::None`]: https://docs.rs/yew-e2e/latest/yew_e2e/enum.Frontend.html#variant.None
163//! [`Frontend::Trunk(dir)`]: https://docs.rs/yew-e2e/latest/yew_e2e/enum.Frontend.html#variant.Trunk
164//! [`Frontend::Trug(dir)`]: https://docs.rs/yew-e2e/latest/yew_e2e/enum.Frontend.html#variant.Trug
165//! [`harness!`]: https://docs.rs/yew-e2e/latest/yew_e2e/macro.harness.html
166//! [`TestDriver::snapshot`]: https://docs.rs/yew-e2e/latest/yew_e2e/struct.TestDriver.html#method.snapshot
167//! [`TestDriver`]: https://docs.rs/yew-e2e/latest/yew_e2e/struct.TestDriver.html
168//! [Trunk]: https://trunkrs.dev
169//! [trug]: https://github.com/udoprog/trug
170//! [Yew]: https://yew.rs
171
172#![warn(missing_docs)]
173#![deny(rustdoc::broken_intra_doc_links)]
174
175use std::future::Future;
176use std::path::PathBuf;
177
178use anyhow::Result;
179
180mod browser;
181mod dist;
182mod driver;
183mod element;
184mod fetch;
185mod finding;
186pub mod harness;
187#[cfg(test)]
188mod lib_tests;
189mod run_lock;
190mod sessions;
191mod test_driver;
192
193pub use self::dist::{dist, target_dir, workspace_root};
194pub use self::driver::Engine;
195pub use self::element::TestElement;
196pub use self::finding::{IntoBy, POLL_INTERVAL};
197pub use self::test_driver::{CanvasSize, TestDriver};
198
199pub(crate) use self::browser::{Browser, Holding, WINDOW, Waiting, overran, run_one};
200
201/// What a test file needs in scope, in one `use yew_e2e::prelude::*;`.
202///
203/// That is [`anyhow`](mod@anyhow)'s [`Result`] and error macros, the whole of
204/// `thirtyfour`'s prelude (among it [`By`], [`Key`] and [`WebDriver`]), and
205/// the [`TestDriver`] and [`TestElement`] a test is handed.
206///
207/// [`Result`]: anyhow::Result
208/// [`By`]: thirtyfour::By
209/// [`Key`]: thirtyfour::Key
210/// [`WebDriver`]: thirtyfour::WebDriver
211pub mod prelude {
212 pub use anyhow::{Context, Result, anyhow, bail, ensure};
213 pub use thirtyfour::prelude::*;
214
215 /// What every test is handed, so its signature can be written without a
216 /// `use` per file saying so.
217 pub use crate::{TestDriver, TestElement};
218}
219
220/// **The application under test**, started afresh for every test and taken
221/// down after it.
222///
223/// A suite names one fixture in [`harness!`], and every test is handed the one
224/// started for it beside the browser, so whatever a test needs to reach behind
225/// the page (a database, a port, a channel into the server) is its own.
226pub trait Fixture: Sized + 'static {
227 /// What one test asks of the fixture started for it. [`harness!`] sets a
228 /// `bool` field of this for every word in the parentheses after a test's
229 /// name; `()` where no test asks for anything.
230 type Setup: Default;
231
232 /// How this suite is run: its name, its frontend and its lock.
233 fn config() -> Config {
234 Config::default()
235 }
236
237 /// Install the run's tracing subscriber. The default prints `INFO` and
238 /// above.
239 fn init_tracing() {
240 _ = tracing_subscriber::fmt()
241 .with_max_level(tracing::Level::INFO)
242 .try_init();
243 }
244
245 /// Start the application for one test.
246 fn start(setup: Self::Setup) -> impl Future<Output = Result<Self>>;
247
248 /// Where the browser is pointed for this test.
249 fn url(&self) -> String;
250
251 /// Take the application down once its test has finished.
252 fn quit(self) -> impl Future<Output = Result<()>>;
253}
254
255/// How a suite is run; see [`Fixture::config`].
256#[derive(Debug, Clone)]
257pub struct Config {
258 pub(crate) about: String,
259 pub(crate) frontend: Frontend,
260 pub(crate) lock: String,
261 pub(crate) sessions: String,
262}
263
264impl Default for Config {
265 fn default() -> Self {
266 Self {
267 about: String::from("A browser suite."),
268 frontend: Frontend::Trunk(PathBuf::new()),
269 lock: String::from("yew-e2e.lock"),
270 sessions: String::from("e2e-sessions"),
271 }
272 }
273}
274
275impl Config {
276 /// The one line `--help` opens with.
277 pub fn about(mut self, about: impl Into<String>) -> Self {
278 self.about = about.into();
279 self
280 }
281
282 /// What the suite serves, and how it is built.
283 pub fn frontend(mut self, frontend: Frontend) -> Self {
284 self.frontend = frontend;
285 self
286 }
287
288 /// What the run lock is called inside whichever directory `--lock` names.
289 pub fn lock_name(mut self, name: impl Into<String>) -> Self {
290 self.lock = name.into();
291 self
292 }
293
294 /// Where under the build directory the record of every run is kept, which
295 /// is what `--last-session` reads the newest of. Two suites sharing a
296 /// build directory name one each, or each picks up the other's runs.
297 pub fn sessions_dir(mut self, name: impl Into<String>) -> Self {
298 self.sessions = name.into();
299 self
300 }
301}
302
303/// The frontend a suite serves, built once for the whole run; [`dist`] is
304/// where it ends up.
305#[derive(Debug, Clone)]
306pub enum Frontend {
307 /// Nothing to build: the fixture serves its own pages.
308 None,
309 /// `trunk build` run in this directory, relative to the workspace root,
310 /// into `e2e-dist` under the build directory. `E2E_DIST` names a frontend
311 /// already built in its place.
312 Trunk(PathBuf),
313 /// `trug build` run in this directory, relative to the workspace root,
314 /// into `e2e-dist` under the build directory. `E2E_DIST` names a frontend
315 /// already built in its place.
316 Trug(PathBuf),
317}