yew-e2e 0.2.2

Browser tests for Yew applications, and the runner that drives them.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
//! Which browser the suite drives, and the WebDriver server that drives it.

use std::fmt;
use std::future::Future;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::str::FromStr;
use std::time::Duration;

use anyhow::{Context, Result, anyhow, bail, ensure};
use thirtyfour::common::capabilities::firefox::FirefoxPreferences;
use thirtyfour::prelude::*;
use tokio::time::{Instant, timeout};

pub(crate) const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) const QUIT_TIMEOUT: Duration = Duration::from_secs(5);
pub(crate) const REAP_TIMEOUT: Duration = Duration::from_secs(5);

/// Cancellation must not leave a browser behind. On Unix the driver starts a
/// new process group, so the kill reaches only descendants of this test's
/// driver, never a person's existing browser. We reap the direct driver child;
/// adoption and reaping of its terminated descendants belongs to the OS.
/// Windows currently has only the
/// child handle fallback; descendant job ownership is separate platform work.
struct OwnedProcess {
    child: tokio::process::Child,
    #[cfg(unix)]
    group: Option<i32>,
}

impl OwnedProcess {
    fn spawn(command: &mut tokio::process::Command) -> Result<Self> {
        command.kill_on_drop(true);
        #[cfg(unix)]
        command.process_group(0);
        let child = command.spawn()?;
        Ok(Self {
            #[cfg(unix)]
            group: child.id().and_then(|pid| i32::try_from(pid).ok()),
            child,
        })
    }

    fn stop(&mut self) -> Result<()> {
        #[cfg(unix)]
        if let Some(group) = self.group.take() {
            // This is the positive PID returned by our process_group(0) spawn.
            // Forget it before reaping, so Drop cannot target a reused group.
            ensure!(group > 0, "invalid owned driver process group");
            if unsafe { libc::kill(-group, libc::SIGKILL) } != 0 {
                let error = std::io::Error::last_os_error();
                if error.raw_os_error() != Some(libc::ESRCH) {
                    return Err(error).context("terminating the test driver process group");
                }
            }
        }
        self.child
            .start_kill()
            .context("terminating the test driver")
    }

    async fn reap(&mut self) -> Result<()> {
        let stopped = self.stop();
        let reaped = timeout(REAP_TIMEOUT, self.child.wait())
            .await
            .context("test driver reap timed out")?
            .context("reaping the test driver");
        stopped?;
        reaped?;
        Ok(())
    }
}

impl Drop for OwnedProcess {
    fn drop(&mut self) {
        if let Err(error) = self.stop() {
            tracing::warn!(%error, "stopping a dropped test driver");
        }
        // Tokio's kill_on_drop child guard also arranges orphan reaping when
        // an async startup/cleanup future is cancelled before wait completes.
    }
}

/// A browser this suite knows how to drive.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Engine {
    /// Firefox, driven through `geckodriver`.
    Firefox,
    /// Chrome, driven through `chromedriver`, which is fetched to match the
    /// installed Chrome when none is on the `PATH`.
    Chrome,
}

/// Which colour scheme `E2E_THEME` asks the browser to report, or `None` where
/// it says nothing and the machine answers for itself. Without it every run is
/// read in whatever the machine prefers, and the other scheme is never looked
/// at.
fn forced_dark() -> Result<Option<bool>> {
    match std::env::var("E2E_THEME") {
        Ok(value) => theme_preference(&value).map(Some),
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(error) => Err(error).context("reading E2E_THEME"),
    }
}

fn theme_preference(value: &str) -> Result<bool> {
    match value {
        "dark" => Ok(true),
        "light" => Ok(false),
        _ => bail!("E2E_THEME must be dark or light, got {value:?}"),
    }
}

fn motion_preference(value: &str) -> Result<bool> {
    match value {
        "reduce" => Ok(true),
        "normal" => Ok(false),
        _ => bail!("E2E_MOTION must be reduce or normal, got {value:?}"),
    }
}

fn forced_motion() -> Result<Option<bool>> {
    match std::env::var("E2E_MOTION") {
        Ok(value) => motion_preference(&value).map(Some),
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(error) => Err(error).context("reading E2E_MOTION"),
    }
}

