-
Notifications
You must be signed in to change notification settings - Fork 107
/
command.rs
1619 lines (1400 loc) · 52.7 KB
/
command.rs
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
//! Launching test commands for Zebra integration and acceptance tests.
use std::{
collections::HashSet,
convert::Infallible as NoDir,
fmt::{self, Debug, Write as _},
io::{BufRead, BufReader, ErrorKind, Read, Write as _},
path::Path,
process::{Child, Command, ExitStatus, Output, Stdio},
time::{Duration, Instant},
};
#[cfg(unix)]
use std::os::unix::process::ExitStatusExt;
use color_eyre::{
eyre::{eyre, Context, Report, Result},
Help, SectionExt,
};
use regex::RegexSet;
use tracing::instrument;
#[macro_use]
mod arguments;
pub mod to_regex;
pub use self::arguments::Arguments;
use self::to_regex::{CollectRegexSet, RegexSetExt, ToRegexSet};
/// A super-trait for [`Iterator`] + [`Debug`].
pub trait IteratorDebug: Iterator + Debug {}
impl<T> IteratorDebug for T where T: Iterator + Debug {}
/// Runs a command
pub fn test_cmd(command_path: &str, tempdir: &Path) -> Result<Command> {
let mut cmd = Command::new(command_path);
cmd.current_dir(tempdir);
Ok(cmd)
}
// TODO: split these extensions into their own module
/// Wrappers for `Command` methods to integrate with [`zebra_test`](crate).
pub trait CommandExt {
/// wrapper for `status` fn on `Command` that constructs informative error
/// reports
fn status2(&mut self) -> Result<TestStatus, Report>;
/// wrapper for `output` fn on `Command` that constructs informative error
/// reports
fn output2(&mut self) -> Result<TestOutput<NoDir>, Report>;
/// wrapper for `spawn` fn on `Command` that constructs informative error
/// reports using the original `command_path`
fn spawn2<T>(&mut self, dir: T, command_path: impl ToString) -> Result<TestChild<T>, Report>;
}
impl CommandExt for Command {
/// wrapper for `status` fn on `Command` that constructs informative error
/// reports
fn status2(&mut self) -> Result<TestStatus, Report> {
let cmd = format!("{self:?}");
let status = self.status();
let command = || cmd.clone().header("Command:");
let status = status
.wrap_err("failed to execute process")
.with_section(command)?;
Ok(TestStatus { cmd, status })
}
/// wrapper for `output` fn on `Command` that constructs informative error
/// reports
fn output2(&mut self) -> Result<TestOutput<NoDir>, Report> {
let output = self.output();
let output = output
.wrap_err("failed to execute process")
.with_section(|| format!("{self:?}").header("Command:"))?;
Ok(TestOutput {
dir: None,
output,
cmd: format!("{self:?}"),
})
}
/// wrapper for `spawn` fn on `Command` that constructs informative error
/// reports using the original `command_path`
fn spawn2<T>(&mut self, dir: T, command_path: impl ToString) -> Result<TestChild<T>, Report> {
let command_and_args = format!("{self:?}");
let child = self.spawn();
let child = child
.wrap_err("failed to execute process")
.with_section(|| command_and_args.clone().header("Command:"))?;
Ok(TestChild {
dir: Some(dir),
cmd: command_and_args,
command_path: command_path.to_string(),
child: Some(child),
stdout: None,
stderr: None,
failure_regexes: RegexSet::empty(),
ignore_regexes: RegexSet::empty(),
deadline: None,
timeout: None,
bypass_test_capture: false,
})
}
}
/// Extension trait for methods on `tempdir::TempDir` for using it as a test
/// directory with an arbitrary command.
///
/// This trait is separate from `ZebradTestDirExt`, so that we can test
/// `zebra_test::command` without running `zebrad`.
pub trait TestDirExt
where
Self: AsRef<Path> + Sized,
{
/// Spawn `cmd` with `args` as a child process in this test directory,
/// potentially taking ownership of the tempdir for the duration of the
/// child process.
fn spawn_child_with_command(self, cmd: &str, args: Arguments) -> Result<TestChild<Self>>;
}
impl<T> TestDirExt for T
where
Self: AsRef<Path> + Sized,
{
#[allow(clippy::unwrap_in_result)]
fn spawn_child_with_command(
self,
command_path: &str,
args: Arguments,
) -> Result<TestChild<Self>> {
let mut cmd = test_cmd(command_path, self.as_ref())?;
Ok(cmd
.args(args.into_arguments())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn2(self, command_path)
.unwrap())
}
}
/// Test command exit status information.
#[derive(Debug)]
pub struct TestStatus {
/// The original command string.
pub cmd: String,
/// The exit status of the command.
pub status: ExitStatus,
}
impl TestStatus {
pub fn assert_success(self) -> Result<Self> {
if !self.status.success() {
Err(eyre!("command exited unsuccessfully")).context_from(&self)?;
}
Ok(self)
}
pub fn assert_failure(self) -> Result<Self> {
if self.status.success() {
Err(eyre!("command unexpectedly exited successfully")).context_from(&self)?;
}
Ok(self)
}
}
/// A test command child process.
// TODO: split this struct into its own module (or multiple modules)
#[derive(Debug)]
pub struct TestChild<T> {
/// The working directory of the command.
///
/// `None` when the command has been waited on,
/// and its output has been taken.
pub dir: Option<T>,
/// The full command string, including arguments and working directory.
pub cmd: String,
/// The path of the command, as passed to spawn2().
pub command_path: String,
/// The child process itself.
///
/// `None` when the command has been waited on,
/// and its output has been taken.
pub child: Option<Child>,
/// The standard output stream of the child process.
///
/// TODO: replace with `Option<ChildOutput { stdout, stderr }>.
pub stdout: Option<Box<dyn IteratorDebug<Item = std::io::Result<String>> + Send>>,
/// The standard error stream of the child process.
pub stderr: Option<Box<dyn IteratorDebug<Item = std::io::Result<String>> + Send>>,
/// Command outputs which indicate test failure.
///
/// This list of regexes is matches against `stdout` or `stderr`,
/// in every method that reads command output.
///
/// If any line matches any failure regex, the test fails.
failure_regexes: RegexSet,
/// Command outputs which are ignored when checking for test failure.
/// These regexes override `failure_regexes`.
///
/// This list of regexes is matches against `stdout` or `stderr`,
/// in every method that reads command output.
///
/// If a line matches any ignore regex, the failure regex check is skipped for that line.
ignore_regexes: RegexSet,
/// The deadline for this command to finish.
///
/// Only checked when the command outputs each new line (#1140).
pub deadline: Option<Instant>,
/// The timeout for this command to finish.
///
/// Only used for debugging output.
pub timeout: Option<Duration>,
/// If true, write child output directly to standard output,
/// bypassing the Rust test harness output capture.
bypass_test_capture: bool,
}
/// Checks command output log `line` from `cmd` against a `failure_regexes` regex set,
/// and returns an error if any regex matches. The line is skipped if it matches `ignore_regexes`.
///
/// Passes through errors from the underlying reader.
pub fn check_failure_regexes(
line: std::io::Result<String>,
failure_regexes: &RegexSet,
ignore_regexes: &RegexSet,
cmd: &str,
bypass_test_capture: bool,
) -> std::io::Result<String> {
let line = line?;
// Check if the line matches any patterns
let ignore_matches = ignore_regexes.matches(&line);
let ignore_matches: Vec<&str> = ignore_matches
.iter()
.map(|index| ignore_regexes.patterns()[index].as_str())
.collect();
let failure_matches = failure_regexes.matches(&line);
let failure_matches: Vec<&str> = failure_matches
.iter()
.map(|index| failure_regexes.patterns()[index].as_str())
.collect();
// If we match an ignore pattern, ignore any failure matches
if !ignore_matches.is_empty() {
let ignore_matches = ignore_matches.join(",");
let ignore_msg = if failure_matches.is_empty() {
format!("Log matched ignore regexes: {ignore_matches:?}, but no failure regexes",)
} else {
let failure_matches = failure_matches.join(",");
format!(
"Ignoring failure regexes: {failure_matches:?}, because log matched ignore regexes: {ignore_matches:?}",
)
};
write_to_test_logs(ignore_msg, bypass_test_capture);
return Ok(line);
}
// If there were no failures, pass the log line through
if failure_matches.is_empty() {
return Ok(line);
}
// Otherwise, if the process logged a failure message, return an error
let error = std::io::Error::new(
ErrorKind::Other,
format!(
"test command:\n\
{cmd}\n\n\
Logged a failure message:\n\
{line}\n\n\
Matching failure regex: \
{failure_matches:#?}\n\n\
All Failure regexes: \
{:#?}\n",
failure_regexes.patterns(),
),
);
Err(error)
}
/// Write `line` to stdout, so it can be seen in the test logs.
///
/// Set `bypass_test_capture` to `true` or
/// use `cargo test -- --nocapture` to see this output.
///
/// May cause weird reordering for stdout / stderr.
/// Uses stdout even if the original lines were from stderr.
#[allow(clippy::print_stdout)]
fn write_to_test_logs<S>(line: S, bypass_test_capture: bool)
where
S: AsRef<str>,
{
let line = line.as_ref();
if bypass_test_capture {
// Send lines directly to the terminal (or process stdout file redirect).
#[allow(clippy::explicit_write)]
writeln!(std::io::stdout(), "{line}").unwrap();
} else {
// If the test fails, the test runner captures and displays this output.
// To show this output unconditionally, use `cargo test -- --nocapture`.
println!("{line}");
}
// Some OSes require a flush to send all output to the terminal.
let _ = std::io::stdout().lock().flush();
}
/// A [`CollectRegexSet`] iterator that never matches anything.
///
/// Used to work around type inference issues in [`TestChild::with_failure_regex_iter`].
pub const NO_MATCHES_REGEX_ITER: &[&str] = &[];
impl<T> TestChild<T> {
/// Sets up command output so each line is checked against a failure regex set,
/// unless it matches any of the ignore regexes.
///
/// The failure regexes are ignored by `wait_with_output`.
///
/// To never match any log lines, use `RegexSet::empty()`.
///
/// This method is a [`TestChild::with_failure_regexes`] wrapper for
/// strings, `Regex`es, and [`RegexSet`]s.
///
/// # Panics
///
/// - adds a panic to any method that reads output,
/// if any stdout or stderr lines match any failure regex
pub fn with_failure_regex_set<F, X>(self, failure_regexes: F, ignore_regexes: X) -> Self
where
F: ToRegexSet,
X: ToRegexSet,
{
let failure_regexes = failure_regexes
.to_regex_set()
.expect("failure regexes must be valid");
let ignore_regexes = ignore_regexes
.to_regex_set()
.expect("ignore regexes must be valid");
self.with_failure_regexes(failure_regexes, ignore_regexes)
}
/// Sets up command output so each line is checked against a failure regex set,
/// unless it matches any of the ignore regexes.
///
/// The failure regexes are ignored by `wait_with_output`.
///
/// To never match any log lines, use [`NO_MATCHES_REGEX_ITER`].
///
/// This method is a [`TestChild::with_failure_regexes`] wrapper for
/// regular expression iterators.
///
/// # Panics
///
/// - adds a panic to any method that reads output,
/// if any stdout or stderr lines match any failure regex
pub fn with_failure_regex_iter<F, X>(self, failure_regexes: F, ignore_regexes: X) -> Self
where
F: CollectRegexSet,
X: CollectRegexSet,
{
let failure_regexes = failure_regexes
.collect_regex_set()
.expect("failure regexes must be valid");
let ignore_regexes = ignore_regexes
.collect_regex_set()
.expect("ignore regexes must be valid");
self.with_failure_regexes(failure_regexes, ignore_regexes)
}
/// Sets up command output so each line is checked against a failure regex set,
/// unless it matches any of the ignore regexes.
///
/// The failure regexes are ignored by `wait_with_output`.
///
/// # Panics
///
/// - adds a panic to any method that reads output,
/// if any stdout or stderr lines match any failure regex
pub fn with_failure_regexes(
mut self,
failure_regexes: RegexSet,
ignore_regexes: impl Into<Option<RegexSet>>,
) -> Self {
self.failure_regexes = failure_regexes;
self.ignore_regexes = ignore_regexes.into().unwrap_or_else(RegexSet::empty);
self.apply_failure_regexes_to_outputs();
self
}
/// Applies the failure and ignore regex sets to command output.
///
/// The failure regexes are ignored by `wait_with_output`.
///
/// # Panics
///
/// - adds a panic to any method that reads output,
/// if any stdout or stderr lines match any failure regex
pub fn apply_failure_regexes_to_outputs(&mut self) {
if self.stdout.is_none() {
self.stdout = self
.child
.as_mut()
.and_then(|child| child.stdout.take())
.map(|output| self.map_into_string_lines(output))
}
if self.stderr.is_none() {
self.stderr = self
.child
.as_mut()
.and_then(|child| child.stderr.take())
.map(|output| self.map_into_string_lines(output))
}
}
/// Maps a reader into a string line iterator,
/// and applies the failure and ignore regex sets to it.
fn map_into_string_lines<R>(
&self,
reader: R,
) -> Box<dyn IteratorDebug<Item = std::io::Result<String>> + Send>
where
R: Read + Debug + Send + 'static,
{
let failure_regexes = self.failure_regexes.clone();
let ignore_regexes = self.ignore_regexes.clone();
let cmd = self.cmd.clone();
let bypass_test_capture = self.bypass_test_capture;
let reader = BufReader::new(reader);
let lines = BufRead::lines(reader).map(move |line| {
check_failure_regexes(
line,
&failure_regexes,
&ignore_regexes,
&cmd,
bypass_test_capture,
)
});
Box::new(lines) as _
}
/// Kill the child process.
///
/// If `ignore_exited` is `true`, log "can't kill an exited process" errors,
/// rather than returning them.
///
/// Returns the result of the kill.
///
/// ## BUGS
///
/// On Windows (and possibly macOS), this function can return `Ok` for
/// processes that have panicked. See #1781.
#[spandoc::spandoc]
pub fn kill(&mut self, ignore_exited: bool) -> Result<()> {
let child = match self.child.as_mut() {
Some(child) => child,
None if ignore_exited => {
Self::write_to_test_logs(
"test child was already taken\n\
ignoring kill because ignore_exited is true",
self.bypass_test_capture,
);
return Ok(());
}
None => {
return Err(eyre!(
"test child was already taken\n\
call kill() once for each child process, or set ignore_exited to true"
))
.context_from(self.as_mut())
}
};
/// SPANDOC: Killing child process
let kill_result = child.kill().or_else(|error| {
if ignore_exited && error.kind() == ErrorKind::InvalidInput {
Ok(())
} else {
Err(error)
}
});
kill_result.context_from(self.as_mut())?;
Ok(())
}
/// Kill the process, and consume all its remaining output.
///
/// If `ignore_exited` is `true`, log "can't kill an exited process" errors,
/// rather than returning them.
///
/// Returns the result of the kill.
pub fn kill_and_consume_output(&mut self, ignore_exited: bool) -> Result<()> {
self.apply_failure_regexes_to_outputs();
// Prevent a hang when consuming output,
// by making sure the child's output actually finishes.
let kill_result = self.kill(ignore_exited);
// Read unread child output.
//
// This checks for failure logs, and prevents some test hangs and deadlocks.
//
// TODO: this could block if stderr is full and stdout is waiting for stderr to be read.
if self.stdout.is_some() {
let wrote_lines =
self.wait_for_stdout_line(format!("\n{} Child Stdout:", self.command_path));
while self.wait_for_stdout_line(None) {}
if wrote_lines {
// Write an empty line, to make output more readable
Self::write_to_test_logs("", self.bypass_test_capture);
}
}
if self.stderr.is_some() {
let wrote_lines =
self.wait_for_stderr_line(format!("\n{} Child Stderr:", self.command_path));
while self.wait_for_stderr_line(None) {}
if wrote_lines {
Self::write_to_test_logs("", self.bypass_test_capture);
}
}
kill_result
}
/// Kill the process, and return all its remaining standard output and standard error output.
///
/// If `ignore_exited` is `true`, log "can't kill an exited process" errors,
/// rather than returning them.
///
/// Returns `Ok(output)`, or an error if the kill failed.
pub fn kill_and_return_output(&mut self, ignore_exited: bool) -> Result<String> {
self.apply_failure_regexes_to_outputs();
// Prevent a hang when consuming output,
// by making sure the child's output actually finishes.
let kill_result = self.kill(ignore_exited);
// Read unread child output.
let mut stdout_buf = String::new();
let mut stderr_buf = String::new();
// This also checks for failure logs, and prevents some test hangs and deadlocks.
loop {
let mut remaining_output = false;
if let Some(stdout) = self.stdout.as_mut() {
if let Some(line) =
Self::wait_and_return_output_line(stdout, self.bypass_test_capture)
{
stdout_buf.push_str(&line);
remaining_output = true;
}
}
if let Some(stderr) = self.stderr.as_mut() {
if let Some(line) =
Self::wait_and_return_output_line(stderr, self.bypass_test_capture)
{
stderr_buf.push_str(&line);
remaining_output = true;
}
}
if !remaining_output {
break;
}
}
let mut output = stdout_buf;
output.push_str(&stderr_buf);
kill_result.map(|()| output)
}
/// Waits until a line of standard output is available, then consumes it.
///
/// If there is a line, and `write_context` is `Some`, writes the context to the test logs.
/// Always writes the line to the test logs.
///
/// Returns `true` if a line was available,
/// or `false` if the standard output has finished.
pub fn wait_for_stdout_line<OptS>(&mut self, write_context: OptS) -> bool
where
OptS: Into<Option<String>>,
{
self.apply_failure_regexes_to_outputs();
if let Some(line_result) = self.stdout.as_mut().and_then(|iter| iter.next()) {
let bypass_test_capture = self.bypass_test_capture;
if let Some(write_context) = write_context.into() {
Self::write_to_test_logs(write_context, bypass_test_capture);
}
Self::write_to_test_logs(
line_result
.context_from(self)
.expect("failure reading test process logs"),
bypass_test_capture,
);
return true;
}
false
}
/// Waits until a line of standard error is available, then consumes it.
///
/// If there is a line, and `write_context` is `Some`, writes the context to the test logs.
/// Always writes the line to the test logs.
///
/// Returns `true` if a line was available,
/// or `false` if the standard error has finished.
pub fn wait_for_stderr_line<OptS>(&mut self, write_context: OptS) -> bool
where
OptS: Into<Option<String>>,
{
self.apply_failure_regexes_to_outputs();
if let Some(line_result) = self.stderr.as_mut().and_then(|iter| iter.next()) {
let bypass_test_capture = self.bypass_test_capture;
if let Some(write_context) = write_context.into() {
Self::write_to_test_logs(write_context, bypass_test_capture);
}
Self::write_to_test_logs(
line_result
.context_from(self)
.expect("failure reading test process logs"),
bypass_test_capture,
);
return true;
}
false
}
/// Waits until a line of `output` is available, then returns it.
///
/// If there is a line, and `write_context` is `Some`, writes the context to the test logs.
/// Always writes the line to the test logs.
///
/// Returns `true` if a line was available,
/// or `false` if the standard output has finished.
#[allow(clippy::unwrap_in_result)]
fn wait_and_return_output_line(
mut output: impl Iterator<Item = std::io::Result<String>>,
bypass_test_capture: bool,
) -> Option<String> {
if let Some(line_result) = output.next() {
let line_result = line_result.expect("failure reading test process logs");
Self::write_to_test_logs(&line_result, bypass_test_capture);
return Some(line_result);
}
None
}
/// Waits for the child process to exit, then returns its output.
///
/// # Correctness
///
/// The other test child output methods take one or both outputs,
/// making them unavailable to this method.
///
/// Ignores any configured timeouts.
///
/// Returns an error if the child has already been taken.
/// TODO: return an error if both outputs have already been taken.
#[spandoc::spandoc]
pub fn wait_with_output(mut self) -> Result<TestOutput<T>> {
let child = match self.child.take() {
Some(child) => child,
// Also checks the taken child output for failure regexes,
// either in `context_from`, or on drop.
None => {
return Err(eyre!(
"test child was already taken\n\
wait_with_output can only be called once for each child process",
))
.context_from(self.as_mut())
}
};
// TODO: fix the usage in the zebrad acceptance tests, or fix the bugs in TestChild,
// then re-enable this check
/*
if child.stdout.is_none() && child.stderr.is_none() {
// Also checks the taken child output for failure regexes,
// either in `context_from`, or on drop.
return Err(eyre!(
"child stdout and stderr were already taken.\n\
Hint: choose one of these alternatives:\n\
1. use wait_with_output once on each child process, or\n\
2. replace wait_with_output with the other TestChild output methods"
))
.context_from(self.as_mut());
};
*/
/// SPANDOC: waiting for command to exit
let output = child.wait_with_output().with_section({
let cmd = self.cmd.clone();
|| cmd.header("Command:")
})?;
Ok(TestOutput {
output,
cmd: self.cmd.clone(),
dir: self.dir.take(),
})
}
/// Set a timeout for `expect_stdout_line_matches` or `expect_stderr_line_matches`.
///
/// Does not apply to `wait_with_output`.
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self.deadline = Some(Instant::now() + timeout);
self
}
/// Configures this test runner to forward stdout and stderr to the true stdout,
/// rather than the fakestdout used by cargo tests.
pub fn bypass_test_capture(mut self, cond: bool) -> Self {
self.bypass_test_capture = cond;
self
}
/// Checks each line of the child's stdout against any regex in `success_regex`,
/// and returns the first matching line. Prints all stdout lines.
///
/// Kills the child on error, or after the configured timeout has elapsed.
/// See [`Self::expect_line_matching_regex_set`] for details.
//
// TODO: these methods could block if stderr is full and stdout is waiting for stderr to be read
#[instrument(skip(self))]
#[allow(clippy::unwrap_in_result)]
pub fn expect_stdout_line_matches<R>(&mut self, success_regex: R) -> Result<String>
where
R: ToRegexSet + Debug,
{
self.apply_failure_regexes_to_outputs();
let mut lines = self
.stdout
.take()
.expect("child must capture stdout to call expect_stdout_line_matches, and it can't be called again after an error");
match self.expect_line_matching_regex_set(&mut lines, success_regex, "stdout", true) {
Ok(line) => {
// Replace the log lines for the next check
self.stdout = Some(lines);
Ok(line)
}
Err(report) => {
// Read all the log lines for error context
self.stdout = Some(lines);
Err(report).context_from(self)
}
}
}
/// Checks each line of the child's stderr against any regex in `success_regex`,
/// and returns the first matching line. Prints all stderr lines to stdout.
///
/// Kills the child on error, or after the configured timeout has elapsed.
/// See [`Self::expect_line_matching_regex_set`] for details.
#[instrument(skip(self))]
#[allow(clippy::unwrap_in_result)]
pub fn expect_stderr_line_matches<R>(&mut self, success_regex: R) -> Result<String>
where
R: ToRegexSet + Debug,
{
self.apply_failure_regexes_to_outputs();
let mut lines = self
.stderr
.take()
.expect("child must capture stderr to call expect_stderr_line_matches, and it can't be called again after an error");
match self.expect_line_matching_regex_set(&mut lines, success_regex, "stderr", true) {
Ok(line) => {
// Replace the log lines for the next check
self.stderr = Some(lines);
Ok(line)
}
Err(report) => {
// Read all the log lines for error context
self.stderr = Some(lines);
Err(report).context_from(self)
}
}
}
/// Checks each line of the child's stdout, until it finds every regex in `unordered_regexes`,
/// and returns all lines matched by any regex, until each regex has been matched at least once.
/// If the output finishes or the command times out before all regexes are matched, returns an error with
/// a list of unmatched regexes. Prints all stdout lines.
///
/// Kills the child on error, or after the configured timeout has elapsed.
/// See [`Self::expect_line_matching_regex_set`] for details.
//
// TODO: these methods could block if stderr is full and stdout is waiting for stderr to be read
#[instrument(skip(self))]
#[allow(clippy::unwrap_in_result)]
pub fn expect_stdout_line_matches_all_unordered<RegexList>(
&mut self,
unordered_regexes: RegexList,
) -> Result<Vec<String>>
where
RegexList: IntoIterator + Debug,
RegexList::Item: ToRegexSet,
{
let regex_list = unordered_regexes.collect_regex_set()?;
let mut unmatched_indexes: HashSet<usize> = (0..regex_list.len()).collect();
let mut matched_lines = Vec::new();
while !unmatched_indexes.is_empty() {
let line = self
.expect_stdout_line_matches(regex_list.clone())
.map_err(|err| {
let unmatched_regexes = regex_list.patterns_for_indexes(&unmatched_indexes);
err.with_section(|| {
format!("{unmatched_regexes:#?}").header("Unmatched regexes:")
})
.with_section(|| format!("{matched_lines:#?}").header("Matched lines:"))
})?;
let matched_indices: HashSet<usize> = regex_list.matches(&line).iter().collect();
unmatched_indexes = &unmatched_indexes - &matched_indices;
matched_lines.push(line);
}
Ok(matched_lines)
}
/// Checks each line of the child's stderr, until it finds every regex in `unordered_regexes`,
/// and returns all lines matched by any regex, until each regex has been matched at least once.
/// If the output finishes or the command times out before all regexes are matched, returns an error with
/// a list of unmatched regexes. Prints all stderr lines.
///
/// Kills the child on error, or after the configured timeout has elapsed.
/// See [`Self::expect_line_matching_regex_set`] for details.
//
// TODO: these methods could block if stdout is full and stderr is waiting for stdout to be read
#[instrument(skip(self))]
#[allow(clippy::unwrap_in_result)]
pub fn expect_stderr_line_matches_all_unordered<RegexList>(
&mut self,
unordered_regexes: RegexList,
) -> Result<Vec<String>>
where
RegexList: IntoIterator + Debug,
RegexList::Item: ToRegexSet,
{
let regex_list = unordered_regexes.collect_regex_set()?;
let mut unmatched_indexes: HashSet<usize> = (0..regex_list.len()).collect();
let mut matched_lines = Vec::new();
while !unmatched_indexes.is_empty() {
let line = self
.expect_stderr_line_matches(regex_list.clone())
.map_err(|err| {
let unmatched_regexes = regex_list.patterns_for_indexes(&unmatched_indexes);
err.with_section(|| {
format!("{unmatched_regexes:#?}").header("Unmatched regexes:")
})
.with_section(|| format!("{matched_lines:#?}").header("Matched lines:"))
})?;
let matched_indices: HashSet<usize> = regex_list.matches(&line).iter().collect();
unmatched_indexes = &unmatched_indexes - &matched_indices;
matched_lines.push(line);
}
Ok(matched_lines)
}
/// Checks each line of the child's stdout against `success_regex`,
/// and returns the first matching line. Does not print any output.
///
/// Kills the child on error, or after the configured timeout has elapsed.
/// See [`Self::expect_line_matching_regex_set`] for details.
#[instrument(skip(self))]
#[allow(clippy::unwrap_in_result)]
pub fn expect_stdout_line_matches_silent<R>(&mut self, success_regex: R) -> Result<String>
where
R: ToRegexSet + Debug,
{
self.apply_failure_regexes_to_outputs();
let mut lines = self
.stdout
.take()
.expect("child must capture stdout to call expect_stdout_line_matches, and it can't be called again after an error");
match self.expect_line_matching_regex_set(&mut lines, success_regex, "stdout", false) {
Ok(line) => {
// Replace the log lines for the next check
self.stdout = Some(lines);
Ok(line)
}
Err(report) => {
// Read all the log lines for error context
self.stdout = Some(lines);
Err(report).context_from(self)
}
}
}
/// Checks each line of the child's stderr against `success_regex`,
/// and returns the first matching line. Does not print any output.
///
/// Kills the child on error, or after the configured timeout has elapsed.
/// See [`Self::expect_line_matching_regex_set`] for details.
#[instrument(skip(self))]
#[allow(clippy::unwrap_in_result)]
pub fn expect_stderr_line_matches_silent<R>(&mut self, success_regex: R) -> Result<String>
where
R: ToRegexSet + Debug,
{
self.apply_failure_regexes_to_outputs();
let mut lines = self
.stderr
.take()
.expect("child must capture stderr to call expect_stderr_line_matches, and it can't be called again after an error");
match self.expect_line_matching_regex_set(&mut lines, success_regex, "stderr", false) {
Ok(line) => {
// Replace the log lines for the next check
self.stderr = Some(lines);
Ok(line)
}
Err(report) => {
// Read all the log lines for error context
self.stderr = Some(lines);
Err(report).context_from(self)