Skip to main content

yew_e2e/
driver.rs

1//! Which browser the suite drives, and the WebDriver server that drives it.
2
3use std::fmt;
4use std::future::Future;
5use std::net::SocketAddr;
6use std::path::PathBuf;
7use std::str::FromStr;
8use std::time::Duration;
9
10use anyhow::{Context, Result, anyhow, bail, ensure};
11use thirtyfour::common::capabilities::firefox::FirefoxPreferences;
12use thirtyfour::prelude::*;
13use tokio::time::{Instant, timeout};
14
15pub(crate) const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
16pub(crate) const QUIT_TIMEOUT: Duration = Duration::from_secs(5);
17pub(crate) const REAP_TIMEOUT: Duration = Duration::from_secs(5);
18
19/// Cancellation must not leave a browser behind. On Unix the driver starts a
20/// new process group, so the kill reaches only descendants of this test's
21/// driver, never a person's existing browser. We reap the direct driver child;
22/// adoption and reaping of its terminated descendants belongs to the OS.
23/// Windows currently has only the
24/// child handle fallback; descendant job ownership is separate platform work.
25struct OwnedProcess {
26    child: tokio::process::Child,
27    #[cfg(unix)]
28    group: Option<i32>,
29}
30
31impl OwnedProcess {
32    fn spawn(command: &mut tokio::process::Command) -> Result<Self> {
33        command.kill_on_drop(true);
34        #[cfg(unix)]
35        command.process_group(0);
36        let child = command.spawn()?;
37        Ok(Self {
38            #[cfg(unix)]
39            group: child.id().and_then(|pid| i32::try_from(pid).ok()),
40            child,
41        })
42    }
43
44    fn stop(&mut self) -> Result<()> {
45        #[cfg(unix)]
46        if let Some(group) = self.group.take() {
47            // This is the positive PID returned by our process_group(0) spawn.
48            // Forget it before reaping, so Drop cannot target a reused group.
49            ensure!(group > 0, "invalid owned driver process group");
50            if unsafe { libc::kill(-group, libc::SIGKILL) } != 0 {
51                let error = std::io::Error::last_os_error();
52                if error.raw_os_error() != Some(libc::ESRCH) {
53                    return Err(error).context("terminating the test driver process group");
54                }
55            }
56        }
57        self.child
58            .start_kill()
59            .context("terminating the test driver")
60    }
61
62    async fn reap(&mut self) -> Result<()> {
63        let stopped = self.stop();
64        let reaped = timeout(REAP_TIMEOUT, self.child.wait())
65            .await
66            .context("test driver reap timed out")?
67            .context("reaping the test driver");
68        stopped?;
69        reaped?;
70        Ok(())
71    }
72}
73
74impl Drop for OwnedProcess {
75    fn drop(&mut self) {
76        if let Err(error) = self.stop() {
77            tracing::warn!(%error, "stopping a dropped test driver");
78        }
79        // Tokio's kill_on_drop child guard also arranges orphan reaping when
80        // an async startup/cleanup future is cancelled before wait completes.
81    }
82}
83
84/// A browser this suite knows how to drive.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum Engine {
87    /// Firefox, driven through `geckodriver`.
88    Firefox,
89    /// Chrome, driven through `chromedriver`, which is fetched to match the
90    /// installed Chrome when none is on the `PATH`.
91    Chrome,
92}
93
94/// Which colour scheme `E2E_THEME` asks the browser to report, or `None` where
95/// it says nothing and the machine answers for itself. Without it every run is
96/// read in whatever the machine prefers, and the other scheme is never looked
97/// at.
98fn forced_dark() -> Option<bool> {
99    match std::env::var("E2E_THEME").ok()?.as_str() {
100        "dark" => Some(true),
101        "light" => Some(false),
102        _ => None,
103    }
104}
105
106fn motion_preference(value: &str) -> Result<bool> {
107    match value {
108        "reduce" => Ok(true),
109        "normal" => Ok(false),
110        _ => bail!("E2E_MOTION must be reduce or normal, got {value:?}"),
111    }
112}
113
114fn forced_motion() -> Result<Option<bool>> {
115    match std::env::var("E2E_MOTION") {
116        Ok(value) => motion_preference(&value).map(Some),
117        Err(std::env::VarError::NotPresent) => Ok(None),
118        Err(error) => Err(error).context("reading E2E_MOTION"),
119    }
120}
121
122/// The device pixel ratio `E2E_SCALE` asks the browser to report, or `None`
123/// where it says nothing and a session runs at the platform's own ratio --
124/// ordinarily 1, so a high-DPI-specific path is never actually exercised
125/// without this. Unlike `E2E_THEME`/`E2E_MOTION`, both engines answer it:
126/// Firefox through a preference, Chrome through a launch flag.
127fn forced_scale() -> Result<Option<f64>> {
128    match std::env::var("E2E_SCALE") {
129        Ok(value) => {
130            let scale: f64 = value
131                .parse()
132                .with_context(|| format!("E2E_SCALE must be a number, got {value:?}"))?;
133            ensure!(scale > 0.0, "E2E_SCALE must be positive, got {scale}");
134            Ok(Some(scale))
135        }
136        Err(std::env::VarError::NotPresent) => Ok(None),
137        Err(error) => Err(error).context("reading E2E_SCALE"),
138    }
139}
140
141impl Engine {
142    /// Every engine, in the order a run with no preference tries them.
143    pub const ALL: [Engine; 2] = [Engine::Firefox, Engine::Chrome];
144
145    /// The WebDriver server that drives this engine.
146    pub fn driver(self) -> &'static str {
147        match self {
148            Engine::Firefox => "geckodriver",
149            Engine::Chrome => "chromedriver",
150        }
151    }
152
153    /// What to call this engine where somebody reads it.
154    pub fn name(self) -> &'static str {
155        match self {
156            Engine::Firefox => "firefox",
157            Engine::Chrome => "chrome",
158        }
159    }
160
161    /// The capabilities a session is opened with, headless unless asked
162    /// otherwise.
163    pub fn capabilities(self, headed: bool) -> Result<Capabilities> {
164        self.with_preferences(headed, forced_dark(), forced_motion()?, forced_scale()?)
165    }
166
167    fn with_preferences(
168        self,
169        headed: bool,
170        dark: Option<bool>,
171        reduced_motion: Option<bool>,
172        scale: Option<f64>,
173    ) -> Result<Capabilities> {
174        match self {
175            Engine::Firefox => {
176                let mut caps = DesiredCapabilities::firefox();
177
178                if !headed {
179                    caps.add_arg("--headless")?;
180                }
181
182                if dark.is_some() || reduced_motion.is_some() || scale.is_some() {
183                    let mut prefs = FirefoxPreferences::new();
184                    if let Some(dark) = dark {
185                        prefs.set("ui.systemUsesDarkTheme", i64::from(dark))?;
186                    }
187                    if let Some(reduced) = reduced_motion {
188                        prefs.set("ui.prefersReducedMotion", i64::from(reduced))?;
189                    }
190                    if let Some(scale) = scale {
191                        prefs.set("layout.css.devPixelsPerPx", scale.to_string())?;
192                    }
193                    caps.set_preferences(prefs)?;
194                }
195
196                Ok(caps.into())
197            }
198            Engine::Chrome => {
199                let mut caps = DesiredCapabilities::chrome();
200
201                if !headed {
202                    caps.add_arg("--headless=new")?;
203                }
204
205                if dark.is_some() {
206                    bail!("E2E_THEME is a Firefox preference and chrome has no answer for it");
207                }
208                if reduced_motion.is_some() {
209                    bail!("E2E_MOTION is a Firefox preference and chrome has no answer for it");
210                }
211
212                if let Some(scale) = scale {
213                    caps.add_arg(&format!("--force-device-scale-factor={scale}"))?;
214                    caps.add_arg("--high-dpi-support=1")?;
215                }
216
217                Ok(caps.into())
218            }
219        }
220    }
221
222    /// Where this engine's driver already is, or `None` for a machine that has
223    /// not got one.
224    pub(crate) fn installed(self) -> Option<PathBuf> {
225        if let Some(path) = on_path(self.driver()) {
226            return Some(path);
227        }
228
229        let cached = crate::fetch::cached(self).ok()?;
230        cached.is_file().then_some(cached)
231    }
232
233    /// Whether this engine can be driven without fetching anything.
234    pub fn available(self) -> bool {
235        self.installed().is_some()
236    }
237
238    /// Whether this engine's browser is here, whether or not its driver is.
239    pub fn browser_present(self) -> bool {
240        match self {
241            Engine::Firefox => false,
242            Engine::Chrome => crate::fetch::chrome_present(),
243        }
244    }
245
246    /// The first engine whose driver this machine has — failing that, the first
247    /// whose *browser* it has, which a fetch can finish.
248    pub fn detect() -> Option<Engine> {
249        Engine::ALL
250            .into_iter()
251            .find(|engine| engine.available())
252            .or_else(|| {
253                Engine::ALL
254                    .into_iter()
255                    .find(|engine| engine.browser_present())
256            })
257    }
258
259    /// [`Engine::detect`], or an error naming what would have satisfied it.
260    pub fn require() -> Result<Engine> {
261        if let Some(engine) = Engine::detect() {
262            return Ok(engine);
263        }
264
265        let drivers = Engine::ALL
266            .map(|engine| format!("{} (for {})", engine.driver(), engine.name()))
267            .join(", ");
268
269        bail!(
270            "No browser this suite can drive. It needs either a WebDriver server \
271             on PATH — one of: {drivers} — or a Chrome it can fetch a matching \
272             chromedriver for, which it does by itself into target/e2e."
273        )
274    }
275
276    /// Where this engine's driver is, fetching one if that is the only way.
277    pub(crate) fn provision(self) -> Result<PathBuf> {
278        if let Some(path) = self.installed() {
279            return Ok(path);
280        }
281
282        crate::fetch::fetch(self)
283    }
284}
285
286impl fmt::Display for Engine {
287    #[inline]
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        f.write_str(self.name())
290    }
291}
292
293impl FromStr for Engine {
294    type Err = anyhow::Error;
295
296    fn from_str(input: &str) -> Result<Self> {
297        for engine in Engine::ALL {
298            if input.eq_ignore_ascii_case(engine.name()) {
299                return Ok(engine);
300            }
301        }
302
303        match input.to_ascii_lowercase().as_str() {
304            "gecko" => Ok(Engine::Firefox),
305            "chromium" => Ok(Engine::Chrome),
306            _ => {
307                let names = Engine::ALL.map(Engine::name).join(", ");
308                Err(anyhow!(
309                    "{input:?} is not a browser this suite drives: {names}"
310                ))
311            }
312        }
313    }
314}
315
316/// Where `name` is on `PATH`, taking the platform's executable suffix into
317/// account.
318fn on_path(name: &str) -> Option<PathBuf> {
319    let path = std::env::var_os("PATH")?;
320
321    let suffixes: Vec<String> = match cfg!(windows) {
322        true => std::env::var("PATHEXT")
323            .unwrap_or_else(|_| String::from(".EXE"))
324            .split(';')
325            .map(str::to_ascii_lowercase)
326            .chain([String::new()])
327            .collect(),
328        false => vec![String::new()],
329    };
330
331    for dir in std::env::split_paths(&path) {
332        for suffix in &suffixes {
333            let candidate = dir.join(format!("{name}{suffix}"));
334
335            if candidate.is_file() {
336                return Some(candidate);
337            }
338        }
339    }
340
341    None
342}
343
344/// A running WebDriver server, and the address it answers on.
345pub(crate) struct Driver {
346    engine: Engine,
347    process: OwnedProcess,
348    stdout: tokio::io::BufReader<tokio::process::ChildStdout>,
349    stderr: tokio::io::BufReader<tokio::process::ChildStderr>,
350    stdout_line: Vec<u8>,
351    stderr_line: Vec<u8>,
352    stdout_open: bool,
353    stderr_open: bool,
354    log: String,
355    pub(crate) address: SocketAddr,
356}
357
358impl Driver {
359    /// Start one, and do not return until it says where it is answering.
360    pub(crate) async fn new(engine: Engine, deadline: Instant) -> Result<Self> {
361        use tokio::process::Command;
362
363        let binary = engine.installed().with_context(|| {
364            anyhow!(
365                "No {} to drive {engine} with. It is provisioned once before the \
366                 run starts; see `harness::choose`.",
367                engine.driver()
368            )
369        })?;
370
371        let mut command = Command::new(&binary);
372        command.args(engine.port_args());
373        Self::start(engine, &mut command, deadline).await
374    }
375
376    pub(crate) async fn start(
377        engine: Engine,
378        command: &mut tokio::process::Command,
379        deadline: Instant,
380    ) -> Result<Self> {
381        use std::process::Stdio;
382        use tokio::io::BufReader;
383
384        command
385            .stdout(Stdio::piped())
386            .stderr(Stdio::piped())
387            .stdin(Stdio::null());
388        let mut process = OwnedProcess::spawn(command).context("spawning the test driver")?;
389        let stdout = BufReader::new(process.child.stdout.take().context("missing stdout")?);
390        let stderr = BufReader::new(process.child.stderr.take().context("missing stderr")?);
391        let mut driver = Self {
392            engine,
393            process,
394            stdout,
395            stderr,
396            stdout_line: Vec::new(),
397            stderr_line: Vec::new(),
398            stdout_open: true,
399            stderr_open: true,
400            log: String::new(),
401            address: SocketAddr::from(([127, 0, 0, 1], 0)),
402        };
403        let ready = tokio::time::timeout_at(deadline, async {
404            for _ in 0..READY_LINES {
405                ensure!(
406                    driver.io().await?,
407                    "driver stopped before announcing its address"
408                );
409                if let Some(address) = driver.log.lines().find_map(|line| engine.address_of(line)) {
410                    driver.address = address;
411                    return Ok(());
412                }
413            }
414            bail!("driver did not announce its address in its first {READY_LINES} lines")
415        })
416        .await
417        .context("test browser startup timed out while waiting for the driver address")
418        .and_then(|result| result);
419        if let Err(error) = ready {
420            let error = error.context(driver.diagnostics());
421            return Err(with_cleanup(error, driver.terminate().await));
422        }
423        Ok(driver)
424    }
425
426    /// Which engine this is driving, for whatever reads it back.
427    #[inline]
428    pub(crate) fn engine(&self) -> Engine {
429        self.engine
430    }
431
432    #[inline]
433    pub(crate) async fn io(&mut self) -> Result<bool> {
434        use tokio::io::AsyncBufReadExt;
435        while self.stdout_open || self.stderr_open {
436            let (n, stderr) = tokio::select! {
437                n = self.stdout.read_until(b'\n', &mut self.stdout_line), if self.stdout_open => (n?, false),
438                n = self.stderr.read_until(b'\n', &mut self.stderr_line), if self.stderr_open => (n?, true),
439            };
440            if n == 0 {
441                if stderr {
442                    self.stderr_open = false;
443                } else {
444                    self.stdout_open = false;
445                }
446                continue;
447            }
448            // Keep each pipe's partial line across select cancellation.
449            let bytes = if stderr {
450                &mut self.stderr_line
451            } else {
452                &mut self.stdout_line
453            };
454            let line = String::from_utf8_lossy(bytes);
455            self.log.push_str(&line);
456            if self.log.len() > 8192 {
457                let mut at = self.log.len() - 8192;
458                while !self.log.is_char_boundary(at) {
459                    at += 1;
460                }
461                self.log.drain(..at);
462            }
463            tracing::trace!(driver = self.engine.driver(), stderr, line = %line.trim(), "test driver output");
464            bytes.clear();
465            return Ok(true);
466        }
467        Ok(false)
468    }
469
470    pub(crate) fn diagnostics(&self) -> String {
471        format!("{}{}", self.engine.driver(), quoted(&self.log))
472    }
473
474    /// Drain both pipes while a protocol operation is pending: a full stderr
475    /// pipe during browser boot must not masquerade as a hung session request.
476    pub(crate) async fn during<T>(
477        &mut self,
478        deadline: Instant,
479        stage: &str,
480        operation: impl Future<Output = Result<T>>,
481    ) -> Result<T> {
482        let mut operation = std::pin::pin!(operation);
483        let result = loop {
484            tokio::select! {
485                biased;
486                _ = tokio::time::sleep_until(deadline) => break Err(TimedOut(stage.to_owned()).into()),
487                result = operation.as_mut() => break result,
488                read = self.io(), if self.stdout_open || self.stderr_open => {
489                    if let Err(error) = read { break Err(error); }
490                    // A driver may close logging pipes before replying to quit.
491                    // Keep polling the protocol, still under the same deadline.
492                }
493            }
494        };
495        result.with_context(|| format!("browser {stage}: {}", self.diagnostics()))
496    }
497
498    pub(crate) async fn terminate(&mut self) -> Result<()> {
499        self.process.reap().await
500    }
501}
502
503/// A browser operation that did not answer by its deadline, named by stage.
504#[derive(Debug)]
505pub(crate) struct TimedOut(pub(crate) String);
506
507impl fmt::Display for TimedOut {
508    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509        write!(f, "test browser {} timed out", self.0)
510    }
511}
512
513impl std::error::Error for TimedOut {}
514
515pub(crate) fn with_cleanup(error: anyhow::Error, cleanup: Result<()>) -> anyhow::Error {
516    match cleanup {
517        Ok(()) => error,
518        Err(cleanup) => error.context(format!("test browser cleanup also failed: {cleanup:#}")),
519    }
520}
521
522/// How many lines of a driver's greeting are read while waiting for it to say it
523/// is listening. chromedriver takes four; the rest is headroom for a version
524/// that says more.
525const READY_LINES: usize = 16;
526
527impl Engine {
528    /// How this engine's driver is told to serve on a port of its own choosing.
529    fn port_args(self) -> &'static [&'static str] {
530        match self {
531            Engine::Firefox => &["--port", "0"],
532            Engine::Chrome => &["--port=0"],
533        }
534    }
535
536    /// The address a line of the driver's greeting announces, if it is the line
537    /// that announces one.
538    fn address_of(self, line: &str) -> Option<SocketAddr> {
539        match self {
540            Engine::Firefox => {
541                let at = line.find("Listening on ")? + "Listening on ".len();
542                line[at..].trim().parse().ok()
543            }
544            Engine::Chrome => {
545                const SAID: &str = "started successfully on port ";
546
547                let at = line.find(SAID)? + SAID.len();
548                let port: u16 = line[at..].trim().trim_end_matches('.').parse().ok()?;
549
550                Some(SocketAddr::from(([127, 0, 0, 1], port)))
551            }
552        }
553    }
554}
555
556/// Whatever the driver managed to say, set off so it reads as its words rather
557/// than as this suite's.
558fn quoted(said: &str) -> String {
559    match said.trim() {
560        "" => String::from(" It printed nothing."),
561        said => format!(" It said:\n{said}"),
562    }
563}
564
565#[cfg(test)]
566mod tests {
567    use super::{Engine, motion_preference};
568
569    #[test]
570    fn motion_preferences_are_explicit_and_do_not_replace_theme_preferences() {
571        assert!(motion_preference("reduce").unwrap());
572        assert!(!motion_preference("normal").unwrap());
573        for invalid in ["", "false", "off", "reduced"] {
574            assert!(motion_preference(invalid).is_err());
575        }
576        for reduced in [false, true] {
577            let caps = Engine::Firefox
578                .with_preferences(false, Some(true), Some(reduced), None)
579                .unwrap();
580            let prefs = &caps.get("moz:firefoxOptions").unwrap()["prefs"];
581            assert_eq!(prefs["ui.systemUsesDarkTheme"], 1);
582            assert_eq!(prefs["ui.prefersReducedMotion"], i64::from(reduced));
583            let error = Engine::Chrome
584                .with_preferences(false, None, Some(reduced), None)
585                .unwrap_err();
586            assert!(error.to_string().contains("E2E_MOTION"));
587        }
588        let caps = Engine::Firefox
589            .with_preferences(false, None, None, None)
590            .unwrap();
591        assert!(
592            caps.get("moz:firefoxOptions")
593                .unwrap()
594                .get("prefs")
595                .is_none()
596        );
597        assert!(
598            Engine::Chrome
599                .with_preferences(false, None, None, None)
600                .is_ok()
601        );
602    }
603
604    /// **A forced device pixel ratio reaches both engines**, unlike theme and
605    /// motion, which are Firefox-only preferences.
606    #[test]
607    fn a_forced_scale_reaches_both_engines() {
608        let caps = Engine::Firefox
609            .with_preferences(false, None, None, Some(2.0))
610            .unwrap();
611        let prefs = &caps.get("moz:firefoxOptions").unwrap()["prefs"];
612        assert_eq!(prefs["layout.css.devPixelsPerPx"], "2");
613
614        let caps = Engine::Chrome
615            .with_preferences(false, None, None, Some(2.0))
616            .unwrap();
617        let args = caps.get("goog:chromeOptions").unwrap()["args"]
618            .as_array()
619            .unwrap();
620        assert!(args.iter().any(|a| a == "--force-device-scale-factor=2"));
621    }
622
623    /// **Every engine is named, parses back, and has a driver of its own.** The
624    /// list is short enough that this looks like ceremony and is not: a third
625    /// entry added with a copied `name` would make `--browser` reach the wrong
626    /// one, silently, and the suite would report the engine it was not running.
627    #[test]
628    fn every_engine_round_trips_through_its_name() {
629        for engine in Engine::ALL {
630            assert_eq!(engine.name().parse::<Engine>().unwrap(), engine);
631
632            assert_eq!(
633                engine.name().to_uppercase().parse::<Engine>().unwrap(),
634                engine
635            );
636        }
637
638        for pair in Engine::ALL.windows(2) {
639            assert_ne!(pair[0].name(), pair[1].name());
640            assert_ne!(pair[0].driver(), pair[1].driver());
641        }
642    }
643
644    /// A name nothing answers to says what would have worked, rather than
645    /// failing somewhere further in with a spawn error naming one binary.
646    #[test]
647    fn a_browser_nothing_drives_is_refused_with_the_list() {
648        let error = "safari".parse::<Engine>().unwrap_err().to_string();
649
650        for engine in Engine::ALL {
651            assert!(
652                error.contains(engine.name()),
653                "{error} does not offer {engine}"
654            );
655        }
656    }
657
658    /// **Each driver's greeting is read for the port it took, and only the line
659    /// that carries one counts.**
660    #[test]
661    fn each_driver_is_read_for_the_port_it_took() {
662        use std::net::SocketAddr;
663
664        let gecko = "1730000000\tgeckodriver\tINFO\tListening on 127.0.0.1:51234";
665
666        let chrome = [
667            "Starting ChromeDriver 151.0.7922.138 (abcdef) on port 0",
668            "Only local connections are allowed.",
669            "Please see https://chromedriver.chromium.org/security-considerations \
670             for suggestions on keeping ChromeDriver safe.",
671            "ChromeDriver was started successfully on port 52725.",
672        ];
673
674        let expect = |port| Some(SocketAddr::from(([127, 0, 0, 1], port)));
675
676        assert_eq!(Engine::Firefox.address_of(gecko), expect(51234));
677        assert_eq!(Engine::Chrome.address_of(gecko), None);
678
679        assert_eq!(Engine::Chrome.address_of(chrome[3]), expect(52725));
680
681        for line in &chrome[..3] {
682            assert_eq!(
683                Engine::Chrome.address_of(line),
684                None,
685                "{line:?} is not where the port is"
686            );
687            assert_eq!(Engine::Firefox.address_of(line), None);
688        }
689    }
690
691    /// **Both are told to pick a port, which is what makes starting several at
692    /// once safe** — and the two spellings are not interchangeable.
693    /// chromedriver answers a separated `--port 0` with its usage and an exit.
694    #[test]
695    fn each_driver_is_told_to_pick_its_own_port() {
696        for engine in Engine::ALL {
697            let args = engine.port_args();
698
699            assert!(
700                args.iter().any(|arg| arg.contains('0')),
701                "{engine} is not asking for a port of the driver's choosing"
702            );
703        }
704
705        assert_eq!(Engine::Firefox.port_args(), ["--port", "0"]);
706        assert_eq!(Engine::Chrome.port_args(), ["--port=0"]);
707    }
708
709    /// The suite asks the machine what it can drive before it tries to drive
710    /// anything, so a machine with neither driver is told what to install
711    /// instead of being handed a spawn error naming one binary.
712    #[test]
713    fn a_machine_with_no_driver_is_told_what_would_have_worked() {
714        if Engine::detect().is_some() {
715            assert!(Engine::require().is_ok());
716            return;
717        }
718
719        let error = Engine::require().unwrap_err().to_string();
720
721        for engine in Engine::ALL {
722            assert!(
723                error.contains(engine.driver()),
724                "{error} does not name a driver"
725            );
726        }
727    }
728}
729
730#[cfg(all(test, unix))]
731pub(crate) mod lifecycle_tests {
732    use super::*;
733    use tokio::process::Command;
734
735    pub(crate) async fn fake(address: SocketAddr) -> (Driver, i32) {
736        let mut command = Command::new("sh");
737        command.args([
738            "-c",
739            &format!("echo 'Listening on {address}'; exec sleep 60"),
740        ]);
741        let driver = Driver::start(
742            Engine::Firefox,
743            &mut command,
744            Instant::now() + STARTUP_TIMEOUT,
745        )
746        .await
747        .unwrap();
748        let pid = driver.process.child.id().unwrap() as i32;
749        (driver, pid)
750    }
751
752    pub(crate) async fn gone(pid: i32) {
753        timeout(Duration::from_secs(2), async {
754            loop {
755                let result = unsafe { libc::kill(pid, 0) };
756                if result != 0
757                    && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
758                {
759                    break;
760                }
761                tokio::task::yield_now().await;
762            }
763        })
764        .await
765        .expect("the owned driver must be reaped");
766    }
767
768    #[tokio::test]
769    async fn readiness_timeout_keeps_stderr_and_reaps_its_process() {
770        let mut command = Command::new("sh");
771        command.args([
772            "-c",
773            "echo owned-pid=$$ >&2; echo boot-stalled >&2; exec sleep 60",
774        ]);
775        let error = Driver::start(
776            Engine::Firefox,
777            &mut command,
778            Instant::now() + Duration::from_millis(250),
779        )
780        .await
781        .err()
782        .unwrap();
783        let message = format!("{error:#}");
784        assert!(message.contains("boot-stalled"), "{message}");
785        assert!(message.contains("startup timed out"), "{message}");
786        let pid = message
787            .lines()
788            .find_map(|line| line.strip_prefix("owned-pid="))
789            .unwrap()
790            .parse()
791            .unwrap();
792        gone(pid).await;
793    }
794
795    #[tokio::test]
796    async fn early_driver_exit_reports_its_original_error_and_output() {
797        let mut command = Command::new("sh");
798        command.args(["-c", "echo fatal-startup-marker >&2; exit 7"]);
799        let error = Driver::start(
800            Engine::Firefox,
801            &mut command,
802            Instant::now() + STARTUP_TIMEOUT,
803        )
804        .await
805        .err()
806        .unwrap();
807        let message = format!("{error:#}");
808        assert!(message.contains("fatal-startup-marker"), "{message}");
809        assert!(message.contains("stopped before announcing"), "{message}");
810    }
811
812    #[tokio::test]
813    async fn closing_one_log_pipe_does_not_hide_the_other_pipes_greeting() {
814        let mut command = Command::new("sh");
815        command.args([
816            "-c",
817            "exec 1>&-; echo 'Listening on 127.0.0.1:12345' >&2; exec sleep 60",
818        ]);
819        let mut driver = Driver::start(
820            Engine::Firefox,
821            &mut command,
822            Instant::now() + STARTUP_TIMEOUT,
823        )
824        .await
825        .unwrap();
826        assert_eq!(driver.address.port(), 12345);
827        assert!(driver.diagnostics().contains("Listening on"));
828        driver.terminate().await.unwrap();
829    }
830
831    #[tokio::test]
832    async fn cancelling_before_the_driver_announces_its_address_reaps_it() {
833        let pid_file = tempfile::NamedTempFile::new().unwrap();
834        let path = pid_file.path().to_owned();
835        let mut command = Command::new("sh");
836        command.args([
837            "-c",
838            "printf '%s' \"$$\" > \"$1\"; exec sleep 60",
839            "test-driver",
840        ]);
841        command.arg(&path);
842        let starting = tokio::spawn(async move {
843            Driver::start(
844                Engine::Firefox,
845                &mut command,
846                Instant::now() + STARTUP_TIMEOUT,
847            )
848            .await
849        });
850        let pid = timeout(STARTUP_TIMEOUT, async {
851            loop {
852                if let Ok(pid) = tokio::fs::read_to_string(&path)
853                    .await
854                    .unwrap()
855                    .parse::<i32>()
856                {
857                    break pid;
858                }
859                tokio::task::yield_now().await;
860            }
861        })
862        .await
863        .unwrap();
864        starting.abort();
865        assert!(matches!(starting.await, Err(error) if error.is_cancelled()));
866        gone(pid).await;
867    }
868
869    #[tokio::test]
870    async fn killing_an_owned_group_does_not_kill_an_unrelated_child() {
871        use tokio::io::AsyncBufReadExt;
872        let mut unrelated = Command::new("sleep")
873            .arg("60")
874            .kill_on_drop(true)
875            .spawn()
876            .unwrap();
877        let mut command = Command::new("sh");
878        command.args(["-c", "sleep 60 & echo $!; wait"]);
879        command.stdout(std::process::Stdio::piped());
880        let mut owned = OwnedProcess::spawn(&mut command).unwrap();
881        let leader = owned.child.id().unwrap() as i32;
882        let mut child_line = String::new();
883        tokio::io::BufReader::new(owned.child.stdout.take().unwrap())
884            .read_line(&mut child_line)
885            .await
886            .unwrap();
887        let descendant: i32 = child_line.trim().parse().unwrap();
888        assert_ne!(leader, descendant);
889        assert_eq!(unsafe { libc::getpgid(leader) }, leader);
890        assert_eq!(unsafe { libc::getpgid(descendant) }, leader);
891        assert_ne!(
892            unsafe { libc::getpgid(unrelated.id().unwrap() as i32) },
893            leader
894        );
895        owned.reap().await.unwrap();
896        gone(leader).await;
897        // Grandchildren are reaped by their new parent, not this harness. A
898        // zombie has stopped running even if init has not collected it yet.
899        timeout(Duration::from_secs(2), async {
900            loop {
901                let dead = unsafe { libc::kill(descendant, 0) } != 0;
902                #[cfg(target_os = "linux")]
903                let dead = dead
904                    || std::fs::read_to_string(format!("/proc/{descendant}/stat")).is_ok_and(
905                        |stat| {
906                            stat.rsplit_once(") ")
907                                .is_some_and(|(_, fields)| fields.starts_with('Z'))
908                        },
909                    );
910                if dead {
911                    break;
912                }
913                tokio::task::yield_now().await;
914            }
915        })
916        .await
917        .unwrap();
918        assert!(unrelated.try_wait().unwrap().is_none());
919        unrelated.kill().await.unwrap();
920    }
921
922    #[test]
923    fn cleanup_failure_keeps_the_original_failure_chain() {
924        let error = with_cleanup(
925            anyhow!("original assertion failed"),
926            Err(TimedOut("quit".to_owned()).into()),
927        );
928        let message = format!("{error:#}");
929        assert!(message.contains("original assertion failed"));
930        assert!(message.contains("quit timed out"));
931    }
932
933    #[test]
934    fn a_timeout_stays_recognisable_under_its_context() {
935        let error = anyhow::Error::from(TimedOut("quit".to_owned()))
936            .context("browser quit: geckodriver It printed nothing.");
937        assert!(error.downcast_ref::<TimedOut>().is_some());
938        assert!(format!("{error:#}").contains("test browser quit timed out"));
939        assert!(
940            anyhow!("quit timed out")
941                .downcast_ref::<TimedOut>()
942                .is_none()
943        );
944    }
945}