/// The device pixel ratio `E2E_SCALE` asks the browser to report, or `None`
/// where it says nothing and a session runs at the platform's own ratio --
/// ordinarily 1, so a high-DPI-specific path is never actually exercised
/// without this. Unlike `E2E_THEME`/`E2E_MOTION`, both engines answer it:
/// Firefox through a preference, Chrome through a launch flag.
fn forced_scale() -> Result<Option<f64>> {
    match std::env::var("E2E_SCALE") {
        Ok(value) => {
            let scale: f64 = value
                .parse()
                .with_context(|| format!("E2E_SCALE must be a number, got {value:?}"))?;
            ensure!(scale > 0.0, "E2E_SCALE must be positive, got {scale}");
            Ok(Some(scale))
        }
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(error) => Err(error).context("reading E2E_SCALE"),
    }
}

impl Engine {
    /// Every engine, in the order a run with no preference tries them.
    pub const ALL: [Engine; 2] = [Engine::Firefox, Engine::Chrome];

    /// The WebDriver server that drives this engine.
    pub fn driver(self) -> &'static str {
        match self {
            Engine::Firefox => "geckodriver",
            Engine::Chrome => "chromedriver",
        }
    }

    /// What to call this engine where somebody reads it.
    pub fn name(self) -> &'static str {
        match self {
            Engine::Firefox => "firefox",
            Engine::Chrome => "chrome",
        }
    }

    /// The capabilities a session is opened with, headless unless asked
    /// otherwise.
    pub fn capabilities(self, headed: bool) -> Result<Capabilities> {
        self.with_preferences(headed, forced_dark()?, forced_motion()?, forced_scale()?)
    }

    fn with_preferences(
        self,
        headed: bool,
        dark: Option<bool>,
        reduced_motion: Option<bool>,
        scale: Option<f64>,
    ) -> Result<Capabilities> {
        match self {
            Engine::Firefox => {
                let mut caps = DesiredCapabilities::firefox();

                if !headed {
                    caps.add_arg("--headless")?;
                }

                if dark.is_some() || reduced_motion.is_some() || scale.is_some() {
                    let mut prefs = FirefoxPreferences::new();
                    if let Some(dark) = dark {
                        prefs.set("ui.systemUsesDarkTheme", i64::from(dark))?;
                    }
                    if let Some(reduced) = reduced_motion {
                        prefs.set("ui.prefersReducedMotion", i64::from(reduced))?;
                    }
                    if let Some(scale) = scale {
                        prefs.set("layout.css.devPixelsPerPx", scale.to_string())?;
                    }
                    caps.set_preferences(prefs)?;
                }

                Ok(caps.into())
            }
            Engine::Chrome => {
                let mut caps = DesiredCapabilities::chrome();

                if !headed {
                    caps.add_arg("--headless=new")?;
                }

                if dark.is_some() {
                    bail!("E2E_THEME is a Firefox preference and chrome has no answer for it");
                }
                if reduced_motion.is_some() {
                    bail!("E2E_MOTION is a Firefox preference and chrome has no answer for it");
                }

                if let Some(scale) = scale {
                    caps.add_arg(&format!("--force-device-scale-factor={scale}"))?;
                    caps.add_arg("--high-dpi-support=1")?;
                }

                Ok(caps.into())
            }
        }
    }

    /// Where this engine's driver already is, or `None` for a machine that has
    /// not got one.
    pub(crate) fn installed(self) -> Option<PathBuf> {
        if let Some(path) = on_path(self.driver()) {
            return Some(path);
        }

        let cached = crate::fetch::cached(self).ok()?;
        cached.is_file().then_some(cached)
    }

    /// Whether this engine can be driven without fetching anything.
    pub fn available(self) -> bool {
        self.installed().is_some()
    }

    /// Whether this engine's browser is here, whether or not its driver is.
    pub fn browser_present(self) -> bool {
        match self {
            Engine::Firefox => false,
            Engine::Chrome => crate::fetch::chrome_present(),
        }
    }

    /// The first engine whose driver this machine has — failing that, the first
    /// whose *browser* it has, which a fetch can finish.
    pub fn detect() -> Option<Engine> {
        Engine::ALL
            .into_iter()
            .find(|engine| engine.available())
            .or_else(|| {
                Engine::ALL
                    .into_iter()
                    .find(|engine| engine.browser_present())
            })
    }

    /// [`Engine::detect`], or an error naming what would have satisfied it.
    pub fn require() -> Result<Engine> {
        if let Some(engine) = Engine::detect() {
            return Ok(engine);
        }

        let drivers = Engine::ALL
            .map(|engine| format!("{} (for {})", engine.driver(), engine.name()))
            .join(", ");

        bail!(
            "No browser this suite can drive. It needs either a WebDriver server \
             on PATH — one of: {drivers} — or a Chrome it can fetch a matching \
             chromedriver for, which it does by itself into e2e/ under the \
             build directory."
        )
    }

    /// Where this engine's driver is, fetching one if that is the only way.
    pub(crate) fn provision(self) -> Result<PathBuf> {
        if let Some(path) = self.installed() {
            return Ok(path);
        }

        crate::fetch::fetch(self)
    }
}

