#![allow(dead_code)]
use super::utils::assert_matches_regex;
use std::process::Command;
pub struct RunOutput {
pub status: std::process::ExitStatus,
#[allow(dead_code)]
pub stdout: String,
pub stderr: String,
}
pub struct Cmd {
command: Command,
expect_failure: Option<String>,
scratch_cwd: Option<tempfile::TempDir>,
}
pub fn fixture(exe: &str) -> Cmd {
let scratch_cwd = tempfile::TempDir::new().unwrap();
let mut command = Command::new(exe);
command.current_dir(scratch_cwd.path());
Cmd {
command,
expect_failure: None,
scratch_cwd: Some(scratch_cwd),
}
}
pub fn self_test(test_name: &str) -> Cmd {
let mut command = Command::new(std::env::current_exe().unwrap());
command.args(["--exact", test_name, "--ignored", "--nocapture"]);
command.env("HEGEL_TEST_INHERIT_CWD", "1");
Cmd {
command,
expect_failure: None,
scratch_cwd: None,
}
}
impl Cmd {
pub fn arg(mut self, arg: &str) -> Self {
self.command.arg(arg);
self
}
pub fn args(mut self, args: &[&str]) -> Self {
self.command.args(args);
self
}
pub fn env(mut self, key: &str, value: &str) -> Self {
self.command.env(key, value);
self
}
pub fn env_remove(mut self, key: &str) -> Self {
self.command.env_remove(key);
self
}
pub fn expect_failure(mut self, pattern: &str) -> Self {
self.expect_failure = Some(pattern.to_string());
self
}
pub fn run(mut self) -> RunOutput {
let output = self.command.output().unwrap();
drop(self.scratch_cwd.take());
let run_output = RunOutput {
status: output.status,
stdout: String::from_utf8_lossy(&output.stdout).trim().to_string(),
stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
};
match &self.expect_failure {
None => {
assert!(
run_output.status.success(),
"Expected command to succeed.\nstdout:\n{}\nstderr:\n{}",
run_output.stdout,
run_output.stderr
);
}
Some(pattern) => {
assert!(
!run_output.status.success(),
"Expected command to fail.\nstdout:\n{}\nstderr:\n{}",
run_output.stdout,
run_output.stderr
);
let combined = format!("{}\n{}", run_output.stdout, run_output.stderr);
assert_matches_regex(&combined, pattern);
}
}
run_output
}
}