Skip to main content

zebra_test/
command.rs

1//! Launching test commands for Zebra integration and acceptance tests.
2
3use std::{
4    collections::HashSet,
5    convert::Infallible as NoDir,
6    fmt::{self, Debug},
7    io::{ErrorKind, Write as _},
8    path::Path,
9    process::{Child, ChildStdin, Command, ExitStatus, Output, Stdio},
10    sync::mpsc::{self, Receiver, Sender},
11    thread::{self, JoinHandle},
12    time::{Duration, Instant},
13};
14
15#[cfg(unix)]
16use std::os::unix::process::ExitStatusExt;
17
18use color_eyre::{
19    eyre::{eyre, Context, Report, Result},
20    Help, SectionExt,
21};
22use regex::RegexSet;
23#[cfg(unix)]
24use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, BufReader};
25use tracing::instrument;
26
27#[macro_use]
28mod arguments;
29
30#[cfg(unix)]
31#[path = "command/process_group/unix.rs"]
32mod process_group;
33#[cfg(windows)]
34#[path = "command/process_group/windows.rs"]
35#[allow(unsafe_code)]
36mod process_group;
37
38pub mod to_regex;
39
40pub use self::arguments::Arguments;
41use self::to_regex::{CollectRegexSet, RegexSetExt, ToRegexSet};
42
43/// Bound exit and output draining independently of an expired observation budget.
44const CHILD_CLEANUP_TIMEOUT: Duration = Duration::from_secs(1);
45
46/// A demand-driven child pipe reader. Idle readers do not consume child output.
47///
48/// Each read runs on an owned thread so synchronous harness methods can also be used inside
49/// async tests. Pipe reads are cancellable, including when a child keeps a partial line
50/// or an inherited pipe open. Dropping the reader stops and joins its thread.
51#[derive(Debug)]
52pub struct ChildOutput {
53    requests: Sender<ReadRequest>,
54    responses: Receiver<ReadResponse>,
55    worker: Option<JoinHandle<()>>,
56    deadline: Option<Instant>,
57    drained: Option<ReadResponse>,
58    cancelled: tokio::sync::watch::Sender<bool>,
59    finished: bool,
60    failure_regexes: RegexSet,
61    ignore_regexes: RegexSet,
62    cmd: String,
63    bypass_test_capture: bool,
64}
65
66#[derive(Debug)]
67enum ReadRequest {
68    Line(Option<Instant>),
69    Drain(Option<Instant>),
70    Stop,
71}
72
73#[derive(Debug)]
74struct ReadResponse {
75    bytes: Vec<u8>,
76    error: Option<std::io::Error>,
77}
78
79impl ChildOutput {
80    #[cfg(unix)]
81    fn new<R, P>(reader: R, convert: fn(R) -> std::io::Result<P>) -> Self
82    where
83        R: Send + 'static,
84        P: AsyncRead + Unpin + 'static,
85    {
86        let (requests, receive_requests) = mpsc::channel();
87        let (send_responses, responses) = mpsc::channel();
88        let (cancelled, mut worker_cancelled) = tokio::sync::watch::channel(false);
89        let worker = thread::spawn(move || {
90            let runtime = tokio::runtime::Builder::new_current_thread()
91                .enable_io()
92                .enable_time()
93                .build();
94            let mut pipe = runtime
95                .as_ref()
96                .map_err(|error| error.to_string())
97                .and_then(|runtime| {
98                    let _guard = runtime.enter();
99                    convert(reader)
100                        .map(BufReader::new)
101                        .map_err(|error| error.to_string())
102                });
103            let mut pending = Vec::new();
104
105            while let Ok(request) = receive_requests.recv() {
106                let (deadline, drain) = match request {
107                    ReadRequest::Line(deadline) => (deadline, false),
108                    ReadRequest::Drain(deadline) => (deadline, true),
109                    ReadRequest::Stop => break,
110                };
111                let mut bytes = if drain {
112                    std::mem::take(&mut pending)
113                } else {
114                    Vec::new()
115                };
116                let result = match (&runtime, &mut pipe) {
117                    (Ok(runtime), Ok(pipe)) => runtime.block_on(async {
118                        let read = async {
119                            if drain {
120                                let mut chunk = [0; 8192];
121                                loop {
122                                    let count = pipe.read(&mut chunk).await?;
123                                    if count == 0 {
124                                        break Ok(bytes.len());
125                                    }
126                                    bytes.extend_from_slice(&chunk[..count]);
127                                }
128                            } else {
129                                pipe.read_until(b'\n', &mut pending).await
130                            }
131                        };
132                        let read_with_deadline = async {
133                            match deadline {
134                                Some(deadline) if Instant::now() >= deadline => {
135                                    Err(std::io::Error::new(
136                                        ErrorKind::TimedOut,
137                                        "test child output deadline elapsed",
138                                    ))
139                                }
140                                Some(deadline) => tokio::time::timeout_at(deadline.into(), read)
141                                    .await
142                                    .unwrap_or_else(|_| {
143                                        Err(std::io::Error::new(
144                                            ErrorKind::TimedOut,
145                                            "test child output deadline elapsed",
146                                        ))
147                                    }),
148                                None => read.await,
149                            }
150                        };
151                        tokio::select! {
152                            result = read_with_deadline => result,
153                            _ = worker_cancelled.changed() => Err(std::io::Error::new(
154                                ErrorKind::Interrupted, "test child output read cancelled",
155                            )),
156                        }
157                    }),
158                    (_, Err(error)) => Err(std::io::Error::other(error.clone())),
159                    (Err(error), _) => Err(std::io::Error::other(error.to_string())),
160                };
161                if !drain && result.is_ok() {
162                    bytes = std::mem::take(&mut pending);
163                }
164                if send_responses
165                    .send(ReadResponse {
166                        bytes,
167                        error: result.err(),
168                    })
169                    .is_err()
170                    || drain
171                {
172                    break;
173                }
174            }
175        });
176
177        Self {
178            requests,
179            responses,
180            worker: Some(worker),
181            deadline: None,
182            drained: None,
183            cancelled,
184            finished: false,
185            failure_regexes: RegexSet::empty(),
186            ignore_regexes: RegexSet::empty(),
187            cmd: String::new(),
188            bypass_test_capture: false,
189        }
190    }
191
192    #[cfg(windows)]
193    fn new<R>(mut reader: R) -> Self
194    where
195        R: std::io::Read + std::os::windows::io::AsRawHandle + Send + 'static,
196    {
197        let (requests, receive_requests) = mpsc::channel();
198        let (send_responses, responses) = mpsc::channel();
199        let (cancelled, worker_cancelled) = tokio::sync::watch::channel(false);
200        let worker = thread::spawn(move || {
201            let mut pending = Vec::new();
202            while let Ok(request) = receive_requests.recv() {
203                let (deadline, drain) = match request {
204                    ReadRequest::Line(deadline) => (deadline, false),
205                    ReadRequest::Drain(deadline) => (deadline, true),
206                    ReadRequest::Stop => break,
207                };
208                let mut bytes = if drain {
209                    std::mem::take(&mut pending)
210                } else {
211                    Vec::new()
212                };
213                let result = loop {
214                    if *worker_cancelled.borrow() {
215                        break Err(std::io::Error::new(
216                            ErrorKind::Interrupted,
217                            "output read cancelled",
218                        ));
219                    }
220                    if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
221                        break Err(std::io::Error::new(
222                            ErrorKind::TimedOut,
223                            "output deadline elapsed",
224                        ));
225                    }
226                    if !drain {
227                        if let Some(end) = pending.iter().position(|byte| *byte == b'\n') {
228                            let rest = pending.split_off(end + 1);
229                            bytes = std::mem::replace(&mut pending, rest);
230                            break Ok(());
231                        }
232                    }
233                    match windows_pipe_available(&reader) {
234                        Ok(None) => {
235                            if !drain {
236                                bytes = std::mem::take(&mut pending);
237                            }
238                            break Ok(());
239                        }
240                        Ok(Some(0)) => thread::sleep(Duration::from_millis(10)),
241                        Ok(Some(available)) => {
242                            let mut chunk = [0; 8192];
243                            let count = available.min(chunk.len());
244                            match reader.read(&mut chunk[..count]) {
245                                Ok(0) => break Ok(()),
246                                Ok(count) if drain => bytes.extend_from_slice(&chunk[..count]),
247                                Ok(count) => pending.extend_from_slice(&chunk[..count]),
248                                Err(error) => break Err(error),
249                            }
250                        }
251                        Err(error) => break Err(error),
252                    }
253                };
254                if send_responses
255                    .send(ReadResponse {
256                        bytes,
257                        error: result.err(),
258                    })
259                    .is_err()
260                    || drain
261                {
262                    break;
263                }
264            }
265        });
266        Self {
267            requests,
268            responses,
269            worker: Some(worker),
270            deadline: None,
271            drained: None,
272            cancelled,
273            finished: false,
274            failure_regexes: RegexSet::empty(),
275            ignore_regexes: RegexSet::empty(),
276            cmd: String::new(),
277            bypass_test_capture: false,
278        }
279    }
280
281    fn receive(&self) -> ReadResponse {
282        self.responses.recv().unwrap_or_else(|error| ReadResponse {
283            bytes: Vec::new(),
284            error: Some(std::io::Error::other(error)),
285        })
286    }
287
288    fn start_drain(&self, deadline: Option<Instant>) {
289        let _ = self.requests.send(ReadRequest::Drain(deadline));
290    }
291
292    fn finish_drain(&mut self) -> ReadResponse {
293        let response = self.drained.take().unwrap_or_else(|| self.receive());
294        self.finished = true;
295        if let Some(worker) = self.worker.take() {
296            let _ = worker.join();
297        }
298        response
299    }
300
301    fn poll_drain(&mut self) -> std::io::Result<()> {
302        if self.drained.is_none() {
303            match self.responses.try_recv() {
304                Ok(response) => self.drained = Some(response),
305                Err(mpsc::TryRecvError::Empty) => return Ok(()),
306                Err(error) => return Err(std::io::Error::other(error)),
307            }
308        }
309        match self
310            .drained
311            .as_ref()
312            .and_then(|response| response.error.as_ref())
313        {
314            Some(error) => Err(std::io::Error::new(error.kind(), error.to_string())),
315            None => Ok(()),
316        }
317    }
318}
319
320impl Iterator for ChildOutput {
321    type Item = std::io::Result<String>;
322
323    fn next(&mut self) -> Option<Self::Item> {
324        if self.finished {
325            return None;
326        }
327        if let Err(error) = self.requests.send(ReadRequest::Line(self.deadline)) {
328            self.finished = true;
329            return Some(Err(std::io::Error::other(error)));
330        }
331        let response = self.receive();
332        if let Some(error) = response.error {
333            self.finished = true;
334            return Some(Err(error));
335        }
336        if response.bytes.is_empty() {
337            self.finished = true;
338            return None;
339        }
340        let mut bytes = response.bytes;
341        if bytes.last() == Some(&b'\n') {
342            bytes.pop();
343            if bytes.last() == Some(&b'\r') {
344                bytes.pop();
345            }
346        }
347        Some(check_failure_regexes(
348            String::from_utf8(bytes)
349                .map_err(|error| std::io::Error::new(ErrorKind::InvalidData, error)),
350            &self.failure_regexes,
351            &self.ignore_regexes,
352            &self.cmd,
353            self.bypass_test_capture,
354        ))
355    }
356}
357
358impl Drop for ChildOutput {
359    fn drop(&mut self) {
360        let _ = self.cancelled.send(true);
361        let _ = self.requests.send(ReadRequest::Stop);
362        if let Some(worker) = self.worker.take() {
363            let _ = worker.join();
364        }
365    }
366}
367
368/// Poll an owned anonymous pipe without starting an uncancellable Windows blocking read.
369#[cfg(windows)]
370#[allow(unsafe_code)]
371fn windows_pipe_available(
372    pipe: &impl std::os::windows::io::AsRawHandle,
373) -> std::io::Result<Option<usize>> {
374    use windows_sys::Win32::{Foundation::ERROR_BROKEN_PIPE, System::Pipes::PeekNamedPipe};
375    let mut available = 0;
376    // SAFETY: the pipe is owned by this reader for the whole call. The only non-null output
377    // pointer refers to a live u32, and no read or handle-close can race with this peek.
378    let result = unsafe {
379        PeekNamedPipe(
380            pipe.as_raw_handle(),
381            std::ptr::null_mut(),
382            0,
383            std::ptr::null_mut(),
384            &mut available,
385            std::ptr::null_mut(),
386        )
387    };
388    if result != 0 {
389        // Windows pointers are at least 32 bits, so the u32 byte count fits usize.
390        Ok(Some(available as usize))
391    } else {
392        let error = std::io::Error::last_os_error();
393        // The Windows broken-pipe error code (109) fits in an i32.
394        if error.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
395            Ok(None)
396        } else {
397            Err(error)
398        }
399    }
400}
401
402/// Runs a command
403pub fn test_cmd(command_path: &str, tempdir: &Path) -> Result<Command> {
404    let mut cmd = Command::new(command_path);
405    cmd.current_dir(tempdir);
406
407    Ok(cmd)
408}
409
410// TODO: split these extensions into their own module
411
412/// Wrappers for `Command` methods to integrate with [`zebra_test`](crate).
413pub trait CommandExt {
414    /// wrapper for `status` fn on `Command` that constructs informative error
415    /// reports
416    fn status2(&mut self) -> Result<TestStatus, Report>;
417
418    /// wrapper for `output` fn on `Command` that constructs informative error
419    /// reports
420    fn output2(&mut self) -> Result<TestOutput<NoDir>, Report>;
421
422    /// Spawns a command with informative errors and owned descendant cleanup.
423    ///
424    /// On Unix, children that leave the process group are outside the cleanup boundary.
425    /// Callers must not externally reap the leader or enable SIGCHLD auto-reaping.
426    /// On Windows, creation flags must remain at their default zero; the child starts suspended
427    /// so its job is attached before command execution. Job assignment restrictions cause an error.
428    fn spawn2<T>(&mut self, dir: T, command_path: impl ToString) -> Result<TestChild<T>, Report>;
429}
430
431impl CommandExt for Command {
432    /// wrapper for `status` fn on `Command` that constructs informative error
433    /// reports
434    fn status2(&mut self) -> Result<TestStatus, Report> {
435        let cmd = format!("{self:?}");
436        let status = self.status();
437
438        let command = || cmd.clone().header("Command:");
439
440        let status = status
441            .wrap_err("failed to execute process")
442            .with_section(command)?;
443
444        Ok(TestStatus { cmd, status })
445    }
446
447    /// wrapper for `output` fn on `Command` that constructs informative error
448    /// reports
449    fn output2(&mut self) -> Result<TestOutput<NoDir>, Report> {
450        let output = self.output();
451
452        let output = output
453            .wrap_err("failed to execute process")
454            .with_section(|| format!("{self:?}").header("Command:"))?;
455
456        Ok(TestOutput {
457            dir: None,
458            output,
459            cmd: format!("{self:?}"),
460        })
461    }
462
463    /// wrapper for `spawn` fn on `Command` that constructs informative error
464    /// reports using the original `command_path`
465    fn spawn2<T>(&mut self, dir: T, command_path: impl ToString) -> Result<TestChild<T>, Report> {
466        // Tests usually kill their children, which then can't remove their temporary files, such
467        // as ephemeral Zebra states. Their temporary directory goes with the `TestChild` instead.
468        // Unix uses `TMPDIR`, and Windows uses `TMP` or `TEMP`.
469        let tmp_dir = tempfile::tempdir().wrap_err("failed to create the child's TMPDIR")?;
470        for var in ["TMPDIR", "TMP", "TEMP"] {
471            self.env(var, tmp_dir.path());
472        }
473
474        let command_and_args = format!("{self:?}");
475        let child = process_group::spawn(self);
476
477        let (child, process_group) = child
478            .wrap_err("failed to execute process")
479            .with_section(|| command_and_args.clone().header("Command:"))?;
480
481        Ok(TestChild {
482            dir: Some(dir),
483            cmd: command_and_args,
484            command_path: command_path.to_string(),
485            child: Some(child),
486            process_group,
487            killed: false,
488            stdout: None,
489            stderr: None,
490            failure_regexes: RegexSet::empty(),
491            ignore_regexes: RegexSet::empty(),
492            deadline: None,
493            timeout: None,
494            bypass_test_capture: false,
495            _tmp_dir: tmp_dir,
496        })
497    }
498}
499
500/// Extension trait for methods on `tempdir::TempDir` for using it as a test
501/// directory with an arbitrary command.
502///
503/// This trait is separate from `ZebradTestDirExt`, so that we can test
504/// `zebra_test::command` without running `zebrad`.
505pub trait TestDirExt
506where
507    Self: AsRef<Path> + Sized,
508{
509    /// Spawn `cmd` with `args` as a child process in this test directory,
510    /// potentially taking ownership of the tempdir for the duration of the
511    /// child process.
512    fn spawn_child_with_command(self, cmd: &str, args: Arguments) -> Result<TestChild<Self>>;
513}
514
515impl<T> TestDirExt for T
516where
517    Self: AsRef<Path> + Sized,
518{
519    #[allow(clippy::unwrap_in_result)]
520    fn spawn_child_with_command(
521        self,
522        command_path: &str,
523        args: Arguments,
524    ) -> Result<TestChild<Self>> {
525        let mut cmd = test_cmd(command_path, self.as_ref())?;
526
527        Ok(cmd
528            .args(args.into_arguments())
529            .stdout(Stdio::piped())
530            .stderr(Stdio::piped())
531            .spawn2(self, command_path)
532            .unwrap())
533    }
534}
535
536/// Test command exit status information.
537#[derive(Debug)]
538pub struct TestStatus {
539    /// The original command string.
540    pub cmd: String,
541
542    /// The exit status of the command.
543    pub status: ExitStatus,
544}
545
546impl TestStatus {
547    pub fn assert_success(self) -> Result<Self> {
548        if !self.status.success() {
549            Err(eyre!("command exited unsuccessfully")).context_from(&self)?;
550        }
551
552        Ok(self)
553    }
554
555    pub fn assert_failure(self) -> Result<Self> {
556        if self.status.success() {
557            Err(eyre!("command unexpectedly exited successfully")).context_from(&self)?;
558        }
559
560        Ok(self)
561    }
562}
563
564/// Reap only after the owned group has been retired, without an unbounded process wait.
565fn reap_before_deadline(child: &mut Child, deadline: Instant) -> std::io::Result<ExitStatus> {
566    loop {
567        if let Some(status) = child.try_wait()? {
568            return Ok(status);
569        }
570        if Instant::now() >= deadline {
571            return Err(std::io::Error::new(
572                ErrorKind::TimedOut,
573                "test child cleanup deadline elapsed before exit",
574            ));
575        }
576        thread::sleep(Duration::from_millis(10));
577    }
578}
579
580/// A test command child process.
581// TODO: split this struct into its own module (or multiple modules)
582#[derive(Debug)]
583pub struct TestChild<T> {
584    /// The working directory of the command.
585    ///
586    /// `None` when the command has been waited on,
587    /// and its output has been taken.
588    pub dir: Option<T>,
589
590    /// The full command string, including arguments and working directory.
591    pub cmd: String,
592
593    /// The path of the command, as passed to spawn2().
594    pub command_path: String,
595
596    /// The process remains private so callers cannot reap it before group cleanup.
597    child: Option<Child>,
598
599    /// The group or job is retired before the leader is reaped.
600    process_group: process_group::ProcessGroup,
601
602    /// Intentional termination switches exit waiting from observation to bounded cleanup.
603    killed: bool,
604
605    /// The demand-driven standard output stream of the child process.
606    pub stdout: Option<ChildOutput>,
607
608    /// The demand-driven standard error stream of the child process.
609    pub stderr: Option<ChildOutput>,
610
611    /// Command outputs which indicate test failure.
612    ///
613    /// This list of regexes is matches against `stdout` or `stderr`,
614    /// in every method that reads command output.
615    ///
616    /// If any line matches any failure regex, the test fails.
617    failure_regexes: RegexSet,
618
619    /// Command outputs which are ignored when checking for test failure.
620    /// These regexes override `failure_regexes`.
621    ///
622    /// This list of regexes is matches against `stdout` or `stderr`,
623    /// in every method that reads command output.
624    ///
625    /// If a line matches any ignore regex, the failure regex check is skipped for that line.
626    ignore_regexes: RegexSet,
627
628    /// The observation deadline for command output reads and natural process exit.
629    deadline: Option<Instant>,
630
631    /// The configured observation duration, used only for debugging output.
632    timeout: Option<Duration>,
633
634    /// If true, write child output directly to standard output,
635    /// bypassing the Rust test harness output capture.
636    bypass_test_capture: bool,
637
638    /// The child's `TMPDIR`, removed after the child is killed or reaped.
639    _tmp_dir: tempfile::TempDir,
640}
641
642/// Checks command output log `line` from `cmd` against a `failure_regexes` regex set,
643/// and returns an error if any regex matches. The line is skipped if it matches `ignore_regexes`.
644///
645/// Passes through errors from the underlying reader.
646pub fn check_failure_regexes(
647    line: std::io::Result<String>,
648    failure_regexes: &RegexSet,
649    ignore_regexes: &RegexSet,
650    cmd: &str,
651    bypass_test_capture: bool,
652) -> std::io::Result<String> {
653    let line = line?;
654
655    // Check if the line matches any patterns
656    let ignore_matches = ignore_regexes.matches(&line);
657    let ignore_matches: Vec<&str> = ignore_matches
658        .iter()
659        .map(|index| ignore_regexes.patterns()[index].as_str())
660        .collect();
661
662    let failure_matches = failure_regexes.matches(&line);
663    let failure_matches: Vec<&str> = failure_matches
664        .iter()
665        .map(|index| failure_regexes.patterns()[index].as_str())
666        .collect();
667
668    // If we match an ignore pattern, ignore any failure matches
669    if !ignore_matches.is_empty() {
670        let ignore_matches = ignore_matches.join(",");
671
672        let ignore_msg = if failure_matches.is_empty() {
673            format!("Log matched ignore regexes: {ignore_matches:?}, but no failure regexes",)
674        } else {
675            let failure_matches = failure_matches.join(",");
676            format!(
677                "Ignoring failure regexes: {failure_matches:?}, because log matched ignore regexes: {ignore_matches:?}",
678            )
679        };
680
681        write_to_test_logs(ignore_msg, bypass_test_capture);
682
683        return Ok(line);
684    }
685
686    // If there were no failures, pass the log line through
687    if failure_matches.is_empty() {
688        return Ok(line);
689    }
690
691    // Otherwise, if the process logged a failure message, return an error
692    let error = std::io::Error::other(format!(
693        "test command:\n\
694             {cmd}\n\n\
695             Logged a failure message:\n\
696             {line}\n\n\
697             Matching failure regex: \
698             {failure_matches:#?}\n\n\
699             All Failure regexes: \
700             {:#?}\n",
701        failure_regexes.patterns(),
702    ));
703
704    Err(error)
705}
706
707/// Write `line` to stdout, so it can be seen in the test logs.
708///
709/// Set `bypass_test_capture` to `true` or
710/// use `cargo test -- --nocapture` to see this output.
711///
712/// May cause weird reordering for stdout / stderr.
713/// Uses stdout even if the original lines were from stderr.
714#[allow(clippy::print_stdout)]
715fn write_to_test_logs<S>(line: S, bypass_test_capture: bool)
716where
717    S: AsRef<str>,
718{
719    let line = line.as_ref();
720
721    if bypass_test_capture {
722        // Send lines directly to the terminal (or process stdout file redirect).
723        #[allow(clippy::explicit_write)]
724        writeln!(std::io::stdout(), "{line}").unwrap();
725    } else {
726        // If the test fails, the test runner captures and displays this output.
727        // To show this output unconditionally, use `cargo test -- --nocapture`.
728        println!("{line}");
729    }
730
731    // Some OSes require a flush to send all output to the terminal.
732    let _ = std::io::stdout().lock().flush();
733}
734
735/// A [`CollectRegexSet`] iterator that never matches anything.
736///
737/// Used to work around type inference issues in [`TestChild::with_failure_regex_iter`].
738pub const NO_MATCHES_REGEX_ITER: &[&str] = &[];
739
740impl<T> TestChild<T> {
741    /// Returns the command's process ID.
742    ///
743    /// A process ID is an observation, not an ownership token for later cleanup.
744    pub fn id(&self) -> u32 {
745        self.child
746            .as_ref()
747            .expect("TestChild owns its process until wait_with_output consumes it")
748            .id()
749    }
750
751    /// Borrows piped standard input without exposing process reaping.
752    ///
753    /// Returns `None` if standard input was not piped.
754    pub fn stdin_mut(&mut self) -> Option<&mut ChildStdin> {
755        self.child.as_mut().and_then(|child| child.stdin.as_mut())
756    }
757
758    /// Sets up command output so each line is checked against a failure regex set,
759    /// unless it matches any of the ignore regexes.
760    ///
761    /// To never match any log lines, use `RegexSet::empty()`.
762    ///
763    /// This method is a [`TestChild::with_failure_regexes`] wrapper for
764    /// strings, `Regex`es, and [`RegexSet`]s.
765    ///
766    /// # Panics
767    ///
768    /// - adds a panic to any method that reads output,
769    ///   if any stdout or stderr lines match any failure regex
770    pub fn with_failure_regex_set<F, X>(self, failure_regexes: F, ignore_regexes: X) -> Self
771    where
772        F: ToRegexSet,
773        X: ToRegexSet,
774    {
775        let failure_regexes = failure_regexes
776            .to_regex_set()
777            .expect("failure regexes must be valid");
778
779        let ignore_regexes = ignore_regexes
780            .to_regex_set()
781            .expect("ignore regexes must be valid");
782
783        self.with_failure_regexes(failure_regexes, ignore_regexes)
784    }
785
786    /// Sets up command output so each line is checked against a failure regex set,
787    /// unless it matches any of the ignore regexes.
788    ///
789    /// To never match any log lines, use [`NO_MATCHES_REGEX_ITER`].
790    ///
791    /// This method is a [`TestChild::with_failure_regexes`] wrapper for
792    /// regular expression iterators.
793    ///
794    /// # Panics
795    ///
796    /// - adds a panic to any method that reads output,
797    ///   if any stdout or stderr lines match any failure regex
798    pub fn with_failure_regex_iter<F, X>(self, failure_regexes: F, ignore_regexes: X) -> Self
799    where
800        F: CollectRegexSet,
801        X: CollectRegexSet,
802    {
803        let failure_regexes = failure_regexes
804            .collect_regex_set()
805            .expect("failure regexes must be valid");
806
807        let ignore_regexes = ignore_regexes
808            .collect_regex_set()
809            .expect("ignore regexes must be valid");
810
811        self.with_failure_regexes(failure_regexes, ignore_regexes)
812    }
813
814    /// Sets up command output so each line is checked against a failure regex set,
815    /// unless it matches any of the ignore regexes.
816    ///
817    /// # Panics
818    ///
819    /// - adds a panic to any method that reads output,
820    ///   if any stdout or stderr lines match any failure regex
821    pub fn with_failure_regexes(
822        mut self,
823        failure_regexes: RegexSet,
824        ignore_regexes: impl Into<Option<RegexSet>>,
825    ) -> Self {
826        self.failure_regexes = failure_regexes;
827        self.ignore_regexes = ignore_regexes.into().unwrap_or_else(RegexSet::empty);
828
829        self.apply_failure_regexes_to_outputs();
830
831        self
832    }
833
834    /// Applies the failure and ignore regex sets to command output.
835    ///
836    /// # Panics
837    ///
838    /// - adds a panic to any method that reads output,
839    ///   if any stdout or stderr lines match any failure regex
840    pub fn apply_failure_regexes_to_outputs(&mut self) {
841        if self.stdout.is_none() {
842            self.stdout = self
843                .child
844                .as_mut()
845                .and_then(|child| child.stdout.take())
846                .map(|pipe| {
847                    #[cfg(unix)]
848                    {
849                        ChildOutput::new(pipe, tokio::process::ChildStdout::from_std)
850                    }
851                    #[cfg(windows)]
852                    {
853                        ChildOutput::new(pipe)
854                    }
855                });
856        }
857        if self.stderr.is_none() {
858            self.stderr = self
859                .child
860                .as_mut()
861                .and_then(|child| child.stderr.take())
862                .map(|pipe| {
863                    #[cfg(unix)]
864                    {
865                        ChildOutput::new(pipe, tokio::process::ChildStderr::from_std)
866                    }
867                    #[cfg(windows)]
868                    {
869                        ChildOutput::new(pipe)
870                    }
871                });
872        }
873        for output in [&mut self.stdout, &mut self.stderr].into_iter().flatten() {
874            output.deadline = self.deadline;
875            if output.failure_regexes.patterns() != self.failure_regexes.patterns() {
876                output.failure_regexes = self.failure_regexes.clone();
877            }
878            if output.ignore_regexes.patterns() != self.ignore_regexes.patterns() {
879                output.ignore_regexes = self.ignore_regexes.clone();
880            }
881            if output.cmd != self.cmd {
882                output.cmd.clone_from(&self.cmd);
883            }
884            output.bypass_test_capture = self.bypass_test_capture;
885        }
886    }
887
888    /// Kill the child process.
889    ///
890    /// If `ignore_exited` is `true`, log "can't kill an exited process" errors,
891    /// rather than returning them.
892    ///
893    /// Returns the result of the kill. Subsequent exit waiting and output draining use
894    /// a separate one-second cleanup grace rather than the observation deadline.
895    ///
896    /// ## BUGS
897    ///
898    /// On Windows (and possibly macOS), this function can return `Ok` for
899    /// processes that have panicked. See #1781.
900    #[spandoc::spandoc]
901    pub fn kill(&mut self, ignore_exited: bool) -> Result<()> {
902        let child = match self.child.as_mut() {
903            Some(child) => child,
904            None if ignore_exited => {
905                Self::write_to_test_logs(
906                    "test child was already taken\n\
907                     ignoring kill because ignore_exited is true",
908                    self.bypass_test_capture,
909                );
910                return Ok(());
911            }
912            None => {
913                return Err(eyre!(
914                    "test child was already taken\n\
915                     call kill() once for each child process, or set ignore_exited to true"
916                ))
917                .context_from(self.as_mut())
918            }
919        };
920
921        /// SPANDOC: Killing child process
922        let kill_result = self.process_group.kill(child).or_else(|error| {
923            if ignore_exited && error.kind() == ErrorKind::InvalidInput {
924                Ok(())
925            } else {
926                Err(error)
927            }
928        });
929
930        kill_result.context_from(self.as_mut())?;
931        self.killed = true;
932
933        Ok(())
934    }
935
936    /// Kill the process, and consume all its remaining output.
937    ///
938    /// If `ignore_exited` is `true`, log "can't kill an exited process" errors,
939    /// rather than returning them.
940    ///
941    /// Returns the result of the kill.
942    pub fn kill_and_consume_output(&mut self, ignore_exited: bool) -> Result<()> {
943        let output = self.kill_and_return_output(ignore_exited)?;
944        if !output.is_empty() {
945            Self::write_to_test_logs(output, self.bypass_test_capture);
946        }
947        Ok(())
948    }
949
950    /// Kill the process, and return all its remaining standard output and standard error output.
951    ///
952    /// If `ignore_exited` is `true`, log "can't kill an exited process" errors,
953    /// rather than returning them.
954    ///
955    /// Returns `Ok(output)`, or an error if termination, reaping, or draining fails.
956    /// Exit and draining share a one-second cleanup grace, independent of the observation deadline.
957    pub fn kill_and_return_output(&mut self, ignore_exited: bool) -> Result<String> {
958        self.apply_failure_regexes_to_outputs();
959        let deadline = Instant::now() + CHILD_CLEANUP_TIMEOUT;
960        let kill_result = self.kill(ignore_exited);
961        self.start_output_drain(Some(deadline));
962        let cleanup_result = kill_result.and_then(|()| {
963            if let Some(child) = self.child.as_mut() {
964                reap_before_deadline(child, deadline).wrap_err("reaping test child")?;
965            }
966            Ok(())
967        });
968        let (stdout, stderr, read_error) = self.finish_output_drain();
969        let error = match (cleanup_result, read_error) {
970            (Err(cause), Some(error)) => Some(cause.wrap_err(error)),
971            (Err(cause), None) => Some(cause),
972            (Ok(()), error) => error,
973        };
974        if let Some(error) = error {
975            return Err(error)
976                .section(
977                    String::from_utf8_lossy(&stdout)
978                        .into_owned()
979                        .header("Unread Stdout:"),
980                )
981                .section(
982                    String::from_utf8_lossy(&stderr)
983                        .into_owned()
984                        .header("Unread Stderr:"),
985                );
986        }
987        Ok(format!(
988            "{}{}",
989            String::from_utf8_lossy(&stdout),
990            String::from_utf8_lossy(&stderr)
991        ))
992    }
993
994    fn start_output_drain(&self, deadline: Option<Instant>) {
995        for output in [&self.stdout, &self.stderr].into_iter().flatten() {
996            output.start_drain(deadline);
997        }
998    }
999
1000    /// Finish supervised drains, cancelling any remaining readers when cleanup expires.
1001    fn finish_output_drain_before(
1002        &mut self,
1003        deadline: Instant,
1004    ) -> (Vec<u8>, Vec<u8>, Option<Report>) {
1005        let timed_out = loop {
1006            let mut pending = false;
1007            for output in [&mut self.stdout, &mut self.stderr].into_iter().flatten() {
1008                if output.drained.is_none()
1009                    && output.poll_drain().is_ok()
1010                    && output.drained.is_none()
1011                {
1012                    pending = true;
1013                }
1014            }
1015            if !pending {
1016                break false;
1017            }
1018            if Instant::now() >= deadline {
1019                for output in [&self.stdout, &self.stderr].into_iter().flatten() {
1020                    let _ = output.cancelled.send(true);
1021                }
1022                break true;
1023            }
1024            thread::sleep(Duration::from_millis(10));
1025        };
1026        let (stdout, stderr, error) = self.finish_output_drain();
1027        let error = if timed_out {
1028            let timeout = std::io::Error::new(
1029                ErrorKind::TimedOut,
1030                "test child cleanup deadline elapsed while draining output",
1031            );
1032            Some(match error {
1033                Some(error) => error.wrap_err(timeout),
1034                None => timeout.into(),
1035            })
1036        } else {
1037            error
1038        };
1039        (stdout, stderr, error)
1040    }
1041
1042    fn finish_output_drain(&mut self) -> (Vec<u8>, Vec<u8>, Option<Report>) {
1043        let mut error = None;
1044        let mut drain = |output: &mut Option<ChildOutput>| {
1045            let Some(mut output) = output.take() else {
1046                return Vec::new();
1047            };
1048            let response = output.finish_drain();
1049            if !self.failure_regexes.is_empty() || !self.ignore_regexes.is_empty() {
1050                for line in String::from_utf8_lossy(&response.bytes).lines() {
1051                    if let Err(failure) = check_failure_regexes(
1052                        Ok(line.to_owned()),
1053                        &self.failure_regexes,
1054                        &self.ignore_regexes,
1055                        &self.cmd,
1056                        self.bypass_test_capture,
1057                    ) {
1058                        error.get_or_insert_with(|| failure.into());
1059                    }
1060                }
1061            }
1062            if let Some(read_error) = response.error {
1063                error.get_or_insert_with(|| read_error.into());
1064            }
1065            response.bytes
1066        };
1067        let stdout = drain(&mut self.stdout);
1068        let stderr = drain(&mut self.stderr);
1069        (stdout, stderr, error)
1070    }
1071
1072    /// Waits until a line of standard output is available, then consumes it.
1073    ///
1074    /// If there is a line, and `write_context` is `Some`, writes the context to the test logs.
1075    /// Always writes the line to the test logs.
1076    ///
1077    /// Returns `true` if a line was available,
1078    /// or `false` if the standard output has finished.
1079    pub fn wait_for_stdout_line<OptS>(&mut self, write_context: OptS) -> bool
1080    where
1081        OptS: Into<Option<String>>,
1082    {
1083        self.apply_failure_regexes_to_outputs();
1084
1085        if let Some(line_result) = self.stdout.as_mut().and_then(|iter| iter.next()) {
1086            let bypass_test_capture = self.bypass_test_capture;
1087
1088            if let Some(write_context) = write_context.into() {
1089                Self::write_to_test_logs(write_context, bypass_test_capture);
1090            }
1091
1092            Self::write_to_test_logs(
1093                line_result
1094                    .context_from(self)
1095                    .expect("failure reading test process logs"),
1096                bypass_test_capture,
1097            );
1098
1099            return true;
1100        }
1101
1102        false
1103    }
1104
1105    /// Waits until a line of standard error is available, then consumes it.
1106    ///
1107    /// If there is a line, and `write_context` is `Some`, writes the context to the test logs.
1108    /// Always writes the line to the test logs.
1109    ///
1110    /// Returns `true` if a line was available,
1111    /// or `false` if the standard error has finished.
1112    pub fn wait_for_stderr_line<OptS>(&mut self, write_context: OptS) -> bool
1113    where
1114        OptS: Into<Option<String>>,
1115    {
1116        self.apply_failure_regexes_to_outputs();
1117
1118        if let Some(line_result) = self.stderr.as_mut().and_then(|iter| iter.next()) {
1119            let bypass_test_capture = self.bypass_test_capture;
1120
1121            if let Some(write_context) = write_context.into() {
1122                Self::write_to_test_logs(write_context, bypass_test_capture);
1123            }
1124
1125            Self::write_to_test_logs(
1126                line_result
1127                    .context_from(self)
1128                    .expect("failure reading test process logs"),
1129                bypass_test_capture,
1130            );
1131
1132            return true;
1133        }
1134
1135        false
1136    }
1137
1138    /// Waits for natural child exit while draining both remaining output streams.
1139    ///
1140    /// The observation deadline bounds a live child, including after earlier log matches.
1141    /// Intentional termination and draining after natural exit use a separate one-second cleanup
1142    /// grace. On observation timeout or reader error the owned group is killed, with reaping and
1143    /// remaining drains bounded by that grace; errors include captured output.
1144    /// Output already consumed by matchers is not included.
1145    #[spandoc::spandoc]
1146    pub fn wait_with_output(mut self) -> Result<TestOutput<T>> {
1147        self.apply_failure_regexes_to_outputs();
1148        let Some(mut child) = self.child.take() else {
1149            return Err(eyre!("test child was already taken")).context_from(self.as_mut());
1150        };
1151        // Match std::process::Child::wait_with_output: a piped-input child needs EOF to exit.
1152        drop(child.stdin.take());
1153        // Drains stay cancellable while this method supervises the observation/cleanup phases.
1154        self.start_output_drain(None);
1155        let cleanup_deadline = self.killed.then(|| Instant::now() + CHILD_CLEANUP_TIMEOUT);
1156        let mut status = loop {
1157            let read_error = [&mut self.stdout, &mut self.stderr]
1158                .into_iter()
1159                .flatten()
1160                .find_map(|output| output.poll_drain().err());
1161            if let Some(error) = read_error {
1162                break Err(Report::from(error));
1163            }
1164            match self.process_group.try_wait(&mut child) {
1165                Ok(Some(status)) => break Ok(status),
1166                Err(error) => break Err(Report::from(error)),
1167                Ok(None)
1168                    if cleanup_deadline
1169                        .or(self.deadline)
1170                        .is_some_and(|deadline| Instant::now() >= deadline) =>
1171                {
1172                    break Err(eyre!("test child process deadline elapsed"));
1173                }
1174                Ok(None) => thread::sleep(Duration::from_millis(10)),
1175            }
1176        };
1177        let cleanup_deadline =
1178            cleanup_deadline.unwrap_or_else(|| Instant::now() + CHILD_CLEANUP_TIMEOUT);
1179        if status.is_err() {
1180            // Retire group ownership before reaping; never signal a reusable saved PID.
1181            let cleanup = self
1182                .process_group
1183                .kill(&mut child)
1184                .and_then(|()| reap_before_deadline(&mut child, cleanup_deadline).map(|_| ()));
1185            if let Err(error) = cleanup {
1186                status = status.map_err(|cause| cause.wrap_err(error));
1187            }
1188        }
1189        let (stdout, stderr, read_error) = self.finish_output_drain_before(cleanup_deadline);
1190        let status = match status {
1191            Ok(status) => status,
1192            Err(error) => {
1193                let error = match read_error {
1194                    Some(read_error) => error.wrap_err(read_error),
1195                    None => error,
1196                };
1197                return Err(error
1198                    .section(self.cmd.clone().header("Command:"))
1199                    .section(
1200                        String::from_utf8_lossy(&stdout)
1201                            .into_owned()
1202                            .header("Stdout:"),
1203                    )
1204                    .section(
1205                        String::from_utf8_lossy(&stderr)
1206                            .into_owned()
1207                            .header("Stderr:"),
1208                    ));
1209            }
1210        };
1211        let output = Output {
1212            status,
1213            stdout,
1214            stderr,
1215        };
1216        if let Some(error) = read_error {
1217            return Err(error).context_from(&output);
1218        }
1219        Ok(TestOutput {
1220            output,
1221            cmd: self.cmd.clone(),
1222            dir: self.dir.take(),
1223        })
1224    }
1225
1226    /// Returns the current observation deadline, or `None` if no timeout was configured.
1227    ///
1228    /// Intentional termination and post-exit draining have an independent cleanup grace.
1229    pub fn deadline(&self) -> Option<Instant> {
1230        self.deadline
1231    }
1232
1233    /// Sets or resets the observation deadline for output reads and natural process exit.
1234    ///
1235    /// Updates already-created readers immediately. A zero duration expires the observation budget.
1236    /// Intentional termination and post-exit draining retain their independent cleanup grace.
1237    ///
1238    /// # Errors
1239    ///
1240    /// Returns [`ErrorKind::InvalidInput`] if `timeout` cannot be represented by [`Instant`].
1241    /// Overflow never disables the deadline. On error, the consumed child is dropped and cleaned up.
1242    pub fn with_timeout(mut self, timeout: Duration) -> Result<Self> {
1243        let deadline = Instant::now().checked_add(timeout).ok_or_else(|| {
1244            std::io::Error::new(
1245                ErrorKind::InvalidInput,
1246                "test child timeout exceeds Instant range",
1247            )
1248        })?;
1249        self.timeout = Some(timeout);
1250        self.deadline = Some(deadline);
1251        for output in [&mut self.stdout, &mut self.stderr].into_iter().flatten() {
1252            output.deadline = Some(deadline);
1253        }
1254
1255        Ok(self)
1256    }
1257
1258    /// Configures this test runner to forward stdout and stderr to the true stdout,
1259    /// rather than the fakestdout used by cargo tests.
1260    pub fn bypass_test_capture(mut self, cond: bool) -> Self {
1261        self.bypass_test_capture = cond;
1262        self
1263    }
1264
1265    /// Checks each line of the child's stdout against any regex in `success_regex`,
1266    /// and returns the first matching line. Prints all stdout lines.
1267    ///
1268    /// Kills the child on error, or after the configured timeout has elapsed.
1269    /// See [`Self::expect_line_matching_regex_set`] for details.
1270    //
1271    // TODO: these methods could block if stderr is full and stdout is waiting for stderr to be read
1272    #[instrument(skip(self))]
1273    #[allow(clippy::unwrap_in_result)]
1274    pub fn expect_stdout_line_matches<R>(&mut self, success_regex: R) -> Result<String>
1275    where
1276        R: ToRegexSet + Debug,
1277    {
1278        self.apply_failure_regexes_to_outputs();
1279
1280        let mut lines = self
1281            .stdout
1282            .take()
1283            .expect("child must capture stdout to call expect_stdout_line_matches, and it can't be called again after an error");
1284
1285        match self.expect_line_matching_regex_set(&mut lines, success_regex, "stdout", true) {
1286            Ok(line) => {
1287                // Replace the log lines for the next check
1288                self.stdout = Some(lines);
1289                Ok(line)
1290            }
1291            Err(report) => {
1292                // Read all the log lines for error context
1293                self.stdout = Some(lines);
1294                Err(report).context_from(self)
1295            }
1296        }
1297    }
1298
1299    /// Checks each line of the child's stderr against any regex in `success_regex`,
1300    /// and returns the first matching line. Prints all stderr lines to stdout.
1301    ///
1302    /// Kills the child on error, or after the configured timeout has elapsed.
1303    /// See [`Self::expect_line_matching_regex_set`] for details.
1304    #[instrument(skip(self))]
1305    #[allow(clippy::unwrap_in_result)]
1306    pub fn expect_stderr_line_matches<R>(&mut self, success_regex: R) -> Result<String>
1307    where
1308        R: ToRegexSet + Debug,
1309    {
1310        self.apply_failure_regexes_to_outputs();
1311
1312        let mut lines = self
1313            .stderr
1314            .take()
1315            .expect("child must capture stderr to call expect_stderr_line_matches, and it can't be called again after an error");
1316
1317        match self.expect_line_matching_regex_set(&mut lines, success_regex, "stderr", true) {
1318            Ok(line) => {
1319                // Replace the log lines for the next check
1320                self.stderr = Some(lines);
1321                Ok(line)
1322            }
1323            Err(report) => {
1324                // Read all the log lines for error context
1325                self.stderr = Some(lines);
1326                Err(report).context_from(self)
1327            }
1328        }
1329    }
1330
1331    /// Checks each line of the child's stdout, until it finds every regex in `unordered_regexes`,
1332    /// and returns all lines matched by any regex, until each regex has been matched at least once.
1333    /// If the output finishes or the command times out before all regexes are matched, returns an error with
1334    /// a list of unmatched regexes. Prints all stdout lines.
1335    ///
1336    /// Kills the child on error, or after the configured timeout has elapsed.
1337    /// See [`Self::expect_line_matching_regex_set`] for details.
1338    //
1339    // TODO: these methods could block if stderr is full and stdout is waiting for stderr to be read
1340    #[instrument(skip(self))]
1341    #[allow(clippy::unwrap_in_result)]
1342    pub fn expect_stdout_line_matches_all_unordered<RegexList>(
1343        &mut self,
1344        unordered_regexes: RegexList,
1345    ) -> Result<Vec<String>>
1346    where
1347        RegexList: IntoIterator + Debug,
1348        RegexList::Item: ToRegexSet,
1349    {
1350        let regex_list = unordered_regexes.collect_regex_set()?;
1351
1352        let mut unmatched_indexes: HashSet<usize> = (0..regex_list.len()).collect();
1353        let mut matched_lines = Vec::new();
1354
1355        while !unmatched_indexes.is_empty() {
1356            let line = self
1357                .expect_stdout_line_matches(regex_list.clone())
1358                .map_err(|err| {
1359                    let unmatched_regexes = regex_list.patterns_for_indexes(&unmatched_indexes);
1360
1361                    err.with_section(|| {
1362                        format!("{unmatched_regexes:#?}").header("Unmatched regexes:")
1363                    })
1364                    .with_section(|| format!("{matched_lines:#?}").header("Matched lines:"))
1365                })?;
1366
1367            let matched_indices: HashSet<usize> = regex_list.matches(&line).iter().collect();
1368            unmatched_indexes = &unmatched_indexes - &matched_indices;
1369
1370            matched_lines.push(line);
1371        }
1372
1373        Ok(matched_lines)
1374    }
1375
1376    /// Checks each line of the child's stderr, until it finds every regex in `unordered_regexes`,
1377    /// and returns all lines matched by any regex, until each regex has been matched at least once.
1378    /// If the output finishes or the command times out before all regexes are matched, returns an error with
1379    /// a list of unmatched regexes. Prints all stderr lines.
1380    ///
1381    /// Kills the child on error, or after the configured timeout has elapsed.
1382    /// See [`Self::expect_line_matching_regex_set`] for details.
1383    //
1384    // TODO: these methods could block if stdout is full and stderr is waiting for stdout to be read
1385    #[instrument(skip(self))]
1386    #[allow(clippy::unwrap_in_result)]
1387    pub fn expect_stderr_line_matches_all_unordered<RegexList>(
1388        &mut self,
1389        unordered_regexes: RegexList,
1390    ) -> Result<Vec<String>>
1391    where
1392        RegexList: IntoIterator + Debug,
1393        RegexList::Item: ToRegexSet,
1394    {
1395        let regex_list = unordered_regexes.collect_regex_set()?;
1396
1397        let mut unmatched_indexes: HashSet<usize> = (0..regex_list.len()).collect();
1398        let mut matched_lines = Vec::new();
1399
1400        while !unmatched_indexes.is_empty() {
1401            let line = self
1402                .expect_stderr_line_matches(regex_list.clone())
1403                .map_err(|err| {
1404                    let unmatched_regexes = regex_list.patterns_for_indexes(&unmatched_indexes);
1405
1406                    err.with_section(|| {
1407                        format!("{unmatched_regexes:#?}").header("Unmatched regexes:")
1408                    })
1409                    .with_section(|| format!("{matched_lines:#?}").header("Matched lines:"))
1410                })?;
1411
1412            let matched_indices: HashSet<usize> = regex_list.matches(&line).iter().collect();
1413            unmatched_indexes = &unmatched_indexes - &matched_indices;
1414
1415            matched_lines.push(line);
1416        }
1417
1418        Ok(matched_lines)
1419    }
1420
1421    /// Checks each line of the child's stdout against `success_regex`,
1422    /// and returns the first matching line. Does not print any output.
1423    ///
1424    /// Kills the child on error, or after the configured timeout has elapsed.
1425    /// See [`Self::expect_line_matching_regex_set`] for details.
1426    #[instrument(skip(self))]
1427    #[allow(clippy::unwrap_in_result)]
1428    pub fn expect_stdout_line_matches_silent<R>(&mut self, success_regex: R) -> Result<String>
1429    where
1430        R: ToRegexSet + Debug,
1431    {
1432        self.apply_failure_regexes_to_outputs();
1433
1434        let mut lines = self
1435            .stdout
1436            .take()
1437            .expect("child must capture stdout to call expect_stdout_line_matches, and it can't be called again after an error");
1438
1439        match self.expect_line_matching_regex_set(&mut lines, success_regex, "stdout", false) {
1440            Ok(line) => {
1441                // Replace the log lines for the next check
1442                self.stdout = Some(lines);
1443                Ok(line)
1444            }
1445            Err(report) => {
1446                // Read all the log lines for error context
1447                self.stdout = Some(lines);
1448                Err(report).context_from(self)
1449            }
1450        }
1451    }
1452
1453    /// Checks each line of the child's stderr against `success_regex`,
1454    /// and returns the first matching line. Does not print any output.
1455    ///
1456    /// Kills the child on error, or after the configured timeout has elapsed.
1457    /// See [`Self::expect_line_matching_regex_set`] for details.
1458    #[instrument(skip(self))]
1459    #[allow(clippy::unwrap_in_result)]
1460    pub fn expect_stderr_line_matches_silent<R>(&mut self, success_regex: R) -> Result<String>
1461    where
1462        R: ToRegexSet + Debug,
1463    {
1464        self.apply_failure_regexes_to_outputs();
1465
1466        let mut lines = self
1467            .stderr
1468            .take()
1469            .expect("child must capture stderr to call expect_stderr_line_matches, and it can't be called again after an error");
1470
1471        match self.expect_line_matching_regex_set(&mut lines, success_regex, "stderr", false) {
1472            Ok(line) => {
1473                // Replace the log lines for the next check
1474                self.stderr = Some(lines);
1475                Ok(line)
1476            }
1477            Err(report) => {
1478                // Read all the log lines for error context
1479                self.stderr = Some(lines);
1480                Err(report).context_from(self)
1481            }
1482        }
1483    }
1484
1485    /// Checks each line in `lines` against a regex set, and returns Ok if a line matches.
1486    ///
1487    /// [`Self::expect_line_matching_regexes`] wrapper for strings,
1488    /// [`Regex`](regex::Regex)es, and [`RegexSet`]s.
1489    #[allow(clippy::unwrap_in_result)]
1490    pub fn expect_line_matching_regex_set<L, R>(
1491        &mut self,
1492        lines: &mut L,
1493        success_regexes: R,
1494        stream_name: &str,
1495        write_to_logs: bool,
1496    ) -> Result<String>
1497    where
1498        L: Iterator<Item = std::io::Result<String>>,
1499        R: ToRegexSet,
1500    {
1501        let success_regexes = success_regexes
1502            .to_regex_set()
1503            .expect("regexes must be valid");
1504
1505        self.expect_line_matching_regexes(lines, success_regexes, stream_name, write_to_logs)
1506    }
1507
1508    /// Checks each line in `lines` against a regex set, and returns Ok if a line matches.
1509    ///
1510    /// [`Self::expect_line_matching_regexes`] wrapper for regular expression iterators.
1511    #[allow(clippy::unwrap_in_result)]
1512    pub fn expect_line_matching_regex_iter<L, I>(
1513        &mut self,
1514        lines: &mut L,
1515        success_regexes: I,
1516        stream_name: &str,
1517        write_to_logs: bool,
1518    ) -> Result<String>
1519    where
1520        L: Iterator<Item = std::io::Result<String>>,
1521        I: CollectRegexSet,
1522    {
1523        let success_regexes = success_regexes
1524            .collect_regex_set()
1525            .expect("regexes must be valid");
1526
1527        self.expect_line_matching_regexes(lines, success_regexes, stream_name, write_to_logs)
1528    }
1529
1530    /// Checks each line in `lines` against `success_regexes`, and returns Ok if a line
1531    /// matches. Uses `stream_name` as the name for `lines` in error reports.
1532    ///
1533    /// Kills the child on error, or after the configured timeout has elapsed.
1534    ///
1535    /// Harness-owned output iterators interrupt quiet and partial-line reads at the deadline.
1536    /// Arbitrary iterators supplied by callers must provide their own bounded reads.
1537    #[instrument(skip(self, lines))]
1538    #[allow(clippy::unwrap_in_result)]
1539    pub fn expect_line_matching_regexes<L>(
1540        &mut self,
1541        lines: &mut L,
1542        success_regexes: RegexSet,
1543        stream_name: &str,
1544        write_to_logs: bool,
1545    ) -> Result<String>
1546    where
1547        L: Iterator<Item = std::io::Result<String>>,
1548    {
1549        // We don't check `is_running` here,
1550        // because we want to read to the end of the buffered output,
1551        // even if the child process has exited.
1552        while !self.past_deadline() {
1553            let line = if let Some(line) = lines.next() {
1554                line?
1555            } else {
1556                // When the child process closes its output,
1557                // and we've read all of the buffered output,
1558                // stop checking for any more output.
1559                break;
1560            };
1561
1562            if write_to_logs {
1563                // Since we're about to discard this line write it to stdout.
1564                Self::write_to_test_logs(&line, self.bypass_test_capture);
1565            }
1566
1567            if success_regexes.is_match(&line) {
1568                return Ok(line);
1569            }
1570        }
1571
1572        if self.is_running() {
1573            // If the process exits between is_running and kill, we will see
1574            // spurious errors here. So we want to ignore "no such process"
1575            // errors from kill.
1576            self.kill(true)?;
1577        }
1578
1579        let timeout = self
1580            .timeout
1581            .map(|timeout| humantime::format_duration(timeout).to_string())
1582            .unwrap_or_else(|| "unlimited".to_string());
1583
1584        let report = eyre!(
1585            "{stream_name} of command did not log any matches for the given regex,\n\
1586             within the {timeout} command timeout",
1587        )
1588        .with_section(|| format!("{:#?}", success_regexes.patterns()).header("Match Regex:"));
1589
1590        Err(report)
1591    }
1592
1593    /// Write `line` to stdout, so it can be seen in the test logs.
1594    ///
1595    /// Use [bypass_test_capture(true)](TestChild::bypass_test_capture) or
1596    /// `cargo test -- --nocapture` to see this output.
1597    ///
1598    /// May cause weird reordering for stdout / stderr.
1599    /// Uses stdout even if the original lines were from stderr.
1600    #[allow(clippy::print_stdout)]
1601    fn write_to_test_logs<S>(line: S, bypass_test_capture: bool)
1602    where
1603        S: AsRef<str>,
1604    {
1605        write_to_test_logs(line, bypass_test_capture);
1606    }
1607
1608    /// Kill `child`, wait for its output, and use that output as the context for
1609    /// an error report based on `error`.
1610    #[instrument(skip(self, result))]
1611    pub fn kill_on_error<V, E>(mut self, result: Result<V, E>) -> Result<(V, Self), Report>
1612    where
1613        E: Into<Report> + Send + Sync + 'static,
1614    {
1615        let mut error: Report = match result {
1616            Ok(success) => return Ok((success, self)),
1617            Err(error) => error.into(),
1618        };
1619
1620        if self.is_running() {
1621            let kill_res = self.kill(true);
1622            if let Err(kill_err) = kill_res {
1623                error = error.wrap_err(kill_err);
1624            }
1625        }
1626
1627        let output_res = self.wait_with_output();
1628        let error = match output_res {
1629            Err(output_err) => error.wrap_err(output_err),
1630            Ok(output) => error.context_from(&output),
1631        };
1632
1633        Err(error)
1634    }
1635
1636    fn past_deadline(&self) -> bool {
1637        self.deadline
1638            .map(|deadline| Instant::now() > deadline)
1639            .unwrap_or(false)
1640    }
1641
1642    /// Is this process currently running?
1643    ///
1644    /// ## Bugs
1645    ///
1646    /// On Windows and macOS, this function can return `true` for processes that
1647    /// have panicked. See #1781.
1648    ///
1649    /// ## Panics
1650    ///
1651    /// If the child process was already been taken using wait_with_output.
1652    pub fn is_running(&mut self) -> bool {
1653        let child = self.child.as_mut().expect("child has not been taken");
1654        matches!(self.process_group.try_wait(child), Ok(None))
1655    }
1656}
1657
1658#[cfg(windows)]
1659impl<T> std::os::windows::io::AsHandle for TestChild<T> {
1660    fn as_handle(&self) -> std::os::windows::io::BorrowedHandle<'_> {
1661        self.child
1662            .as_ref()
1663            .expect("TestChild owns its process until wait_with_output consumes it")
1664            .as_handle()
1665    }
1666}
1667
1668impl<T> AsRef<TestChild<T>> for TestChild<T> {
1669    fn as_ref(&self) -> &Self {
1670        self
1671    }
1672}
1673
1674impl<T> AsMut<TestChild<T>> for TestChild<T> {
1675    fn as_mut(&mut self) -> &mut Self {
1676        self
1677    }
1678}
1679
1680impl<T> Drop for TestChild<T> {
1681    fn drop(&mut self) {
1682        // Clean up child processes when the test finishes,
1683        // and check for failure logs.
1684        if let Err(error) = self.kill_and_consume_output(true) {
1685            if thread::panicking() {
1686                Self::write_to_test_logs(format!("{error:?}"), self.bypass_test_capture);
1687            } else {
1688                panic!("failure reading test process logs: {error:?}");
1689            }
1690        }
1691    }
1692}
1693
1694/// Test command output logs.
1695// TODO: split this struct into its own module
1696#[derive(Debug)]
1697pub struct TestOutput<T> {
1698    /// The test directory for this test output.
1699    ///
1700    /// Keeps the test dir around from `TestChild`,
1701    /// so it doesn't get deleted during `wait_with_output`.
1702    #[allow(dead_code)]
1703    pub dir: Option<T>,
1704
1705    /// The test command for this test output.
1706    pub cmd: String,
1707
1708    /// The test exit status, standard out, and standard error.
1709    pub output: Output,
1710}
1711
1712impl<T> TestOutput<T> {
1713    pub fn assert_success(self) -> Result<Self> {
1714        if !self.output.status.success() {
1715            Err(eyre!("command exited unsuccessfully")).context_from(&self)?;
1716        }
1717
1718        Ok(self)
1719    }
1720
1721    pub fn assert_failure(self) -> Result<Self> {
1722        if self.output.status.success() {
1723            Err(eyre!("command unexpectedly exited successfully")).context_from(&self)?;
1724        }
1725
1726        Ok(self)
1727    }
1728
1729    /// Checks the output of a command, using a closure to determine if the
1730    /// output is valid.
1731    ///
1732    /// If the closure returns `true`, the check returns `Ok(self)`.
1733    /// If the closure returns `false`, the check returns an error containing
1734    /// `output_name` and `err_msg`, with context from the command.
1735    ///
1736    /// `output` is typically `self.output.stdout` or `self.output.stderr`.
1737    #[instrument(skip(self, output_predicate, output))]
1738    pub fn output_check<P>(
1739        &self,
1740        output_predicate: P,
1741        output: &[u8],
1742        output_name: impl ToString + fmt::Debug,
1743        err_msg: impl ToString + fmt::Debug,
1744    ) -> Result<&Self>
1745    where
1746        P: FnOnce(&str) -> bool,
1747    {
1748        let output = String::from_utf8_lossy(output);
1749
1750        if output_predicate(&output) {
1751            Ok(self)
1752        } else {
1753            Err(eyre!(
1754                "{} of command did not {}",
1755                output_name.to_string(),
1756                err_msg.to_string()
1757            ))
1758            .context_from(self)
1759        }
1760    }
1761
1762    /// Checks each line in the output of a command, using a closure to determine
1763    /// if the line is valid.
1764    ///
1765    /// See [`Self::output_check`] for details.
1766    #[instrument(skip(self, line_predicate, output))]
1767    pub fn any_output_line<P>(
1768        &self,
1769        mut line_predicate: P,
1770        output: &[u8],
1771        output_name: impl ToString + fmt::Debug,
1772        err_msg: impl ToString + fmt::Debug,
1773    ) -> Result<&Self>
1774    where
1775        P: FnMut(&str) -> bool,
1776    {
1777        let output_predicate = |stdout: &str| {
1778            for line in stdout.lines() {
1779                if line_predicate(line) {
1780                    return true;
1781                }
1782            }
1783            false
1784        };
1785
1786        self.output_check(
1787            output_predicate,
1788            output,
1789            output_name,
1790            format!("have any lines that {}", err_msg.to_string()),
1791        )
1792    }
1793
1794    /// Tests if any lines in the output of a command contain `s`.
1795    ///
1796    /// See [`Self::any_output_line`] for details.
1797    #[instrument(skip(self, output))]
1798    pub fn any_output_line_contains(
1799        &self,
1800        s: &str,
1801        output: &[u8],
1802        output_name: impl ToString + fmt::Debug,
1803        err_msg: impl ToString + fmt::Debug,
1804    ) -> Result<&Self> {
1805        self.any_output_line(
1806            |line| line.contains(s),
1807            output,
1808            output_name,
1809            format!("contain {}", err_msg.to_string()),
1810        )
1811        .with_section(|| format!("{s:?}").header("Match String:"))
1812    }
1813
1814    /// Tests if standard output contains `s`.
1815    #[instrument(skip(self))]
1816    pub fn stdout_contains(&self, s: &str) -> Result<&Self> {
1817        self.output_check(
1818            |stdout| stdout.contains(s),
1819            &self.output.stdout,
1820            "stdout",
1821            "contain the given string",
1822        )
1823        .with_section(|| format!("{s:?}").header("Match String:"))
1824    }
1825
1826    /// Tests if standard output matches `regex`.
1827    #[instrument(skip(self))]
1828    #[allow(clippy::unwrap_in_result)]
1829    pub fn stdout_matches<R>(&self, regex: R) -> Result<&Self>
1830    where
1831        R: ToRegexSet + Debug,
1832    {
1833        let re = regex.to_regex_set().expect("regex must be valid");
1834
1835        self.output_check(
1836            |stdout| re.is_match(stdout),
1837            &self.output.stdout,
1838            "stdout",
1839            "matched the given regex",
1840        )
1841        .with_section(|| format!("{regex:?}").header("Match Regex:"))
1842    }
1843
1844    /// Tests if any lines in standard output contain `s`.
1845    #[instrument(skip(self))]
1846    pub fn stdout_line_contains(&self, s: &str) -> Result<&Self> {
1847        self.any_output_line_contains(s, &self.output.stdout, "stdout", "the given string")
1848    }
1849
1850    /// Tests if any lines in standard output match `regex`.
1851    #[instrument(skip(self))]
1852    #[allow(clippy::unwrap_in_result)]
1853    pub fn stdout_line_matches<R>(&self, regex: R) -> Result<&Self>
1854    where
1855        R: ToRegexSet + Debug,
1856    {
1857        let re = regex.to_regex_set().expect("regex must be valid");
1858
1859        self.any_output_line(
1860            |line| re.is_match(line),
1861            &self.output.stdout,
1862            "stdout",
1863            "matched the given regex",
1864        )
1865        .with_section(|| format!("{regex:?}").header("Line Match Regex:"))
1866    }
1867
1868    /// Tests if standard error contains `s`.
1869    #[instrument(skip(self))]
1870    pub fn stderr_contains(&self, s: &str) -> Result<&Self> {
1871        self.output_check(
1872            |stderr| stderr.contains(s),
1873            &self.output.stderr,
1874            "stderr",
1875            "contain the given string",
1876        )
1877        .with_section(|| format!("{s:?}").header("Match String:"))
1878    }
1879
1880    /// Tests if standard error matches `regex`.
1881    #[instrument(skip(self))]
1882    #[allow(clippy::unwrap_in_result)]
1883    pub fn stderr_matches<R>(&self, regex: R) -> Result<&Self>
1884    where
1885        R: ToRegexSet + Debug,
1886    {
1887        let re = regex.to_regex_set().expect("regex must be valid");
1888
1889        self.output_check(
1890            |stderr| re.is_match(stderr),
1891            &self.output.stderr,
1892            "stderr",
1893            "matched the given regex",
1894        )
1895        .with_section(|| format!("{regex:?}").header("Match Regex:"))
1896    }
1897
1898    /// Tests if any lines in standard error contain `s`.
1899    #[instrument(skip(self))]
1900    pub fn stderr_line_contains(&self, s: &str) -> Result<&Self> {
1901        self.any_output_line_contains(s, &self.output.stderr, "stderr", "the given string")
1902    }
1903
1904    /// Tests if any lines in standard error match `regex`.
1905    #[instrument(skip(self))]
1906    #[allow(clippy::unwrap_in_result)]
1907    pub fn stderr_line_matches<R>(&self, regex: R) -> Result<&Self>
1908    where
1909        R: ToRegexSet + Debug,
1910    {
1911        let re = regex.to_regex_set().expect("regex must be valid");
1912
1913        self.any_output_line(
1914            |line| re.is_match(line),
1915            &self.output.stderr,
1916            "stderr",
1917            "matched the given regex",
1918        )
1919        .with_section(|| format!("{regex:?}").header("Line Match Regex:"))
1920    }
1921
1922    /// Returns Ok if the program was killed, Err(Report) if exit was by another
1923    /// reason.
1924    pub fn assert_was_killed(&self) -> Result<()> {
1925        if self.was_killed() {
1926            Ok(())
1927        } else {
1928            Err(eyre!(
1929                "command exited without a kill, but the test expected kill exit"
1930            ))
1931            .context_from(self)?
1932        }
1933    }
1934
1935    /// Returns Ok if the program was not killed, Err(Report) if exit was by
1936    /// another reason.
1937    pub fn assert_was_not_killed(&self) -> Result<()> {
1938        if self.was_killed() {
1939            Err(eyre!(
1940                "command was killed, but the test expected an exit without a kill"
1941            ))
1942            .context_from(self)?
1943        } else {
1944            Ok(())
1945        }
1946    }
1947
1948    #[cfg(not(unix))]
1949    fn was_killed(&self) -> bool {
1950        self.output.status.code() == Some(1)
1951    }
1952
1953    #[cfg(unix)]
1954    fn was_killed(&self) -> bool {
1955        self.output.status.signal() == Some(9)
1956    }
1957
1958    /// Takes the generic `dir` parameter out of this `TestOutput`.
1959    pub fn take_dir(&mut self) -> Option<T> {
1960        self.dir.take()
1961    }
1962}
1963
1964/// Add context to an error report
1965// TODO: split this trait into its own module
1966pub trait ContextFrom<S> {
1967    type Return;
1968
1969    fn context_from(self, source: S) -> Self::Return;
1970}
1971
1972impl<C, T, E> ContextFrom<C> for Result<T, E>
1973where
1974    E: Into<Report>,
1975    Report: ContextFrom<C, Return = Report>,
1976{
1977    type Return = Result<T, Report>;
1978
1979    fn context_from(self, source: C) -> Self::Return {
1980        self.map_err(|e| e.into())
1981            .map_err(|report| report.context_from(source))
1982    }
1983}
1984
1985impl ContextFrom<&TestStatus> for Report {
1986    type Return = Report;
1987
1988    fn context_from(self, source: &TestStatus) -> Self::Return {
1989        let command = || source.cmd.clone().header("Command:");
1990
1991        self.with_section(command).context_from(&source.status)
1992    }
1993}
1994
1995impl<T> ContextFrom<&mut TestChild<T>> for Report {
1996    type Return = Report;
1997
1998    #[allow(clippy::print_stdout)]
1999    fn context_from(mut self, source: &mut TestChild<T>) -> Self::Return {
2000        self = self.section(source.cmd.clone().header("Command:"));
2001
2002        if let Some(child) = &mut source.child {
2003            if let Ok(Some(status)) = source.process_group.try_wait(child) {
2004                self = self.context_from(&status);
2005            }
2006        }
2007
2008        source.apply_failure_regexes_to_outputs();
2009        let deadline = Instant::now() + CHILD_CLEANUP_TIMEOUT;
2010        source.start_output_drain(Some(deadline));
2011        if let Some(child) = source.child.as_mut() {
2012            if let Err(error) = source.process_group.kill(child).and_then(|()| {
2013                source.killed = true;
2014                reap_before_deadline(child, deadline).map(|_| ())
2015            }) {
2016                self = self.wrap_err(error);
2017            }
2018        }
2019        let (stdout, stderr, error) = source.finish_output_drain();
2020        if let Some(error) = error {
2021            self = self.wrap_err(error);
2022        }
2023        self.section(
2024            String::from_utf8_lossy(&stdout)
2025                .into_owned()
2026                .header(format!("{} Unread Stdout:", source.command_path)),
2027        )
2028        .section(
2029            String::from_utf8_lossy(&stderr)
2030                .into_owned()
2031                .header(format!("{} Unread Stderr:", source.command_path)),
2032        )
2033    }
2034}
2035
2036impl<T> ContextFrom<&TestOutput<T>> for Report {
2037    type Return = Report;
2038
2039    fn context_from(self, source: &TestOutput<T>) -> Self::Return {
2040        self.with_section(|| source.cmd.clone().header("Command:"))
2041            .context_from(&source.output)
2042    }
2043}
2044
2045impl ContextFrom<&Output> for Report {
2046    type Return = Report;
2047
2048    fn context_from(self, source: &Output) -> Self::Return {
2049        // TODO: add TestChild.command_path before Stdout and Stderr header names
2050        let stdout = || {
2051            String::from_utf8_lossy(&source.stdout)
2052                .into_owned()
2053                .header("Stdout:")
2054        };
2055        let stderr = || {
2056            String::from_utf8_lossy(&source.stderr)
2057                .into_owned()
2058                .header("Stderr:")
2059        };
2060
2061        self.context_from(&source.status)
2062            .with_section(stdout)
2063            .with_section(stderr)
2064    }
2065}
2066
2067impl ContextFrom<&ExitStatus> for Report {
2068    type Return = Report;
2069
2070    fn context_from(self, source: &ExitStatus) -> Self::Return {
2071        let how = if source.success() {
2072            "successfully"
2073        } else {
2074            "unsuccessfully"
2075        };
2076
2077        if let Some(code) = source.code() {
2078            return self.with_section(|| {
2079                format!("command exited {how} with status code {code}").header("Exit Status:")
2080            });
2081        }
2082
2083        #[cfg(unix)]
2084        if let Some(signal) = source.signal() {
2085            self.with_section(|| {
2086                format!("command terminated {how} by signal {signal}").header("Exit Status:")
2087            })
2088        } else {
2089            unreachable!("on unix all processes either terminate via signal or with an exit code");
2090        }
2091
2092        #[cfg(not(unix))]
2093        self.with_section(|| {
2094            format!("command exited {} without a status code or signal", how).header("Exit Status:")
2095        })
2096    }
2097}