impl fmt::Display for Engine {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

impl FromStr for Engine {
    type Err = anyhow::Error;

    fn from_str(input: &str) -> Result<Self> {
        for engine in Engine::ALL {
            if input.eq_ignore_ascii_case(engine.name()) {
                return Ok(engine);
            }
        }

        match input.to_ascii_lowercase().as_str() {
            "gecko" => Ok(Engine::Firefox),
            "chromium" => Ok(Engine::Chrome),
            _ => {
                let names = Engine::ALL.map(Engine::name).join(", ");
                Err(anyhow!(
                    "{input:?} is not a browser this suite drives: {names}"
                ))
            }
        }
    }
}

/// Where `name` is on `PATH`, taking the platform's executable suffix into
/// account.
fn on_path(name: &str) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;

    let suffixes: Vec<String> = match cfg!(windows) {
        true => std::env::var("PATHEXT")
            .unwrap_or_else(|_| String::from(".EXE"))
            .split(';')
            .map(str::to_ascii_lowercase)
            .chain([String::new()])
            .collect(),
        false => vec![String::new()],
    };

    for dir in std::env::split_paths(&path) {
        for suffix in &suffixes {
            let candidate = dir.join(format!("{name}{suffix}"));

            if candidate.is_file() {
                return Some(candidate);
            }
        }
    }

    None
}

/// A running WebDriver server, and the address it answers on.
pub(crate) struct Driver {
    engine: Engine,
    process: OwnedProcess,
    stdout: tokio::io::BufReader<tokio::process::ChildStdout>,
    stderr: tokio::io::BufReader<tokio::process::ChildStderr>,
    stdout_line: Vec<u8>,
    stderr_line: Vec<u8>,
    stdout_open: bool,
    stderr_open: bool,
    log: String,
    pub(crate) address: SocketAddr,
}

impl Driver {
    /// Start one, and do not return until it says where it is answering.
    pub(crate) async fn new(engine: Engine, deadline: Instant) -> Result<Self> {
        use tokio::process::Command;

        let binary = engine.installed().with_context(|| {
            anyhow!(
                "No {} to drive {engine} with. It is provisioned once before the \
                 run starts; see `harness::choose`.",
                engine.driver()
            )
        })?;

        let mut command = Command::new(&binary);
        command.args(engine.port_args());
        Self::start_until_it_keeps_a_port(engine, &mut command, deadline).await
    }

    /// Start one with `command`, and start it again each time it exits having
    /// lost the port it picked to another process, up to [`PORT_RETRIES`] times
    /// and all within `deadline`.
    ///
    /// chromedriver told to take any port takes one on `[::1]` and then tries to
    /// take the same number on `127.0.0.1`. The two are handed out separately,
    /// so under parallel runs that number is sometimes already taken on IPv4
    /// and chromedriver gives up. Another start picks another number.
    pub(crate) async fn start_until_it_keeps_a_port(
        engine: Engine,
        command: &mut tokio::process::Command,
        deadline: Instant,
    ) -> Result<Self> {
        let mut lost = 0;

        loop {
            match Self::start(engine, command, deadline).await {
                Err(error) if error.downcast_ref::<PortTaken>().is_some() => {
                    lost += 1;

                    if lost > PORT_RETRIES {
                        return Err(error.context(format!(
                            "{} lost the port it picked {lost} times in a row",
                            engine.driver()
                        )));
                    }

                    tracing::warn!(
                        driver = engine.driver(),
                        attempt = lost,
                        "test driver lost the port it picked; starting it again: {error:#}"
                    );
                }
                result => return result,
            }
        }
    }

    pub(crate) async fn start(
        engine: Engine,
        command: &mut tokio::process::Command,
        deadline: Instant,
    ) -> Result<Self> {
        use std::process::Stdio;
        use tokio::io::BufReader;

        command
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(Stdio::null());
        let mut process = OwnedProcess::spawn(command).context("spawning the test driver")?;
        let stdout = BufReader::new(process.child.stdout.take().context("missing stdout")?);
        let stderr = BufReader::new(process.child.stderr.take().context("missing stderr")?);
        let mut driver = Self {
            engine,
            process,
            stdout,
            stderr,
            stdout_line: Vec::new(),
            stderr_line: Vec::new(),
            stdout_open: true,
            stderr_open: true,
            log: String::new(),
            address: SocketAddr::from(([127, 0, 0, 1], 0)),
        };
        let ready = tokio::time::timeout_at(deadline, async {
            for _ in 0..READY_LINES {
                if !driver.io().await? {
                    if engine.lost_its_port(&driver.log) {
                        return Err(PortTaken.into());
                    }

                    bail!("driver stopped before announcing its address");
                }
                if let Some(address) = driver.log.lines().find_map(|line| engine.address_of(line)) {
                    driver.address = address;
                    return Ok(());
                }
            }
            bail!("driver did not announce its address in its first {READY_LINES} lines")
        })
        .await
        .context("test browser startup timed out while waiting for the driver address")
        .and_then(|result| result);
        if let Err(error) = ready {
            let error = error.context(driver.diagnostics());
            return Err(with_cleanup(error, driver.terminate().await));
        }
        Ok(driver)
    }

