cargo/tests/support.rs

309 lines
7.8 KiB
Rust
Raw Normal View History

// use std::io::fs::{mkdir_recursive,rmdir_recursive};
2014-05-28 01:33:06 +00:00
use std;
2014-05-08 20:10:08 +00:00
use std::io;
use std::io::fs;
2014-04-02 23:34:19 +00:00
use std::io::process::{ProcessOutput,ProcessExit};
2014-03-20 22:17:19 +00:00
use std::os;
2014-05-08 21:12:38 +00:00
use std::path::{Path,BytesContainer};
2014-04-02 23:34:19 +00:00
use std::str;
2014-04-09 20:28:10 +00:00
use std::vec::Vec;
2014-05-08 23:49:58 +00:00
use std::fmt::Show;
2014-04-02 23:34:19 +00:00
use ham = hamcrest;
2014-05-28 01:33:06 +00:00
use cargo::core::shell;
use cargo::util::{process,ProcessBuilder,CargoError};
use cargo::util::result::ProcessError;
static CARGO_INTEGRATION_TEST_DIR : &'static str = "cargo-integration-tests";
2014-03-20 22:17:19 +00:00
/*
*
* ===== Builders =====
*
*/
2014-06-09 20:08:09 +00:00
#[deriving(PartialEq,Clone)]
struct FileBuilder {
path: Path,
2014-05-27 23:14:34 +00:00
body: String
}
impl FileBuilder {
pub fn new(path: Path, body: &str) -> FileBuilder {
2014-05-29 20:57:31 +00:00
FileBuilder { path: path, body: body.to_str() }
}
2014-05-27 23:14:34 +00:00
fn mk(&self) -> Result<(), String> {
try!(mkdir_recursive(&self.dirname()));
let mut file = try!(
fs::File::create(&self.path)
.with_err_msg(format!("Could not create file; path={}", self.path.display())));
file.write_str(self.body.as_slice())
.with_err_msg(format!("Could not write to file; path={}", self.path.display()))
}
fn dirname(&self) -> Path {
Path::new(self.path.dirname())
}
}
2014-06-09 20:08:09 +00:00
#[deriving(PartialEq,Clone)]
struct ProjectBuilder {
2014-05-27 23:14:34 +00:00
name: String,
root: Path,
2014-04-29 18:05:01 +00:00
files: Vec<FileBuilder>
}
impl ProjectBuilder {
pub fn new(name: &str, root: Path) -> ProjectBuilder {
ProjectBuilder {
2014-05-29 20:57:31 +00:00
name: name.to_str(),
root: root,
2014-04-29 18:05:01 +00:00
files: vec!()
}
}
pub fn root(&self) -> Path {
self.root.clone()
}
2014-03-20 22:17:19 +00:00
pub fn cargo_process(&self, program: &str) -> ProcessBuilder {
2014-05-09 00:50:28 +00:00
self.build();
process(program)
.cwd(self.root())
.extra_path(cargo_dir())
2014-03-20 22:17:19 +00:00
}
2014-05-08 21:12:38 +00:00
pub fn file<B: BytesContainer>(mut self, path: B, body: &str) -> ProjectBuilder {
self.files.push(FileBuilder::new(self.root.join(path), body));
self
}
// TODO: return something different than a ProjectBuilder
2014-05-09 00:50:28 +00:00
pub fn build<'a>(&'a self) -> &'a ProjectBuilder {
match self.build_with_result() {
Err(e) => fail!(e),
_ => return self
}
}
2014-05-27 23:14:34 +00:00
pub fn build_with_result(&self) -> Result<(), String> {
// First, clean the directory if it already exists
try!(self.rm_root());
// Create the empty directory
try!(mkdir_recursive(&self.root));
for file in self.files.iter() {
try!(file.mk());
}
Ok(())
}
2014-05-27 23:14:34 +00:00
fn rm_root(&self) -> Result<(), String> {
if self.root.exists() {
rmdir_recursive(&self.root)
}
else {
Ok(())
}
}
}
// Generates a project layout
pub fn project(name: &str) -> ProjectBuilder {
2014-03-20 22:17:19 +00:00
ProjectBuilder::new(name, os::tmpdir().join(CARGO_INTEGRATION_TEST_DIR))
}
// === Helpers ===
2014-05-27 23:14:34 +00:00
pub fn mkdir_recursive(path: &Path) -> Result<(), String> {
2014-05-08 20:10:08 +00:00
fs::mkdir_recursive(path, io::UserDir)
.with_err_msg(format!("could not create directory; path={}", path.display()))
}
2014-05-27 23:14:34 +00:00
pub fn rmdir_recursive(path: &Path) -> Result<(), String> {
fs::rmdir_recursive(path)
.with_err_msg(format!("could not rm directory; path={}", path.display()))
}
trait ErrMsg<T> {
2014-05-27 23:14:34 +00:00
fn with_err_msg(self, val: String) -> Result<T, String>;
}
2014-05-08 23:49:58 +00:00
impl<T, E: Show> ErrMsg<T> for Result<T, E> {
2014-05-27 23:14:34 +00:00
fn with_err_msg(self, val: String) -> Result<T, String> {
match self {
Ok(val) => Ok(val),
2014-05-08 23:49:58 +00:00
Err(err) => Err(format!("{}; original={}", val, err))
}
}
}
2014-03-20 22:17:19 +00:00
// Path to cargo executables
2014-04-02 23:34:19 +00:00
pub fn cargo_dir() -> Path {
2014-05-08 23:49:58 +00:00
os::getenv("CARGO_BIN_PATH")
.map(|s| Path::new(s))
.unwrap_or_else(|| fail!("CARGO_BIN_PATH wasn't set. Cannot continue running test"))
2014-03-20 22:17:19 +00:00
}
2014-06-09 20:08:09 +00:00
/// Returns an absolute path in the filesystem that `path` points to. The
/// returned path does not contain any symlinks in its hierarchy.
2014-03-20 22:17:19 +00:00
/*
*
* ===== Matchers =====
*
*/
2014-04-02 23:34:19 +00:00
2014-06-09 20:08:09 +00:00
#[deriving(Clone)]
2014-04-02 23:34:19 +00:00
struct Execs {
2014-05-27 23:14:34 +00:00
expect_stdout: Option<String>,
expect_stdin: Option<String>,
expect_stderr: Option<String>,
expect_exit_code: Option<int>
2014-04-02 23:34:19 +00:00
}
impl Execs {
2014-06-11 21:50:54 +00:00
pub fn with_stdout<S: ToStr>(mut ~self, expected: S) -> Box<Execs> {
2014-05-29 20:57:31 +00:00
self.expect_stdout = Some(expected.to_str());
2014-04-02 23:34:19 +00:00
self
}
2014-06-11 21:50:54 +00:00
pub fn with_stderr<S: ToStr>(mut ~self, expected: S) -> Box<Execs> {
2014-05-29 20:57:31 +00:00
self.expect_stderr = Some(expected.to_str());
self
}
pub fn with_status(mut ~self, expected: int) -> Box<Execs> {
self.expect_exit_code = Some(expected);
self
}
2014-04-02 23:34:19 +00:00
fn match_output(&self, actual: &ProcessOutput) -> ham::MatchResult {
self.match_status(actual.status)
.and(self.match_stdout(actual))
.and(self.match_stderr(actual))
2014-04-02 23:34:19 +00:00
}
fn match_status(&self, actual: ProcessExit) -> ham::MatchResult {
match self.expect_exit_code {
None => ham::success(),
Some(code) => {
ham::expect(
actual.matches_exit_status(code),
format!("exited with {}", actual))
}
}
}
fn match_stdout(&self, actual: &ProcessOutput) -> ham::MatchResult {
self.match_std(self.expect_stdout.as_ref(), actual.output.as_slice(), "stdout", actual.error.as_slice())
}
fn match_stderr(&self, actual: &ProcessOutput) -> ham::MatchResult {
self.match_std(self.expect_stderr.as_ref(), actual.error.as_slice(), "stderr", actual.output.as_slice())
}
fn match_std(&self, expected: Option<&String>, actual: &[u8], description: &str, extra: &[u8]) -> ham::MatchResult {
match expected.as_ref().map(|s| s.as_slice()) {
2014-04-02 23:34:19 +00:00
None => ham::success(),
Some(out) => {
match str::from_utf8(actual) {
None => Err(format!("{} was not utf8 encoded", description)),
2014-04-02 23:34:19 +00:00
Some(actual) => {
2014-06-11 21:50:54 +00:00
ham::expect(actual == out, format!("{} was:\n`{}`\n\nexpected:\n`{}`\n\nother output:\n`{}`", description, actual, out, str::from_utf8_lossy(extra)))
2014-04-02 23:34:19 +00:00
}
}
}
}
}
}
impl ham::SelfDescribing for Execs {
2014-05-27 23:14:34 +00:00
fn describe(&self) -> String {
2014-05-29 20:57:31 +00:00
"execs".to_str()
2014-04-02 23:34:19 +00:00
}
}
impl ham::Matcher<ProcessBuilder> for Execs {
2014-04-10 01:07:47 +00:00
fn matches(&self, process: ProcessBuilder) -> ham::MatchResult {
2014-04-02 23:34:19 +00:00
let res = process.exec_with_output();
match res {
Ok(out) => self.match_output(&out),
Err(CargoError { kind: ProcessError(_, ref out), .. }) => self.match_output(out.get_ref()),
Err(e) => Err(format!("could not exec process {}: {}", process, e))
2014-04-02 23:34:19 +00:00
}
}
}
2014-05-08 20:10:08 +00:00
pub fn execs() -> Box<Execs> {
box Execs {
expect_stdout: None,
expect_stderr: None,
expect_stdin: None,
expect_exit_code: None
}
2014-04-02 23:34:19 +00:00
}
2014-05-08 23:49:58 +00:00
2014-06-09 20:08:09 +00:00
#[deriving(Clone)]
2014-05-28 01:33:06 +00:00
struct ShellWrites {
expected: String
}
impl ham::SelfDescribing for ShellWrites {
fn describe(&self) -> String {
format!("`{}` written to the shell", self.expected)
}
}
impl<'a> ham::Matcher<&'a mut shell::Shell<std::io::MemWriter>> for ShellWrites {
fn matches(&self, actual: &mut shell::Shell<std::io::MemWriter>) -> ham::MatchResult {
use term::Terminal;
let actual = std::str::from_utf8_lossy(actual.get_ref().get_ref()).to_str();
ham::expect(actual == self.expected, actual)
}
}
pub fn shell_writes<T: Show>(string: T) -> Box<ShellWrites> {
box ShellWrites { expected: string.to_str() }
}
2014-05-08 23:49:58 +00:00
pub trait ResultTest<T,E> {
fn assert(self) -> T;
}
impl<T,E: Show> ResultTest<T,E> for Result<T,E> {
fn assert(self) -> T {
match self {
Ok(val) => val,
Err(err) => fail!("Result was error: {}", err)
}
}
}
2014-05-28 01:33:06 +00:00
impl<T> ResultTest<T,()> for Option<T> {
fn assert(self) -> T {
match self {
Some(val) => val,
None => fail!("Option was None")
}
}
}
pub trait Tap {
fn tap(mut self, callback: |&mut Self|) -> Self;
}
impl<T> Tap for T {
fn tap(mut self, callback: |&mut T|) -> T {
callback(&mut self);
self
}
}