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