    /// Which engine this is driving, for whatever reads it back.
    #[inline]
    pub(crate) fn engine(&self) -> Engine {
        self.engine
    }

    #[inline]
    pub(crate) async fn io(&mut self) -> Result<bool> {
        use tokio::io::AsyncBufReadExt;
        while self.stdout_open || self.stderr_open {
            let (n, stderr) = tokio::select! {
                n = self.stdout.read_until(b'\n', &mut self.stdout_line), if self.stdout_open => (n?, false),
                n = self.stderr.read_until(b'\n', &mut self.stderr_line), if self.stderr_open => (n?, true),
            };
            if n == 0 {
                if stderr {
                    self.stderr_open = false;
                } else {
                    self.stdout_open = false;
                }
                continue;
            }
            // Keep each pipe's partial line across select cancellation.
            let bytes = if stderr {
                &mut self.stderr_line
            } else {
                &mut self.stdout_line
            };
            let line = String::from_utf8_lossy(bytes);
            self.log.push_str(&line);
            if self.log.len() > 8192 {
                let mut at = self.log.len() - 8192;
                while !self.log.is_char_boundary(at) {
                    at += 1;
                }
                self.log.drain(..at);
            }
            tracing::trace!(driver = self.engine.driver(), stderr, line = %line.trim(), "test driver output");
            bytes.clear();
            return Ok(true);
        }
        Ok(false)
    }

    pub(crate) fn diagnostics(&self) -> String {
        format!("{}{}", self.engine.driver(), quoted(&self.log))
    }

    /// Drain both pipes while a protocol operation is pending: a full stderr
    /// pipe during browser boot must not masquerade as a hung session request.
    pub(crate) async fn during<T>(
        &mut self,
        deadline: Instant,
        stage: &str,
        operation: impl Future<Output = Result<T>>,
    ) -> Result<T> {
        let mut operation = std::pin::pin!(operation);
        let result = loop {
            tokio::select! {
                biased;
                _ = tokio::time::sleep_until(deadline) => break Err(TimedOut(stage.to_owned()).into()),
                result = operation.as_mut() => break result,
                read = self.io(), if self.stdout_open || self.stderr_open => {
                    if let Err(error) = read { break Err(error); }
                    // A driver may close logging pipes before replying to quit.
                    // Keep polling the protocol, still under the same deadline.
                }
            }
        };
        result.with_context(|| format!("browser {stage}: {}", self.diagnostics()))
    }

    pub(crate) async fn terminate(&mut self) -> Result<()> {
        self.process.reap().await
    }
}

/// A driver that exited before announcing its address because the port it
/// picked was taken before it could listen on it, which starting it again
/// gets past.
#[derive(Debug)]
pub(crate) struct PortTaken;

impl fmt::Display for PortTaken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(
            "driver stopped before announcing its address: the port it picked \
             was taken before it could listen on it",
        )
    }
}

impl std::error::Error for PortTaken {}

/// A browser operation that did not answer by its deadline, named by stage.
#[derive(Debug)]
pub(crate) struct TimedOut(pub(crate) String);

impl fmt::Display for TimedOut {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "test browser {} timed out", self.0)
    }
}

impl std::error::Error for TimedOut {}

pub(crate) fn with_cleanup(error: anyhow::Error, cleanup: Result<()>) -> anyhow::Error {
    match cleanup {
        Ok(()) => error,
        Err(cleanup) => error.context(format!("test browser cleanup also failed: {cleanup:#}")),
    }
}

/// How many lines of a driver's greeting are read while waiting for it to say it
/// is listening. chromedriver takes four; the rest is headroom for a version
/// that says more.
const READY_LINES: usize = 16;

/// How many more times a driver that lost the port it picked is started before
/// its start fails. Losing it is rare, so losing it again on the next try is
/// rarer still; a driver that keeps losing has something else wrong with it.
const PORT_RETRIES: usize = 3;

