-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
util.rs
4009 lines (3601 loc) · 135 KB
/
util.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
// This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//spell-checker: ignore (linux) rlimit prlimit coreutil ggroups uchild uncaptured scmd SHLVL canonicalized openpty
//spell-checker: ignore (linux) winsize xpixel ypixel setrlimit FSIZE SIGBUS SIGSEGV sigbus
#![allow(dead_code)]
#![allow(
clippy::too_many_lines,
clippy::should_panic_without_expect,
clippy::missing_errors_doc
)]
#[cfg(unix)]
use libc::mode_t;
#[cfg(unix)]
use nix::pty::OpenptyResult;
#[cfg(unix)]
use nix::sys;
use pretty_assertions::assert_eq;
#[cfg(unix)]
use rlimit::setrlimit;
#[cfg(feature = "sleep")]
use rstest::rstest;
use std::borrow::Cow;
use std::collections::VecDeque;
#[cfg(not(windows))]
use std::ffi::CString;
use std::ffi::{OsStr, OsString};
use std::fs::{self, hard_link, remove_file, File, OpenOptions};
use std::io::{self, BufWriter, Read, Result, Write};
#[cfg(unix)]
use std::os::fd::OwnedFd;
#[cfg(unix)]
use std::os::unix::fs::{symlink as symlink_dir, symlink as symlink_file, PermissionsExt};
#[cfg(unix)]
use std::os::unix::process::CommandExt;
#[cfg(unix)]
use std::os::unix::process::ExitStatusExt;
#[cfg(windows)]
use std::os::windows::fs::{symlink_dir, symlink_file};
#[cfg(windows)]
use std::path::MAIN_SEPARATOR_STR;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Output, Stdio};
use std::rc::Rc;
use std::sync::mpsc::{self, RecvTimeoutError};
use std::thread::{sleep, JoinHandle};
use std::time::{Duration, Instant};
use std::{env, hint, mem, thread};
use tempfile::{Builder, TempDir};
static TESTS_DIR: &str = "tests";
static FIXTURES_DIR: &str = "fixtures";
static ALREADY_RUN: &str = " you have already run this UCommand, if you want to run \
another command in the same test, use TestScenario::new instead of \
testing();";
static MULTIPLE_STDIN_MEANINGLESS: &str = "Ucommand is designed around a typical use case of: provide args and input stream -> spawn process -> block until completion -> return output streams. For verifying that a particular section of the input stream is what causes a particular behavior, use the Command type directly.";
static NO_STDIN_MEANINGLESS: &str = "Setting this flag has no effect if there is no stdin";
static END_OF_TRANSMISSION_SEQUENCE: &[u8] = b"\n\x04";
pub const TESTS_BINARY: &str = env!("CARGO_BIN_EXE_coreutils");
pub const PATH: &str = env!("PATH");
/// Default environment variables to run the commands with
const DEFAULT_ENV: [(&str, &str); 2] = [("LC_ALL", "C"), ("TZ", "UTC")];
/// Test if the program is running under CI
pub fn is_ci() -> bool {
std::env::var("CI").is_ok_and(|s| s.eq_ignore_ascii_case("true"))
}
/// Read a test scenario fixture, returning its bytes
fn read_scenario_fixture<S: AsRef<OsStr>>(tmpd: &Option<Rc<TempDir>>, file_rel_path: S) -> Vec<u8> {
let tmpdir_path = tmpd.as_ref().unwrap().as_ref().path();
AtPath::new(tmpdir_path).read_bytes(file_rel_path.as_ref().to_str().unwrap())
}
/// A command result is the outputs of a command (streams and status code)
/// within a struct which has convenience assertion functions about those outputs
#[derive(Debug, Clone)]
pub struct CmdResult {
/// `bin_path` provided by `TestScenario` or `UCommand`
bin_path: PathBuf,
/// `util_name` provided by `TestScenario` or `UCommand`
util_name: Option<String>,
//tmpd is used for convenience functions for asserts against fixtures
tmpd: Option<Rc<TempDir>>,
/// exit status for command (if there is one)
exit_status: Option<ExitStatus>,
/// captured standard output after running the Command
stdout: Vec<u8>,
/// captured standard error after running the Command
stderr: Vec<u8>,
}
impl CmdResult {
pub fn new<S, T, U, V>(
bin_path: S,
util_name: Option<T>,
tmpd: Option<Rc<TempDir>>,
exit_status: Option<ExitStatus>,
stdout: U,
stderr: V,
) -> Self
where
S: Into<PathBuf>,
T: AsRef<str>,
U: Into<Vec<u8>>,
V: Into<Vec<u8>>,
{
Self {
bin_path: bin_path.into(),
util_name: util_name.map(|s| s.as_ref().into()),
tmpd,
exit_status,
stdout: stdout.into(),
stderr: stderr.into(),
}
}
/// Apply a function to `stdout` as bytes and return a new [`CmdResult`]
pub fn stdout_apply<'a, F, R>(&'a self, function: F) -> Self
where
F: Fn(&'a [u8]) -> R,
R: Into<Vec<u8>>,
{
Self::new(
self.bin_path.clone(),
self.util_name.clone(),
self.tmpd.clone(),
self.exit_status,
function(&self.stdout),
self.stderr.as_slice(),
)
}
/// Apply a function to `stdout` as `&str` and return a new [`CmdResult`]
pub fn stdout_str_apply<'a, F, R>(&'a self, function: F) -> Self
where
F: Fn(&'a str) -> R,
R: Into<Vec<u8>>,
{
Self::new(
self.bin_path.clone(),
self.util_name.clone(),
self.tmpd.clone(),
self.exit_status,
function(self.stdout_str()),
self.stderr.as_slice(),
)
}
/// Apply a function to `stderr` as bytes and return a new [`CmdResult`]
pub fn stderr_apply<'a, F, R>(&'a self, function: F) -> Self
where
F: Fn(&'a [u8]) -> R,
R: Into<Vec<u8>>,
{
Self::new(
self.bin_path.clone(),
self.util_name.clone(),
self.tmpd.clone(),
self.exit_status,
self.stdout.as_slice(),
function(&self.stderr),
)
}
/// Apply a function to `stderr` as `&str` and return a new [`CmdResult`]
pub fn stderr_str_apply<'a, F, R>(&'a self, function: F) -> Self
where
F: Fn(&'a str) -> R,
R: Into<Vec<u8>>,
{
Self::new(
self.bin_path.clone(),
self.util_name.clone(),
self.tmpd.clone(),
self.exit_status,
self.stdout.as_slice(),
function(self.stderr_str()),
)
}
/// Assert `stdout` as bytes with a predicate function returning a `bool`.
#[track_caller]
pub fn stdout_check<'a, F>(&'a self, predicate: F) -> &'a Self
where
F: Fn(&'a [u8]) -> bool,
{
assert!(
predicate(&self.stdout),
"Predicate for stdout as `bytes` evaluated to false.\nstdout='{:?}'\nstderr='{:?}'\n",
&self.stdout,
&self.stderr
);
self
}
/// Assert `stdout` as `&str` with a predicate function returning a `bool`.
#[track_caller]
pub fn stdout_str_check<'a, F>(&'a self, predicate: F) -> &'a Self
where
F: Fn(&'a str) -> bool,
{
assert!(
predicate(self.stdout_str()),
"Predicate for stdout as `str` evaluated to false.\nstdout='{}'\nstderr='{}'\n",
self.stdout_str(),
self.stderr_str()
);
self
}
/// Assert `stderr` as bytes with a predicate function returning a `bool`.
#[track_caller]
pub fn stderr_check<'a, F>(&'a self, predicate: F) -> &'a Self
where
F: Fn(&'a [u8]) -> bool,
{
assert!(
predicate(&self.stderr),
"Predicate for stderr as `bytes` evaluated to false.\nstdout='{:?}'\nstderr='{:?}'\n",
&self.stdout,
&self.stderr
);
self
}
/// Assert `stderr` as `&str` with a predicate function returning a `bool`.
#[track_caller]
pub fn stderr_str_check<'a, F>(&'a self, predicate: F) -> &'a Self
where
F: Fn(&'a str) -> bool,
{
assert!(
predicate(self.stderr_str()),
"Predicate for stderr as `str` evaluated to false.\nstdout='{}'\nstderr='{}'\n",
self.stdout_str(),
self.stderr_str()
);
self
}
/// Return the exit status of the child process, if any.
///
/// Returns None if the child process is still running or hasn't been started.
pub fn try_exit_status(&self) -> Option<ExitStatus> {
self.exit_status
}
/// Return the exit status of the child process.
///
/// # Panics
///
/// If the child process is still running or hasn't been started.
pub fn exit_status(&self) -> ExitStatus {
self.try_exit_status()
.expect("Program must be run first or has not finished, yet")
}
/// Return the signal the child process received if any.
///
/// # Platform specific behavior
///
/// This method is only available on unix systems.
#[cfg(unix)]
pub fn signal(&self) -> Option<i32> {
self.exit_status().signal()
}
/// Assert that the given signal `value` equals the signal the child process received.
///
/// See also [`std::os::unix::process::ExitStatusExt::signal`].
///
/// # Platform specific behavior
///
/// This assertion method is only available on unix systems.
#[cfg(unix)]
#[track_caller]
pub fn signal_is(&self, value: i32) -> &Self {
let actual = self.signal().unwrap_or_else(|| {
panic!(
"Expected process to be terminated by the '{}' signal, but exit status is: '{}'",
value,
self.try_exit_status()
.map_or("Not available".to_string(), |e| e.to_string())
)
});
assert_eq!(actual, value);
self
}
/// Assert that the given signal `name` equals the signal the child process received.
///
/// Strings like `SIGINT`, `INT` or a number like `15` are all valid names. See also
/// [`std::os::unix::process::ExitStatusExt::signal`] and
/// [`uucore::signals::signal_by_name_or_value`]
///
/// # Platform specific behavior
///
/// This assertion method is only available on unix systems.
#[cfg(unix)]
#[track_caller]
pub fn signal_name_is(&self, name: &str) -> &Self {
use uucore::signals::signal_by_name_or_value;
let expected: i32 = signal_by_name_or_value(name)
.unwrap_or_else(|| panic!("Invalid signal name or value: '{name}'"))
.try_into()
.unwrap();
let actual = self.signal().unwrap_or_else(|| {
panic!(
"Expected process to be terminated by the '{}' signal, but exit status is: '{}'",
name,
self.try_exit_status()
.map_or("Not available".to_string(), |e| e.to_string())
)
});
assert_eq!(actual, expected);
self
}
/// Returns a reference to the program's standard output as a slice of bytes
pub fn stdout(&self) -> &[u8] {
&self.stdout
}
/// Returns the program's standard output as a string slice
pub fn stdout_str(&self) -> &str {
std::str::from_utf8(&self.stdout).unwrap()
}
/// Returns the program's standard output as a string
/// consumes self
pub fn stdout_move_str(self) -> String {
String::from_utf8(self.stdout).unwrap()
}
/// Returns the program's standard output as a vec of bytes
/// consumes self
pub fn stdout_move_bytes(self) -> Vec<u8> {
self.stdout
}
/// Returns a reference to the program's standard error as a slice of bytes
pub fn stderr(&self) -> &[u8] {
&self.stderr
}
/// Returns the program's standard error as a string slice
pub fn stderr_str(&self) -> &str {
std::str::from_utf8(&self.stderr).unwrap()
}
/// Returns the program's standard error as a string slice, automatically handling invalid utf8
pub fn stderr_str_lossy(&self) -> Cow<'_, str> {
String::from_utf8_lossy(&self.stderr)
}
/// Returns the program's standard error as a string
/// consumes self
pub fn stderr_move_str(self) -> String {
String::from_utf8(self.stderr).unwrap()
}
/// Returns the program's standard error as a vec of bytes
/// consumes self
pub fn stderr_move_bytes(self) -> Vec<u8> {
self.stderr
}
/// Returns the program's exit code
/// Panics if not run or has not finished yet for example when run with `run_no_wait()`
pub fn code(&self) -> i32 {
self.exit_status().code().unwrap()
}
#[track_caller]
pub fn code_is(&self, expected_code: i32) -> &Self {
let fails = self.code() != expected_code;
if fails {
eprintln!(
"stdout:\n{}\nstderr:\n{}",
self.stdout_str(),
self.stderr_str()
);
}
assert_eq!(self.code(), expected_code);
self
}
/// Returns the program's `TempDir`
/// Panics if not present
pub fn tmpd(&self) -> Rc<TempDir> {
match &self.tmpd {
Some(ptr) => ptr.clone(),
None => panic!("Command not associated with a TempDir"),
}
}
/// Returns whether the program succeeded
pub fn succeeded(&self) -> bool {
self.exit_status.map_or(true, |e| e.success())
}
/// asserts that the command resulted in a success (zero) status code
#[track_caller]
pub fn success(&self) -> &Self {
assert!(
self.succeeded(),
"Command was expected to succeed. code: {}\nstdout = {}\n stderr = {}",
self.code(),
self.stdout_str(),
self.stderr_str()
);
self
}
/// asserts that the command resulted in a failure (non-zero) status code
#[track_caller]
pub fn failure(&self) -> &Self {
assert!(
!self.succeeded(),
"Command was expected to fail.\nstdout = {}\n stderr = {}",
self.stdout_str(),
self.stderr_str()
);
self
}
/// asserts that the command resulted in empty (zero-length) stderr stream output
/// generally, it's better to use `stdout_only()` instead,
/// but you might find yourself using this function if
/// 1. you can not know exactly what stdout will be or
/// 2. you know that stdout will also be empty
#[track_caller]
pub fn no_stderr(&self) -> &Self {
assert!(
self.stderr.is_empty(),
"Expected stderr to be empty, but it's:\n{}",
self.stderr_str()
);
self
}
/// asserts that the command resulted in empty (zero-length) stderr stream output
/// unless asserting there was neither stdout or stderr, `stderr_only` is usually a better choice
/// generally, it's better to use `stderr_only()` instead,
/// but you might find yourself using this function if
/// 1. you can not know exactly what stderr will be or
/// 2. you know that stderr will also be empty
#[track_caller]
pub fn no_stdout(&self) -> &Self {
assert!(
self.stdout.is_empty(),
"Expected stdout to be empty, but it's:\n{}",
self.stdout_str()
);
self
}
/// Assert that there is output to neither stderr nor stdout.
#[track_caller]
pub fn no_output(&self) -> &Self {
self.no_stdout().no_stderr()
}
/// asserts that the command resulted in stdout stream output that equals the
/// passed in value, trailing whitespace are kept to force strict comparison (#1235)
/// `stdout_only()` is a better choice unless stderr may or will be non-empty
#[track_caller]
pub fn stdout_is<T: AsRef<str>>(&self, msg: T) -> &Self {
assert_eq!(self.stdout_str(), String::from(msg.as_ref()));
self
}
/// like `stdout_is`, but succeeds if any elements of `expected` matches stdout.
#[track_caller]
pub fn stdout_is_any<T: AsRef<str> + std::fmt::Debug>(&self, expected: &[T]) -> &Self {
assert!(
expected.iter().any(|msg| self.stdout_str() == msg.as_ref()),
"stdout was {}\nExpected any of {:#?}",
self.stdout_str(),
expected
);
self
}
/// Like `stdout_is` but newlines are normalized to `\n`.
#[track_caller]
pub fn normalized_newlines_stdout_is<T: AsRef<str>>(&self, msg: T) -> &Self {
let msg = msg.as_ref().replace("\r\n", "\n");
assert_eq!(self.stdout_str().replace("\r\n", "\n"), msg);
self
}
/// asserts that the command resulted in stdout stream output,
/// whose bytes equal those of the passed in slice
#[track_caller]
pub fn stdout_is_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &Self {
assert_eq!(self.stdout, msg.as_ref(),
"stdout as bytes wasn't equal to expected bytes. Result as strings:\nstdout ='{:?}'\nexpected='{:?}'",
std::str::from_utf8(&self.stdout),
std::str::from_utf8(msg.as_ref()),
);
self
}
/// like `stdout_is()`, but expects the contents of the file at the provided relative path
#[track_caller]
pub fn stdout_is_fixture<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &Self {
let contents = read_scenario_fixture(&self.tmpd, file_rel_path);
self.stdout_is(String::from_utf8(contents).unwrap())
}
/// Assert that the bytes of stdout exactly match those of the given file.
///
/// Contrast this with [`CmdResult::stdout_is_fixture`], which
/// decodes the contents of the file as a UTF-8 [`String`] before
/// comparison with stdout.
///
/// # Examples
///
/// Use this method in a unit test like this:
///
/// ```rust,ignore
/// #[test]
/// fn test_something() {
/// new_ucmd!().succeeds().stdout_is_fixture_bytes("expected.bin");
/// }
/// ```
#[track_caller]
pub fn stdout_is_fixture_bytes<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &Self {
let contents = read_scenario_fixture(&self.tmpd, file_rel_path);
self.stdout_is_bytes(contents)
}
/// like `stdout_is_fixture()`, but replaces the data in fixture file based on values provided in `template_vars`
/// command output
#[track_caller]
pub fn stdout_is_templated_fixture<T: AsRef<OsStr>>(
&self,
file_rel_path: T,
template_vars: &[(&str, &str)],
) -> &Self {
let mut contents =
String::from_utf8(read_scenario_fixture(&self.tmpd, file_rel_path)).unwrap();
for kv in template_vars {
contents = contents.replace(kv.0, kv.1);
}
self.stdout_is(contents)
}
/// like `stdout_is_templated_fixture`, but succeeds if any replacement by `template_vars` results in the actual stdout.
#[track_caller]
pub fn stdout_is_templated_fixture_any<T: AsRef<OsStr>>(
&self,
file_rel_path: T,
template_vars: &[Vec<(String, String)>],
) {
let contents = String::from_utf8(read_scenario_fixture(&self.tmpd, file_rel_path)).unwrap();
let possible_values = template_vars.iter().map(|vars| {
let mut contents = contents.clone();
for kv in vars {
contents = contents.replace(&kv.0, &kv.1);
}
contents
});
self.stdout_is_any(&possible_values.collect::<Vec<_>>());
}
/// assert that the command resulted in stderr stream output that equals the
/// passed in value.
///
/// `stderr_only` is a better choice unless stdout may or will be non-empty
#[track_caller]
pub fn stderr_is<T: AsRef<str>>(&self, msg: T) -> &Self {
assert_eq!(self.stderr_str(), msg.as_ref());
self
}
/// asserts that the command resulted in stderr stream output,
/// whose bytes equal those of the passed in slice
#[track_caller]
pub fn stderr_is_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &Self {
assert_eq!(
&self.stderr,
msg.as_ref(),
"stderr as bytes wasn't equal to expected bytes. Result as strings:\nstderr ='{:?}'\nexpected='{:?}'",
std::str::from_utf8(&self.stderr),
std::str::from_utf8(msg.as_ref())
);
self
}
/// Like `stdout_is_fixture`, but for stderr
#[track_caller]
pub fn stderr_is_fixture<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &Self {
let contents = read_scenario_fixture(&self.tmpd, file_rel_path);
self.stderr_is(String::from_utf8(contents).unwrap())
}
/// asserts that
/// 1. the command resulted in stdout stream output that equals the
/// passed in value
/// 2. the command resulted in empty (zero-length) stderr stream output
#[track_caller]
pub fn stdout_only<T: AsRef<str>>(&self, msg: T) -> &Self {
self.no_stderr().stdout_is(msg)
}
/// asserts that
/// 1. the command resulted in a stdout stream whose bytes
/// equal those of the passed in value
/// 2. the command resulted in an empty stderr stream
#[track_caller]
pub fn stdout_only_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &Self {
self.no_stderr().stdout_is_bytes(msg)
}
/// like `stdout_only()`, but expects the contents of the file at the provided relative path
#[track_caller]
pub fn stdout_only_fixture<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &Self {
let contents = read_scenario_fixture(&self.tmpd, file_rel_path);
self.stdout_only_bytes(contents)
}
/// asserts that
/// 1. the command resulted in stderr stream output that equals the
/// passed in value
/// 2. the command resulted in empty (zero-length) stdout stream output
#[track_caller]
pub fn stderr_only<T: AsRef<str>>(&self, msg: T) -> &Self {
self.no_stdout().stderr_is(msg)
}
/// asserts that
/// 1. the command resulted in a stderr stream whose bytes equal the ones
/// of the passed value
/// 2. the command resulted in an empty stdout stream
#[track_caller]
pub fn stderr_only_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &Self {
self.no_stdout().stderr_is_bytes(msg)
}
#[track_caller]
pub fn fails_silently(&self) -> &Self {
assert!(!self.succeeded());
assert!(self.stderr.is_empty());
self
}
/// asserts that
/// 1. the command resulted in stderr stream output that equals the
/// the following format
/// `"{util_name}: {msg}\nTry '{bin_path} {util_name} --help' for more information."`
/// This the expected format when a `UUsageError` is returned or when `show_error!` is called
/// `msg` should be the same as the one provided to `UUsageError::new` or `show_error!`
///
/// 2. the command resulted in empty (zero-length) stdout stream output
#[track_caller]
pub fn usage_error<T: AsRef<str>>(&self, msg: T) -> &Self {
self.stderr_only(format!(
"{0}: {2}\nTry '{1} {0} --help' for more information.\n",
self.util_name.as_ref().unwrap(), // This shouldn't be called using a normal command
self.bin_path.display(),
msg.as_ref()
))
}
#[track_caller]
pub fn stdout_contains<T: AsRef<str>>(&self, cmp: T) -> &Self {
assert!(
self.stdout_str().contains(cmp.as_ref()),
"'{}' does not contain '{}'",
self.stdout_str(),
cmp.as_ref()
);
self
}
#[track_caller]
pub fn stdout_contains_line<T: AsRef<str>>(&self, cmp: T) -> &Self {
assert!(
self.stdout_str().lines().any(|line| line == cmp.as_ref()),
"'{}' does not contain line '{}'",
self.stdout_str(),
cmp.as_ref()
);
self
}
#[track_caller]
pub fn stderr_contains<T: AsRef<str>>(&self, cmp: T) -> &Self {
assert!(
self.stderr_str().contains(cmp.as_ref()),
"'{}' does not contain '{}'",
self.stderr_str(),
cmp.as_ref()
);
self
}
#[track_caller]
pub fn stdout_does_not_contain<T: AsRef<str>>(&self, cmp: T) -> &Self {
assert!(
!self.stdout_str().contains(cmp.as_ref()),
"'{}' contains '{}' but should not",
self.stdout_str(),
cmp.as_ref(),
);
self
}
#[track_caller]
pub fn stderr_does_not_contain<T: AsRef<str>>(&self, cmp: T) -> &Self {
assert!(!self.stderr_str().contains(cmp.as_ref()));
self
}
#[track_caller]
pub fn stdout_matches(&self, regex: ®ex::Regex) -> &Self {
assert!(
regex.is_match(self.stdout_str()),
"Stdout does not match regex:\n{}",
self.stdout_str()
);
self
}
#[track_caller]
pub fn stderr_matches(&self, regex: ®ex::Regex) -> &Self {
assert!(
regex.is_match(self.stderr_str()),
"Stderr does not match regex:\n{}",
self.stderr_str()
);
self
}
#[track_caller]
pub fn stdout_does_not_match(&self, regex: ®ex::Regex) -> &Self {
assert!(
!regex.is_match(self.stdout_str()),
"Stdout matches regex:\n{}",
self.stdout_str()
);
self
}
}
pub fn log_info<T: AsRef<str>, U: AsRef<str>>(msg: T, par: U) {
println!("{}: {}", msg.as_ref(), par.as_ref());
}
pub fn recursive_copy(src: &Path, dest: &Path) -> Result<()> {
if fs::metadata(src)?.is_dir() {
for entry in fs::read_dir(src)? {
let entry = entry?;
let mut new_dest = PathBuf::from(dest);
new_dest.push(entry.file_name());
if fs::metadata(entry.path())?.is_dir() {
fs::create_dir(&new_dest)?;
recursive_copy(&entry.path(), &new_dest)?;
} else {
fs::copy(entry.path(), new_dest)?;
}
}
}
Ok(())
}
pub fn get_root_path() -> &'static str {
if cfg!(windows) {
"C:\\"
} else {
"/"
}
}
/// Compares the extended attributes (xattrs) of two files or directories.
///
/// # Returns
///
/// `true` if both paths have the same set of extended attributes, `false` otherwise.
#[cfg(all(unix, not(any(target_os = "macos", target_os = "openbsd"))))]
pub fn compare_xattrs<P: AsRef<std::path::Path>>(path1: P, path2: P) -> bool {
let get_sorted_xattrs = |path: P| {
xattr::list(path)
.map(|attrs| {
let mut attrs = attrs.collect::<Vec<_>>();
attrs.sort();
attrs
})
.unwrap_or_default()
};
get_sorted_xattrs(path1) == get_sorted_xattrs(path2)
}
/// Object-oriented path struct that represents and operates on
/// paths relative to the directory it was constructed for.
#[derive(Clone)]
pub struct AtPath {
pub subdir: PathBuf,
}
impl AtPath {
pub fn new(subdir: &Path) -> Self {
Self {
subdir: PathBuf::from(subdir),
}
}
pub fn as_string(&self) -> String {
self.subdir.to_str().unwrap().to_owned()
}
pub fn plus<P: AsRef<Path>>(&self, name: P) -> PathBuf {
let mut pathbuf = self.subdir.clone();
pathbuf.push(name);
pathbuf
}
pub fn plus_as_string<P: AsRef<Path>>(&self, name: P) -> String {
self.plus(name).display().to_string()
}
fn minus(&self, name: &str) -> PathBuf {
let prefixed = PathBuf::from(name);
if prefixed.starts_with(&self.subdir) {
let mut unprefixed = PathBuf::new();
for component in prefixed.components().skip(self.subdir.components().count()) {
unprefixed.push(component.as_os_str().to_str().unwrap());
}
unprefixed
} else {
prefixed
}
}
pub fn minus_as_string(&self, name: &str) -> String {
String::from(self.minus(name).to_str().unwrap())
}
pub fn set_readonly(&self, name: &str) {
let metadata = fs::metadata(self.plus(name)).unwrap();
let mut permissions = metadata.permissions();
permissions.set_readonly(true);
fs::set_permissions(self.plus(name), permissions).unwrap();
}
pub fn open(&self, name: &str) -> File {
log_info("open", self.plus_as_string(name));
File::open(self.plus(name)).unwrap()
}
pub fn read(&self, name: &str) -> String {
let mut f = self.open(name);
let mut contents = String::new();
f.read_to_string(&mut contents)
.unwrap_or_else(|e| panic!("Couldn't read {name}: {e}"));
contents
}
pub fn read_bytes(&self, name: &str) -> Vec<u8> {
let mut f = self.open(name);
let mut contents = Vec::new();
f.read_to_end(&mut contents)
.unwrap_or_else(|e| panic!("Couldn't read {name}: {e}"));
contents
}
pub fn write(&self, name: &str, contents: &str) {
log_info("write(default)", self.plus_as_string(name));
std::fs::write(self.plus(name), contents)
.unwrap_or_else(|e| panic!("Couldn't write {name}: {e}"));
}
pub fn write_bytes(&self, name: &str, contents: &[u8]) {
log_info("write(default)", self.plus_as_string(name));
std::fs::write(self.plus(name), contents)
.unwrap_or_else(|e| panic!("Couldn't write {name}: {e}"));
}
pub fn append(&self, name: &str, contents: &str) {
log_info("write(append)", self.plus_as_string(name));
let mut f = OpenOptions::new()
.append(true)
.create(true)
.open(self.plus(name))
.unwrap();
f.write_all(contents.as_bytes())
.unwrap_or_else(|e| panic!("Couldn't write(append) {name}: {e}"));
}
pub fn append_bytes(&self, name: &str, contents: &[u8]) {
log_info("write(append)", self.plus_as_string(name));
let mut f = OpenOptions::new()
.append(true)
.create(true)
.open(self.plus(name))
.unwrap();
f.write_all(contents)
.unwrap_or_else(|e| panic!("Couldn't write(append) to {name}: {e}"));
}
pub fn truncate(&self, name: &str, contents: &str) {
log_info("write(truncate)", self.plus_as_string(name));
let mut f = OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(self.plus(name))
.unwrap();
f.write_all(contents.as_bytes())
.unwrap_or_else(|e| panic!("Couldn't write(truncate) {name}: {e}"));
}
pub fn rename(&self, source: &str, target: &str) {
let source = self.plus(source);
let target = self.plus(target);
log_info("rename", format!("{source:?} {target:?}"));
std::fs::rename(&source, &target)
.unwrap_or_else(|e| panic!("Couldn't rename {source:?} -> {target:?}: {e}"));
}
pub fn remove(&self, source: &str) {
let source = self.plus(source);
log_info("remove", format!("{source:?}"));
std::fs::remove_file(&source).unwrap_or_else(|e| panic!("Couldn't remove {source:?}: {e}"));
}
pub fn copy(&self, source: &str, target: &str) {
let source = self.plus(source);
let target = self.plus(target);
log_info("copy", format!("{source:?} {target:?}"));
std::fs::copy(&source, &target)
.unwrap_or_else(|e| panic!("Couldn't copy {source:?} -> {target:?}: {e}"));
}
pub fn rmdir(&self, dir: &str) {
log_info("rmdir", self.plus_as_string(dir));
fs::remove_dir(self.plus(dir)).unwrap();
}
pub fn mkdir<P: AsRef<Path>>(&self, dir: P) {
let dir = dir.as_ref();
log_info("mkdir", self.plus_as_string(dir));
fs::create_dir(self.plus(dir)).unwrap();
}
pub fn mkdir_all(&self, dir: &str) {
log_info("mkdir_all", self.plus_as_string(dir));
fs::create_dir_all(self.plus(dir)).unwrap();
}
pub fn make_file(&self, name: &str) -> File {
match File::create(self.plus(name)) {
Ok(f) => f,
Err(e) => panic!("{}", e),
}
}
pub fn touch<P: AsRef<Path>>(&self, file: P) {
let file = file.as_ref();
log_info("touch", self.plus_as_string(file));
File::create(self.plus(file)).unwrap();
}
#[cfg(not(windows))]
pub fn mkfifo(&self, fifo: &str) {
let full_path = self.plus_as_string(fifo);
log_info("mkfifo", &full_path);
unsafe {
let fifo_name: CString = CString::new(full_path).expect("CString creation failed.");
libc::mkfifo(fifo_name.as_ptr(), libc::S_IWUSR | libc::S_IRUSR);
}
}
#[cfg(not(windows))]
pub fn is_fifo(&self, fifo: &str) -> bool {
unsafe {
let name = CString::new(self.plus_as_string(fifo)).unwrap();
let mut stat: libc::stat = std::mem::zeroed();
if libc::stat(name.as_ptr(), &mut stat) >= 0 {
libc::S_IFIFO & stat.st_mode as libc::mode_t != 0
} else {
false
}
}
}