1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 11:37:44 +00:00

Merge pull request #2742 from thomasqueirozb/usage_error

Add CmdResult::usage_error
This commit is contained in:
Sylvestre Ledru 2021-11-12 21:15:07 +01:00 committed by GitHub
commit 9f60f4d0dc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 142 additions and 104 deletions

View file

@ -113,18 +113,12 @@ fn test_wrap_bad_arg() {
#[test] #[test]
fn test_base32_extra_operand() { fn test_base32_extra_operand() {
let ts = TestScenario::new(util_name!());
// Expect a failure when multiple files are specified. // Expect a failure when multiple files are specified.
ts.ucmd() new_ucmd!()
.arg("a.txt") .arg("a.txt")
.arg("b.txt") .arg("b.txt")
.fails() .fails()
.stderr_only(format!( .usage_error("extra operand 'b.txt'");
"{0}: extra operand 'b.txt'\nTry '{1} {0} --help' for more information.",
ts.util_name,
ts.bin_path.to_string_lossy()
));
} }
#[test] #[test]

View file

@ -95,18 +95,12 @@ fn test_wrap_bad_arg() {
#[test] #[test]
fn test_base64_extra_operand() { fn test_base64_extra_operand() {
let ts = TestScenario::new(util_name!());
// Expect a failure when multiple files are specified. // Expect a failure when multiple files are specified.
ts.ucmd() new_ucmd!()
.arg("a.txt") .arg("a.txt")
.arg("b.txt") .arg("b.txt")
.fails() .fails()
.stderr_only(format!( .usage_error("extra operand 'b.txt'");
"{0}: extra operand 'b.txt'\nTry '{1} {0} --help' for more information.",
ts.util_name,
ts.bin_path.to_string_lossy()
));
} }
#[test] #[test]

View file

@ -114,12 +114,7 @@ fn test_no_args() {
#[test] #[test]
fn test_no_args_output() { fn test_no_args_output() {
let ts = TestScenario::new(util_name!()); new_ucmd!().fails().usage_error("missing operand");
ts.ucmd().fails().stderr_is(&format!(
"{0}: missing operand\nTry '{1} {0} --help' for more information.",
ts.util_name,
ts.bin_path.to_string_lossy()
));
} }
#[test] #[test]
@ -129,12 +124,10 @@ fn test_too_many_args() {
#[test] #[test]
fn test_too_many_args_output() { fn test_too_many_args_output() {
let ts = TestScenario::new(util_name!()); new_ucmd!()
ts.ucmd().args(&["a", "b", "c"]).fails().stderr_is(format!( .args(&["a", "b", "c"])
"{0}: extra operand 'c'\nTry '{1} {0} --help' for more information.", .fails()
ts.util_name, .usage_error("extra operand 'c'");
ts.bin_path.to_string_lossy()
));
} }
#[cfg(any(unix, target_os = "redox"))] #[cfg(any(unix, target_os = "redox"))]

View file

@ -563,17 +563,13 @@ fn test_cp_backup_off() {
#[test] #[test]
fn test_cp_backup_no_clobber_conflicting_options() { fn test_cp_backup_no_clobber_conflicting_options() {
let ts = TestScenario::new(util_name!()); new_ucmd!()
ts.ucmd()
.arg("--backup") .arg("--backup")
.arg("--no-clobber") .arg("--no-clobber")
.arg(TEST_HELLO_WORLD_SOURCE) .arg(TEST_HELLO_WORLD_SOURCE)
.arg(TEST_HOW_ARE_YOU_SOURCE) .arg(TEST_HOW_ARE_YOU_SOURCE)
.fails().stderr_is(&format!( .fails()
"{0}: options --backup and --no-clobber are mutually exclusive\nTry '{1} {0} --help' for more information.", .usage_error("options --backup and --no-clobber are mutually exclusive");
ts.util_name,
ts.bin_path.to_string_lossy()
));
} }
#[test] #[test]

View file

@ -15,15 +15,10 @@ fn test_more_dir_arg() {
// Maybe we could capture the error, i.e. "Device not found" in that case // Maybe we could capture the error, i.e. "Device not found" in that case
// but I am leaving this for later // but I am leaving this for later
if atty::is(atty::Stream::Stdout) { if atty::is(atty::Stream::Stdout) {
let ts = TestScenario::new(util_name!()); new_ucmd!()
let result = ts.ucmd().arg(".").run(); .arg(".")
result.failure(); .fails()
let expected_error_message = &format!( .usage_error("'.' is a directory.");
"{0}: '.' is a directory.\nTry '{1} {0} --help' for more information.",
ts.util_name,
ts.bin_path.to_string_lossy()
);
assert_eq!(result.stderr_str().trim(), expected_error_message);
} else { } else {
} }
} }

View file

@ -522,17 +522,13 @@ fn test_mv_backup_off() {
#[test] #[test]
fn test_mv_backup_no_clobber_conflicting_options() { fn test_mv_backup_no_clobber_conflicting_options() {
let ts = TestScenario::new(util_name!()); new_ucmd!()
.arg("--backup")
ts.ucmd().arg("--backup")
.arg("--no-clobber") .arg("--no-clobber")
.arg("file1") .arg("file1")
.arg("file2") .arg("file2")
.fails() .fails()
.stderr_is(&format!("{0}: options --backup and --no-clobber are mutually exclusive\nTry '{1} {0} --help' for more information.", .usage_error("options --backup and --no-clobber are mutually exclusive");
ts.util_name,
ts.bin_path.to_string_lossy()
));
} }
#[test] #[test]

View file

@ -22,15 +22,10 @@ fn test_negative_adjustment() {
#[test] #[test]
fn test_adjustment_with_no_command_should_error() { fn test_adjustment_with_no_command_should_error() {
let ts = TestScenario::new(util_name!()); new_ucmd!()
.args(&["-n", "19"])
ts.ucmd() .fails()
.args(&["-n", "19"]) .usage_error("A command must be given with an adjustment.");
.run()
.stderr_is(&format!("{0}: A command must be given with an adjustment.\nTry '{1} {0} --help' for more information.\n",
ts.util_name,
ts.bin_path.to_string_lossy()
));
} }
#[test] #[test]

View file

@ -66,24 +66,18 @@ fn test_hex_identifier_in_wrong_place() {
#[test] #[test]
fn test_rejects_nan() { fn test_rejects_nan() {
let ts = TestScenario::new(util_name!()); new_ucmd!()
.arg("NaN")
ts.ucmd().args(&["NaN"]).fails().stderr_only(format!( .fails()
"{0}: invalid 'not-a-number' argument: 'NaN'\nTry '{1} {0} --help' for more information.", .usage_error("invalid 'not-a-number' argument: 'NaN'");
ts.util_name,
ts.bin_path.to_string_lossy()
));
} }
#[test] #[test]
fn test_rejects_non_floats() { fn test_rejects_non_floats() {
let ts = TestScenario::new(util_name!()); new_ucmd!()
.arg("foo")
ts.ucmd().args(&["foo"]).fails().stderr_only(&format!( .fails()
"{0}: invalid floating point argument: 'foo'\nTry '{1} {0} --help' for more information.", .usage_error("invalid floating point argument: 'foo'");
ts.util_name,
ts.bin_path.to_string_lossy()
));
} }
#[test] #[test]
@ -547,11 +541,7 @@ fn test_trailing_whitespace_error() {
new_ucmd!() new_ucmd!()
.arg("1 ") .arg("1 ")
.fails() .fails()
.no_stdout() .usage_error("invalid floating point argument: '1 '");
.stderr_contains("seq: invalid floating point argument: '1 '")
// FIXME The second line of the error message is "Try 'seq
// --help' for more information."
.stderr_contains("for more information.");
} }
#[test] #[test]

View file

@ -53,16 +53,10 @@ fn test_stdbuf_trailing_var_arg() {
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
#[test] #[test]
fn test_stdbuf_line_buffering_stdin_fails() { fn test_stdbuf_line_buffering_stdin_fails() {
let ts = TestScenario::new(util_name!()); new_ucmd!()
ts.ucmd()
.args(&["-i", "L", "head"]) .args(&["-i", "L", "head"])
.fails() .fails()
.stderr_is(&format!( .usage_error("line buffering stdin is meaningless");
"{0}: line buffering stdin is meaningless\nTry '{1} {0} --help' for more information.",
ts.util_name,
ts.bin_path.to_string_lossy()
));
} }
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]

View file

@ -62,6 +62,10 @@ fn read_scenario_fixture<S: AsRef<OsStr>>(tmpd: &Option<Rc<TempDir>>, file_rel_p
/// within a struct which has convenience assertion functions about those outputs /// within a struct which has convenience assertion functions about those outputs
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CmdResult { pub struct CmdResult {
/// bin_path provided by `TestScenario` or `UCommand`
bin_path: String,
/// util_name provided by `TestScenario` or `UCommand`
util_name: Option<String>,
//tmpd is used for convenience functions for asserts against fixtures //tmpd is used for convenience functions for asserts against fixtures
tmpd: Option<Rc<TempDir>>, tmpd: Option<Rc<TempDir>>,
/// exit status for command (if there is one) /// exit status for command (if there is one)
@ -77,6 +81,8 @@ pub struct CmdResult {
impl CmdResult { impl CmdResult {
pub fn new( pub fn new(
bin_path: String,
util_name: Option<String>,
tmpd: Option<Rc<TempDir>>, tmpd: Option<Rc<TempDir>>,
code: Option<i32>, code: Option<i32>,
success: bool, success: bool,
@ -84,6 +90,8 @@ impl CmdResult {
stderr: &[u8], stderr: &[u8],
) -> CmdResult { ) -> CmdResult {
CmdResult { CmdResult {
bin_path,
util_name,
tmpd, tmpd,
code, code,
success, success,
@ -357,6 +365,23 @@ impl CmdResult {
self self
} }
/// asserts that
/// 1. the command resulted in stderr stream output that equals the
/// the following format when both are trimmed of trailing whitespace
/// `"{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
pub fn usage_error<T: AsRef<str>>(&self, msg: T) -> &CmdResult {
self.stderr_only(format!(
"{0}: {2}\nTry '{1} {0} --help' for more information.",
self.util_name.as_ref().unwrap(), // This shouldn't be called using a normal command
self.bin_path,
msg.as_ref()
))
}
pub fn stdout_contains<T: AsRef<str>>(&self, cmp: T) -> &CmdResult { pub fn stdout_contains<T: AsRef<str>>(&self, cmp: T) -> &CmdResult {
assert!( assert!(
self.stdout_str().contains(cmp.as_ref()), self.stdout_str().contains(cmp.as_ref()),
@ -780,31 +805,36 @@ impl TestScenario {
/// Returns builder for invoking the target uutils binary. Paths given are /// Returns builder for invoking the target uutils binary. Paths given are
/// treated relative to the environment's unique temporary test directory. /// treated relative to the environment's unique temporary test directory.
pub fn ucmd(&self) -> UCommand { pub fn ucmd(&self) -> UCommand {
let mut cmd = self.cmd(&self.bin_path); self.composite_cmd(&self.bin_path, &self.util_name, true)
cmd.arg(&self.util_name); }
cmd
/// Returns builder for invoking the target uutils binary. Paths given are
/// treated relative to the environment's unique temporary test directory.
pub fn composite_cmd<S: AsRef<OsStr>, T: AsRef<OsStr>>(
&self,
bin: S,
util_name: T,
env_clear: bool,
) -> UCommand {
UCommand::new_from_tmp(bin, Some(util_name), self.tmpd.clone(), env_clear)
} }
/// Returns builder for invoking any system command. Paths given are treated /// Returns builder for invoking any system command. Paths given are treated
/// relative to the environment's unique temporary test directory. /// relative to the environment's unique temporary test directory.
pub fn cmd<S: AsRef<OsStr>>(&self, bin: S) -> UCommand { pub fn cmd<S: AsRef<OsStr>>(&self, bin: S) -> UCommand {
UCommand::new_from_tmp(bin, self.tmpd.clone(), true) UCommand::new_from_tmp::<S, S>(bin, None, self.tmpd.clone(), true)
} }
/// Returns builder for invoking any uutils command. Paths given are treated /// Returns builder for invoking any uutils command. Paths given are treated
/// relative to the environment's unique temporary test directory. /// relative to the environment's unique temporary test directory.
pub fn ccmd<S: AsRef<OsStr>>(&self, bin: S) -> UCommand { pub fn ccmd<S: AsRef<OsStr>>(&self, bin: S) -> UCommand {
let mut cmd = self.cmd(&self.bin_path); self.composite_cmd(&self.bin_path, bin, true)
cmd.arg(bin);
cmd
} }
// different names are used rather than an argument // different names are used rather than an argument
// because the need to keep the environment is exceedingly rare. // because the need to keep the environment is exceedingly rare.
pub fn ucmd_keepenv(&self) -> UCommand { pub fn ucmd_keepenv(&self) -> UCommand {
let mut cmd = self.cmd_keepenv(&self.bin_path); self.composite_cmd(&self.bin_path, &self.util_name, false)
cmd.arg(&self.util_name);
cmd
} }
/// Returns builder for invoking any system command. Paths given are treated /// Returns builder for invoking any system command. Paths given are treated
@ -812,7 +842,7 @@ impl TestScenario {
/// Differs from the builder returned by `cmd` in that `cmd_keepenv` does not call /// Differs from the builder returned by `cmd` in that `cmd_keepenv` does not call
/// `Command::env_clear` (Clears the entire environment map for the child process.) /// `Command::env_clear` (Clears the entire environment map for the child process.)
pub fn cmd_keepenv<S: AsRef<OsStr>>(&self, bin: S) -> UCommand { pub fn cmd_keepenv<S: AsRef<OsStr>>(&self, bin: S) -> UCommand {
UCommand::new_from_tmp(bin, self.tmpd.clone(), false) UCommand::new_from_tmp::<S, S>(bin, None, self.tmpd.clone(), false)
} }
} }
@ -826,6 +856,8 @@ impl TestScenario {
pub struct UCommand { pub struct UCommand {
pub raw: Command, pub raw: Command,
comm_string: String, comm_string: String,
bin_path: String,
util_name: Option<String>,
tmpd: Option<Rc<TempDir>>, tmpd: Option<Rc<TempDir>>,
has_run: bool, has_run: bool,
ignore_stdin_write_error: bool, ignore_stdin_write_error: bool,
@ -838,12 +870,20 @@ pub struct UCommand {
} }
impl UCommand { impl UCommand {
pub fn new<T: AsRef<OsStr>, U: AsRef<OsStr>>(arg: T, curdir: U, env_clear: bool) -> UCommand { pub fn new<T: AsRef<OsStr>, S: AsRef<OsStr>, U: AsRef<OsStr>>(
UCommand { bin_path: T,
util_name: Option<S>,
curdir: U,
env_clear: bool,
) -> UCommand {
let bin_path = bin_path.as_ref();
let util_name = util_name.as_ref().map(|un| un.as_ref());
let mut ucmd = UCommand {
tmpd: None, tmpd: None,
has_run: false, has_run: false,
raw: { raw: {
let mut cmd = Command::new(arg.as_ref()); let mut cmd = Command::new(bin_path);
cmd.current_dir(curdir.as_ref()); cmd.current_dir(curdir.as_ref());
if env_clear { if env_clear {
if cfg!(windows) { if cfg!(windows) {
@ -863,7 +903,9 @@ impl UCommand {
} }
cmd cmd
}, },
comm_string: String::from(arg.as_ref().to_str().unwrap()), comm_string: String::from(bin_path.to_str().unwrap()),
bin_path: bin_path.to_str().unwrap().to_string(),
util_name: util_name.map(|un| un.to_str().unwrap().to_string()),
ignore_stdin_write_error: false, ignore_stdin_write_error: false,
bytes_into_stdin: None, bytes_into_stdin: None,
stdin: None, stdin: None,
@ -871,12 +913,23 @@ impl UCommand {
stderr: None, stderr: None,
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
limits: vec![], limits: vec![],
};
if let Some(un) = util_name {
ucmd.arg(un);
} }
ucmd
} }
pub fn new_from_tmp<T: AsRef<OsStr>>(arg: T, tmpd: Rc<TempDir>, env_clear: bool) -> UCommand { pub fn new_from_tmp<T: AsRef<OsStr>, S: AsRef<OsStr>>(
bin_path: T,
util_name: Option<S>,
tmpd: Rc<TempDir>,
env_clear: bool,
) -> UCommand {
let tmpd_path_buf = String::from(&(*tmpd.as_ref().path().to_str().unwrap())); let tmpd_path_buf = String::from(&(*tmpd.as_ref().path().to_str().unwrap()));
let mut ucmd: UCommand = UCommand::new(arg.as_ref(), tmpd_path_buf, env_clear); let mut ucmd: UCommand = UCommand::new(bin_path, util_name, tmpd_path_buf, env_clear);
ucmd.tmpd = Some(tmpd); ucmd.tmpd = Some(tmpd);
ucmd ucmd
} }
@ -1021,6 +1074,8 @@ impl UCommand {
let prog = self.run_no_wait().wait_with_output().unwrap(); let prog = self.run_no_wait().wait_with_output().unwrap();
CmdResult { CmdResult {
bin_path: self.bin_path.clone(),
util_name: self.util_name.clone(),
tmpd: self.tmpd.clone(), tmpd: self.tmpd.clone(),
code: prog.status.code(), code: prog.status.code(),
success: prog.status.success(), success: prog.status.success(),
@ -1268,6 +1323,8 @@ pub fn expected_result(ts: &TestScenario, args: &[&str]) -> std::result::Result<
}; };
Ok(CmdResult::new( Ok(CmdResult::new(
ts.bin_path.as_os_str().to_str().unwrap().to_string(),
Some(ts.util_name.clone()),
Some(result.tmpd()), Some(result.tmpd()),
Some(result.code()), Some(result.code()),
result.succeeded(), result.succeeded(),
@ -1285,6 +1342,8 @@ mod tests {
#[test] #[test]
fn test_code_is() { fn test_code_is() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: Some(32), code: Some(32),
success: false, success: false,
@ -1298,6 +1357,8 @@ mod tests {
#[should_panic] #[should_panic]
fn test_code_is_fail() { fn test_code_is_fail() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: Some(32), code: Some(32),
success: false, success: false,
@ -1310,6 +1371,8 @@ mod tests {
#[test] #[test]
fn test_failure() { fn test_failure() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: false, success: false,
@ -1323,6 +1386,8 @@ mod tests {
#[should_panic] #[should_panic]
fn test_failure_fail() { fn test_failure_fail() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,
@ -1335,6 +1400,8 @@ mod tests {
#[test] #[test]
fn test_success() { fn test_success() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,
@ -1348,6 +1415,8 @@ mod tests {
#[should_panic] #[should_panic]
fn test_success_fail() { fn test_success_fail() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: false, success: false,
@ -1360,6 +1429,8 @@ mod tests {
#[test] #[test]
fn test_no_stderr_output() { fn test_no_stderr_output() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,
@ -1374,6 +1445,8 @@ mod tests {
#[should_panic] #[should_panic]
fn test_no_stderr_fail() { fn test_no_stderr_fail() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,
@ -1388,6 +1461,8 @@ mod tests {
#[should_panic] #[should_panic]
fn test_no_stdout_fail() { fn test_no_stdout_fail() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,
@ -1401,6 +1476,8 @@ mod tests {
#[test] #[test]
fn test_std_does_not_contain() { fn test_std_does_not_contain() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,
@ -1415,6 +1492,8 @@ mod tests {
#[should_panic] #[should_panic]
fn test_stdout_does_not_contain_fail() { fn test_stdout_does_not_contain_fail() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,
@ -1429,6 +1508,8 @@ mod tests {
#[should_panic] #[should_panic]
fn test_stderr_does_not_contain_fail() { fn test_stderr_does_not_contain_fail() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,
@ -1442,6 +1523,8 @@ mod tests {
#[test] #[test]
fn test_stdout_matches() { fn test_stdout_matches() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,
@ -1458,6 +1541,8 @@ mod tests {
#[should_panic] #[should_panic]
fn test_stdout_matches_fail() { fn test_stdout_matches_fail() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,
@ -1473,6 +1558,8 @@ mod tests {
#[should_panic] #[should_panic]
fn test_stdout_not_matches_fail() { fn test_stdout_not_matches_fail() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,
@ -1487,6 +1574,8 @@ mod tests {
#[test] #[test]
fn test_normalized_newlines_stdout_is() { fn test_normalized_newlines_stdout_is() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,
@ -1503,6 +1592,8 @@ mod tests {
#[should_panic] #[should_panic]
fn test_normalized_newlines_stdout_is_fail() { fn test_normalized_newlines_stdout_is_fail() {
let res = CmdResult { let res = CmdResult {
bin_path: "".into(),
util_name: None,
tmpd: None, tmpd: None,
code: None, code: None,
success: true, success: true,