impl Engine {
    /// How this engine's driver is told to serve on a port of its own choosing.
    fn port_args(self) -> &'static [&'static str] {
        match self {
            Engine::Firefox => &["--port", "0"],
            Engine::Chrome => &["--port=0"],
        }
    }

    /// Whether what the driver said before it exited says that the port it
    /// picked was taken before it could listen on it.
    ///
    /// Only chromedriver loses one: geckodriver listens on the port the system
    /// gives it, while chromedriver listens on `[::1]` first and then asks for
    /// the same number on `127.0.0.1`, saying `IPv4 port not available` when it
    /// is taken (or the IPv6 one, the other way around).
    fn lost_its_port(self, said: &str) -> bool {
        match self {
            Engine::Firefox => false,
            Engine::Chrome => said.contains("port not available"),
        }
    }

    /// The address a line of the driver's greeting announces, if it is the line
    /// that announces one.
    fn address_of(self, line: &str) -> Option<SocketAddr> {
        match self {
            Engine::Firefox => {
                let at = line.find("Listening on ")? + "Listening on ".len();
                line[at..].trim().parse().ok()
            }
            Engine::Chrome => {
                const SAID: &str = "started successfully on port ";

                let at = line.find(SAID)? + SAID.len();
                let port: u16 = line[at..].trim().trim_end_matches('.').parse().ok()?;

                Some(SocketAddr::from(([127, 0, 0, 1], port)))
            }
        }
    }
}

/// Whatever the driver managed to say, set off so it reads as its words rather
/// than as this suite's.
fn quoted(said: &str) -> String {
    match said.trim() {
        "" => String::from(" It printed nothing."),
        said => format!(" It said:\n{said}"),
    }
}

#[cfg(test)]
mod tests {
    use super::{Engine, motion_preference, theme_preference};

    #[test]
    fn theme_preferences_are_explicit() {
        assert!(theme_preference("dark").unwrap());
        assert!(!theme_preference("light").unwrap());
        for invalid in ["", "Dark", "LIGHT", "drak", "auto"] {
            let error = theme_preference(invalid).unwrap_err();
            assert!(error.to_string().contains("E2E_THEME"));
        }
    }

    #[test]
    fn motion_preferences_are_explicit_and_do_not_replace_theme_preferences() {
        assert!(motion_preference("reduce").unwrap());
        assert!(!motion_preference("normal").unwrap());
        for invalid in ["", "false", "off", "reduced"] {
            assert!(motion_preference(invalid).is_err());
        }
        for reduced in [false, true] {
            let caps = Engine::Firefox
                .with_preferences(false, Some(true), Some(reduced), None)
                .unwrap();
            let prefs = &caps.get("moz:firefoxOptions").unwrap()["prefs"];
            assert_eq!(prefs["ui.systemUsesDarkTheme"], 1);
            assert_eq!(prefs["ui.prefersReducedMotion"], i64::from(reduced));
            let error = Engine::Chrome
                .with_preferences(false, None, Some(reduced), None)
                .unwrap_err();
            assert!(error.to_string().contains("E2E_MOTION"));
        }
        let caps = Engine::Firefox
            .with_preferences(false, None, None, None)
            .unwrap();
        assert!(
            caps.get("moz:firefoxOptions")
                .unwrap()
                .get("prefs")
                .is_none()
        );
        assert!(
            Engine::Chrome
                .with_preferences(false, None, None, None)
                .is_ok()
        );
    }

    /// **A forced device pixel ratio reaches both engines**, unlike theme and
    /// motion, which are Firefox-only preferences.
    #[test]
    fn a_forced_scale_reaches_both_engines() {
        let caps = Engine::Firefox
            .with_preferences(false, None, None, Some(2.0))
            .unwrap();
        let prefs = &caps.get("moz:firefoxOptions").unwrap()["prefs"];
        assert_eq!(prefs["layout.css.devPixelsPerPx"], "2");

        let caps = Engine::Chrome
            .with_preferences(false, None, None, Some(2.0))
            .unwrap();
        let args = caps.get("goog:chromeOptions").unwrap()["args"]
            .as_array()
            .unwrap();
        assert!(args.iter().any(|a| a == "--force-device-scale-factor=2"));
    }

