coreutils/test/common/util.rs
Joseph Crail 62b9dc0326 Refactor method to auto-convert into byte array.
When creating tests, we could pass a String, &str, or [u8] to the
standard input. Previously, all arguments had to be manually converted
to a reference to a [u8]. This update makes it more ergonomic.
2015-05-30 19:12:49 -04:00

87 lines
2.1 KiB
Rust

#![allow(dead_code)]
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::Path;
use std::process::{Command, Stdio};
use std::str::from_utf8;
#[macro_export]
macro_rules! assert_empty_stderr(
($cond:expr) => (
if $cond.stderr.len() > 0 {
panic!(format!("stderr: {}", $cond.stderr))
}
);
);
pub struct CmdResult {
pub success: bool,
pub stdout: String,
pub stderr: String,
}
pub fn run(cmd: &mut Command) -> CmdResult {
let prog = cmd.output().unwrap();
CmdResult {
success: prog.status.success(),
stdout: from_utf8(&prog.stdout).unwrap().to_string(),
stderr: from_utf8(&prog.stderr).unwrap().to_string(),
}
}
pub fn run_piped_stdin<T: AsRef<[u8]>>(cmd: &mut Command, input: T)-> CmdResult {
let mut command = cmd
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
command.stdin
.take()
.unwrap_or_else(|| panic!("Could not take child process stdin"))
.write_all(input.as_ref())
.unwrap_or_else(|e| panic!("{}", e));
let prog = command.wait_with_output().unwrap();
CmdResult {
success: prog.status.success(),
stdout: from_utf8(&prog.stdout).unwrap().to_string(),
stderr: from_utf8(&prog.stderr).unwrap().to_string(),
}
}
pub fn get_file_contents(name: &str) -> String {
let mut f = File::open(Path::new(name)).unwrap();
let mut contents = String::new();
let _ = f.read_to_string(&mut contents);
contents
}
pub fn mkdir(dir: &str) {
fs::create_dir(Path::new(dir)).unwrap();
}
pub fn make_file(name: &str) -> File {
match File::create(Path::new(name)) {
Ok(f) => f,
Err(e) => panic!("{}", e)
}
}
pub fn touch(file: &str) {
File::create(Path::new(file)).unwrap();
}
pub fn cleanup(path: &'static str) {
let p = Path::new(path);
match fs::metadata(p) {
Ok(m) => if m.is_file() {
fs::remove_file(&p).unwrap();
} else {
fs::remove_dir(&p).unwrap();
},
Err(_) => {}
}
}