    /// **Every engine is named, parses back, and has a driver of its own.** The
    /// list is short enough that this looks like ceremony and is not: a third
    /// entry added with a copied `name` would make `--browser` reach the wrong
    /// one, silently, and the suite would report the engine it was not running.
    #[test]
    fn every_engine_round_trips_through_its_name() {
        for engine in Engine::ALL {
            assert_eq!(engine.name().parse::<Engine>().unwrap(), engine);

            assert_eq!(
                engine.name().to_uppercase().parse::<Engine>().unwrap(),
                engine
            );
        }

        for pair in Engine::ALL.windows(2) {
            assert_ne!(pair[0].name(), pair[1].name());
            assert_ne!(pair[0].driver(), pair[1].driver());
        }
    }

    /// A name nothing answers to says what would have worked, rather than
    /// failing somewhere further in with a spawn error naming one binary.
    #[test]
    fn a_browser_nothing_drives_is_refused_with_the_list() {
        let error = "safari".parse::<Engine>().unwrap_err().to_string();

        for engine in Engine::ALL {
            assert!(
                error.contains(engine.name()),
                "{error} does not offer {engine}"
            );
        }
    }

    /// **Each driver's greeting is read for the port it took, and only the line
    /// that carries one counts.**
    #[test]
    fn each_driver_is_read_for_the_port_it_took() {
        use std::net::SocketAddr;

        let gecko = "1730000000\tgeckodriver\tINFO\tListening on 127.0.0.1:51234";

        let chrome = [
            "Starting ChromeDriver 151.0.7922.138 (abcdef) on port 0",
            "Only local connections are allowed.",
            "Please see https://chromedriver.chromium.org/security-considerations \
             for suggestions on keeping ChromeDriver safe.",
            "ChromeDriver was started successfully on port 52725.",
        ];

        let expect = |port| Some(SocketAddr::from(([127, 0, 0, 1], port)));

        assert_eq!(Engine::Firefox.address_of(gecko), expect(51234));
        assert_eq!(Engine::Chrome.address_of(gecko), None);

        assert_eq!(Engine::Chrome.address_of(chrome[3]), expect(52725));

        for line in &chrome[..3] {
            assert_eq!(
                Engine::Chrome.address_of(line),
                None,
                "{line:?} is not where the port is"
            );
            assert_eq!(Engine::Firefox.address_of(line), None);
        }
    }

    /// **Only chromedriver saying its port was not available counts as losing
    /// the port it picked**, so no other early exit is started again.
    #[test]
    fn only_a_taken_port_is_read_as_losing_it() {
        let lost = [
            "Starting ChromeDriver 154.0.8037.92 (abcdef) on port 0",
            "[1759451000.123][SEVERE]: bind() failed: Address already in use (98)",
            "IPv4 port not available. Exiting...",
        ]
        .join("\n");

        assert!(Engine::Chrome.lost_its_port(&lost));
        assert!(Engine::Chrome.lost_its_port("IPv6 port not available. Exiting..."));
        assert!(!Engine::Firefox.lost_its_port(&lost));

        for said in [
            "",
            "Starting ChromeDriver 154.0.8037.92 (abcdef) on port 0",
            "ChromeDriver was started successfully on port 52725.",
            "error while loading shared libraries: libnss3.so",
        ] {
            assert!(!Engine::Chrome.lost_its_port(said), "{said:?}");
        }
    }

    /// **Both are told to pick a port, which is what makes starting several at
    /// once safe** — and the two spellings are not interchangeable.
    /// chromedriver answers a separated `--port 0` with its usage and an exit.
    #[test]
    fn each_driver_is_told_to_pick_its_own_port() {
        for engine in Engine::ALL {
            let args = engine.port_args();

            assert!(
                args.iter().any(|arg| arg.contains('0')),
                "{engine} is not asking for a port of the driver's choosing"
            );
        }

        assert_eq!(Engine::Firefox.port_args(), ["--port", "0"]);
        assert_eq!(Engine::Chrome.port_args(), ["--port=0"]);
    }

    /// The suite asks the machine what it can drive before it tries to drive
    /// anything, so a machine with neither driver is told what to install
    /// instead of being handed a spawn error naming one binary.
    #[test]
    fn a_machine_with_no_driver_is_told_what_would_have_worked() {
        if Engine::detect().is_some() {
            assert!(Engine::require().is_ok());
            return;
        }

        let error = Engine::require().unwrap_err().to_string();

        for engine in Engine::ALL {
            assert!(
                error.contains(engine.driver()),
                "{error} does not name a driver"
            );
        }
    }
}

#[cfg(all(test, unix))]
pub(crate) mod lifecycle_tests {
    use super::*;
    use tokio::process::Command;

    pub(crate) async fn fake(address: SocketAddr) -> (Driver, i32) {
        let mut command = Command::new("sh");
        command.args([
            "-c",
            &format!("echo 'Listening on {address}'; exec sleep 60"),
        ]);
        let driver = Driver::start(
            Engine::Firefox,
            &mut command,
            Instant::now() + STARTUP_TIMEOUT,
        )
        .await
        .unwrap();
        let pid = driver.process.child.id().unwrap() as i32;
        (driver, pid)
    }

    pub(crate) async fn gone(pid: i32) {
        timeout(Duration::from_secs(2), async {
            loop {
                let result = unsafe { libc::kill(pid, 0) };
                if result != 0
                    && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
                {
                    break;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("the owned driver must be reaped");
    }

    #[tokio::test]
    async fn readiness_timeout_keeps_stderr_and_reaps_its_process() {
        let mut command = Command::new("sh");
        command.args([
            "-c",
            "echo owned-pid=$$ >&2; echo boot-stalled >&2; exec sleep 60",
        ]);
        let error = Driver::start(
            Engine::Firefox,
            &mut command,
            Instant::now() + Duration::from_millis(250),
        )
        .await
        .err()
        .unwrap();
        let message = format!("{error:#}");
        assert!(message.contains("boot-stalled"), "{message}");
        assert!(message.contains("startup timed out"), "{message}");
        let pid = message
            .lines()
            .find_map(|line| line.strip_prefix("owned-pid="))
            .unwrap()
            .parse()
            .unwrap();
        gone(pid).await;
    }

    #[tokio::test]
    async fn early_driver_exit_reports_its_original_error_and_output() {
        let mut command = Command::new("sh");
        command.args(["-c", "echo fatal-startup-marker >&2; exit 7"]);
        let error = Driver::start(
            Engine::Firefox,
            &mut command,
            Instant::now() + STARTUP_TIMEOUT,
        )
        .await
        .err()
        .unwrap();
        let message = format!("{error:#}");
        assert!(message.contains("fatal-startup-marker"), "{message}");
        assert!(message.contains("stopped before announcing"), "{message}");
    }

    /// A fake chromedriver that loses its port on its first `losses` starts,
    /// and on the start after that announces port 12345, recording each start
    /// in `starts`.
    fn losing(losses: usize, starts: &std::path::Path) -> Command {
        let mut command = Command::new("sh");
        command.args([
            "-c",
            r#"echo start >> "$1"
            if [ "$(wc -l < "$1")" -le "$2" ]; then
                echo '[SEVERE]: bind() failed: Address already in use (98)' >&2
                echo 'IPv4 port not available. Exiting...' >&2
                exit 1
            fi
            echo 'ChromeDriver was started successfully on port 12345.'
            exec sleep 60"#,
            "fake-chromedriver",
        ]);
        command.arg(starts).arg(losses.to_string());
        command
    }

    fn starts(path: &std::path::Path) -> usize {
        std::fs::read_to_string(path).unwrap().lines().count()
    }

    #[tokio::test]
    async fn a_driver_that_lost_its_port_is_started_again() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let mut command = losing(PORT_RETRIES, file.path());
        let mut driver = Driver::start_until_it_keeps_a_port(
            Engine::Chrome,
            &mut command,
            Instant::now() + STARTUP_TIMEOUT,
        )
        .await
        .unwrap();
        assert_eq!(driver.address.port(), 12345);
        assert_eq!(starts(file.path()), PORT_RETRIES + 1);
        driver.terminate().await.unwrap();
    }

    #[tokio::test]
    async fn a_driver_that_keeps_losing_its_port_fails_saying_so() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let mut command = losing(usize::MAX >> 1, file.path());
        let error = Driver::start_until_it_keeps_a_port(
            Engine::Chrome,
            &mut command,
            Instant::now() + STARTUP_TIMEOUT,
        )
        .await
        .err()
        .unwrap();
        let message = format!("{error:#}");
        assert_eq!(starts(file.path()), PORT_RETRIES + 1);
        assert!(
            message.contains("lost the port it picked 4 times"),
            "{message}"
        );
        assert!(message.contains("IPv4 port not available"), "{message}");
        assert!(message.contains("stopped before announcing"), "{message}");
    }

    #[tokio::test]
    async fn a_driver_that_stopped_for_another_reason_is_not_started_again() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let mut command = Command::new("sh");
        command.args([
            "-c",
            r#"echo start >> "$1"; echo 'cannot open display' >&2; exit 1"#,
            "fake-chromedriver",
        ]);
        command.arg(file.path());
        let error = Driver::start_until_it_keeps_a_port(
            Engine::Chrome,
            &mut command,
            Instant::now() + STARTUP_TIMEOUT,
        )
        .await
        .err()
        .unwrap();
        let message = format!("{error:#}");
        assert_eq!(starts(file.path()), 1);
        assert!(message.contains("cannot open display"), "{message}");
        assert!(!message.contains("lost the port"), "{message}");
    }

    #[tokio::test]
    async fn closing_one_log_pipe_does_not_hide_the_other_pipes_greeting() {
        let mut command = Command::new("sh");
        command.args([
            "-c",
            "exec 1>&-; echo 'Listening on 127.0.0.1:12345' >&2; exec sleep 60",
        ]);
        let mut driver = Driver::start(
            Engine::Firefox,
            &mut command,
            Instant::now() + STARTUP_TIMEOUT,
        )
        .await
        .unwrap();
        assert_eq!(driver.address.port(), 12345);
        assert!(driver.diagnostics().contains("Listening on"));
        driver.terminate().await.unwrap();
    }

    #[tokio::test]
    async fn cancelling_before_the_driver_announces_its_address_reaps_it() {
        let pid_file = tempfile::NamedTempFile::new().unwrap();
        let path = pid_file.path().to_owned();
        let mut command = Command::new("sh");
        command.args([
            "-c",
            "printf '%s' \"$$\" > \"$1\"; exec sleep 60",
            "test-driver",
        ]);
        command.arg(&path);
        let starting = tokio::spawn(async move {
            Driver::start(
                Engine::Firefox,
                &mut command,
                Instant::now() + STARTUP_TIMEOUT,
            )
            .await
        });
        let pid = timeout(STARTUP_TIMEOUT, async {
            loop {
                if let Ok(pid) = tokio::fs::read_to_string(&path)
                    .await
                    .unwrap()
                    .parse::<i32>()
                {
                    break pid;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .unwrap();
        starting.abort();
        assert!(matches!(starting.await, Err(error) if error.is_cancelled()));
        gone(pid).await;
    }

    #[tokio::test]
    async fn killing_an_owned_group_does_not_kill_an_unrelated_child() {
        use tokio::io::AsyncBufReadExt;
        let mut unrelated = Command::new("sleep")
            .arg("60")
            .kill_on_drop(true)
            .spawn()
            .unwrap();
        let mut command = Command::new("sh");
        command.args(["-c", "sleep 60 & echo $!; wait"]);
        command.stdout(std::process::Stdio::piped());
        let mut owned = OwnedProcess::spawn(&mut command).unwrap();
        let leader = owned.child.id().unwrap() as i32;
        let mut child_line = String::new();
        tokio::io::BufReader::new(owned.child.stdout.take().unwrap())
            .read_line(&mut child_line)
            .await
            .unwrap();
        let descendant: i32 = child_line.trim().parse().unwrap();
        assert_ne!(leader, descendant);
        assert_eq!(unsafe { libc::getpgid(leader) }, leader);
        assert_eq!(unsafe { libc::getpgid(descendant) }, leader);
        assert_ne!(
            unsafe { libc::getpgid(unrelated.id().unwrap() as i32) },
            leader
        );
        owned.reap().await.unwrap();
        gone(leader).await;
        // Grandchildren are reaped by their new parent, not this harness. A
        // zombie has stopped running even if init has not collected it yet.
        timeout(Duration::from_secs(2), async {
            loop {
                let dead = unsafe { libc::kill(descendant, 0) } != 0;
                #[cfg(target_os = "linux")]
                let dead = dead
                    || std::fs::read_to_string(format!("/proc/{descendant}/stat")).is_ok_and(
                        |stat| {
                            stat.rsplit_once(") ")
                                .is_some_and(|(_, fields)| fields.starts_with('Z'))
                        },
                    );
                if dead {
                    break;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .unwrap();
        assert!(unrelated.try_wait().unwrap().is_none());
        unrelated.kill().await.unwrap();
    }

    #[test]
    fn cleanup_failure_keeps_the_original_failure_chain() {
        let error = with_cleanup(
            anyhow!("original assertion failed"),
            Err(TimedOut("quit".to_owned()).into()),
        );
        let message = format!("{error:#}");
        assert!(message.contains("original assertion failed"));
        assert!(message.contains("quit timed out"));
    }

    #[test]
    fn a_timeout_stays_recognisable_under_its_context() {
        let error = anyhow::Error::from(TimedOut("quit".to_owned()))
            .context("browser quit: geckodriver It printed nothing.");
        assert!(error.downcast_ref::<TimedOut>().is_some());
        assert!(format!("{error:#}").contains("test browser quit timed out"));
        assert!(
            anyhow!("quit timed out")
                .downcast_ref::<TimedOut>()
                .is_none()
        );
    }
}