Skip to content
This repository was archived by the owner on Dec 29, 2021. It is now read-only.

fix(cargo): Avoid cargo run #111

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@ categories = ["development-tools::testing"]
keywords = ["cli", "testing", "assert"]

[[bin]]
name = "assert_fixture"
name = "bin_fixture"

[dependencies]
colored = "1.5"
difference = "2.0"
failure = "0.1"
failure_derive = "0.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
environment = "0.1"

Expand Down
16 changes: 16 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use std::env;
use std::fs;
use std::io::Write;
use std::path;

fn main() {
println!("cargo:rerun-if-changed=build.rs");

// env::ARCH doesn't include full triple, and AFAIK there isn't a nicer way of getting the full triple
// (see lib.rs for the rest of this hack)
let out = path::PathBuf::from(env::var_os("OUT_DIR").expect("run within cargo"))
.join("current_target.txt");
let default_target = env::var("TARGET").expect("run as cargo build script");
let mut file = fs::File::create(out).unwrap();
file.write_all(default_target.as_bytes()).unwrap();
}
File renamed without changes.
187 changes: 83 additions & 104 deletions src/assert.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::default;
use std::ffi::{OsStr, OsString};
use std::io::Write;
use std::path::PathBuf;
Expand All @@ -11,6 +10,35 @@ use failure::Fail;

use errors::*;
use output::{Content, Output, OutputKind, OutputPredicate};
use cargo;

#[derive(Deserialize)]
struct MessageTarget<'a> {
#[serde(borrow)]
crate_types: Vec<&'a str>,
#[serde(borrow)]
kind: Vec<&'a str>,
}

#[derive(Deserialize)]
struct MessageFilter<'a> {
#[serde(borrow)]
reason: &'a str,
target: MessageTarget<'a>,
#[serde(borrow)]
filenames: Vec<&'a str>,
}

fn filenames(msg: cargo::Message, kind: &str) -> Option<String> {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improve name

let filter: MessageFilter = msg.convert().ok()?;
if filter.reason != "compiler-artifact" || filter.target.crate_types != ["bin"]
|| filter.target.kind != [kind]
{
None
} else {
Some(filter.filenames[0].to_owned())
}
}

/// Assertions for a specific command.
#[derive(Debug)]
Expand All @@ -25,80 +53,72 @@ pub struct Assert {
stdin_contents: Option<Vec<u8>>,
}

impl default::Default for Assert {
/// Construct an assert using `cargo run --` as command.
impl Assert {
/// Run the crate's main binary.
///
/// Defaults to asserting _successful_ execution.
fn default() -> Self {
Assert {
cmd: vec![
"cargo",
"run",
#[cfg(not(debug_assertions))]
"--release",
"--quiet",
"--",
].into_iter()
.map(OsString::from)
.collect(),
pub fn main_binary() -> Result<Self, failure::Error> {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Define a proper error for this and related functions

let cargo = cargo::Cargo::new().build().current_release();
let bins: Vec<_> = cargo.exec()?.filter_map(|m| filenames(m, "bin")).collect();
if bins.is_empty() {
bail!("No binaries in crate");
} else if bins.len() != 1 {
bail!("Ambiguous which binary is intended: {:?}", bins);
}
let bin = bins[0].as_str();
let cmd = Self {
cmd: vec![bin].into_iter().map(OsString::from).collect(),
env: Environment::inherit(),
current_dir: None,
expect_success: Some(true),
expect_exit_code: None,
expect_output: vec![],
stdin_contents: None,
}
}
}

impl Assert {
/// Run the crate's main binary.
///
/// Defaults to asserting _successful_ execution.
pub fn main_binary() -> Self {
Assert::default()
};
Ok(cmd)
}

/// Run a specific binary of the current crate.
///
/// Defaults to asserting _successful_ execution.
pub fn cargo_binary<S: AsRef<OsStr>>(name: S) -> Self {
Assert {
cmd: vec![
OsStr::new("cargo"),
OsStr::new("run"),
#[cfg(not(debug_assertions))]
OsStr::new("--release"),
OsStr::new("--quiet"),
OsStr::new("--bin"),
name.as_ref(),
OsStr::new("--"),
].into_iter()
.map(OsString::from)
.collect(),
..Self::default()
}
pub fn cargo_binary<S: AsRef<OsStr>>(name: S) -> Result<Self, failure::Error> {
let cargo = cargo::Cargo::new().build().bin(name).current_release();
let bins: Vec<_> = cargo.exec()?.filter_map(|m| filenames(m, "bin")).collect();
assert_eq!(bins.len(), 1);
let bin = bins[0].as_str();
let cmd = Self {
cmd: vec![bin].into_iter().map(OsString::from).collect(),
env: Environment::inherit(),
current_dir: None,
expect_success: Some(true),
expect_exit_code: None,
expect_output: vec![],
stdin_contents: None,
};
Ok(cmd)
}

/// Run a specific example of the current crate.
///
/// Defaults to asserting _successful_ execution.
pub fn example<S: AsRef<OsStr>>(name: S) -> Self {
Assert {
cmd: vec![
OsStr::new("cargo"),
OsStr::new("run"),
#[cfg(not(debug_assertions))]
OsStr::new("--release"),
OsStr::new("--quiet"),
OsStr::new("--example"),
name.as_ref(),
OsStr::new("--"),
].into_iter()
.map(OsString::from)
.collect(),
..Self::default()
}
pub fn example<S: AsRef<OsStr>>(name: S) -> Result<Self, failure::Error> {
let cargo = cargo::Cargo::new().build().example(name).current_release();
let bins: Vec<_> = cargo
.exec()?
.filter_map(|m| filenames(m, "example"))
.collect();
assert_eq!(bins.len(), 1);
let bin = bins[0].as_str();
let cmd = Self {
cmd: vec![bin].into_iter().map(OsString::from).collect(),
env: Environment::inherit(),
current_dir: None,
expect_success: Some(true),
expect_exit_code: None,
expect_output: vec![],
stdin_contents: None,
};
Ok(cmd)
}

/// Run a custom command.
Expand All @@ -116,7 +136,12 @@ impl Assert {
pub fn command<S: AsRef<OsStr>>(cmd: &[S]) -> Self {
Assert {
cmd: cmd.into_iter().map(OsString::from).collect(),
..Self::default()
env: Environment::inherit(),
current_dir: None,
expect_success: Some(true),
expect_exit_code: None,
expect_output: vec![],
stdin_contents: None,
}
}

Expand Down Expand Up @@ -559,52 +584,6 @@ mod test {
Assert::command(&["printenv"])
}

#[test]
fn main_binary_default_uses_active_profile() {
let assert = Assert::main_binary();

let expected = if cfg!(debug_assertions) {
OsString::from("cargo run --quiet -- ")
} else {
OsString::from("cargo run --release --quiet -- ")
};

assert_eq!(
expected,
assert
.cmd
.into_iter()
.fold(OsString::from(""), |mut cmd, token| {
cmd.push(token);
cmd.push(" ");
cmd
})
);
}

#[test]
fn cargo_binary_default_uses_active_profile() {
let assert = Assert::cargo_binary("hello");

let expected = if cfg!(debug_assertions) {
OsString::from("cargo run --quiet --bin hello -- ")
} else {
OsString::from("cargo run --release --quiet --bin hello -- ")
};

assert_eq!(
expected,
assert
.cmd
.into_iter()
.fold(OsString::from(""), |mut cmd, token| {
cmd.push(token);
cmd.push(" ");
cmd
})
);
}

#[test]
fn take_ownership() {
let x = Environment::inherit();
Expand Down
36 changes: 36 additions & 0 deletions src/bin/bin_fixture.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
extern crate failure;

use std::env;
use std::io;
use std::io::Write;
use std::process;

use failure::ResultExt;

fn run() -> Result<(), failure::Error> {
if let Ok(text) = env::var("stdout") {
println!("{}", text);
}
if let Ok(text) = env::var("stderr") {
eprintln!("{}", text);
}

let code = env::var("exit")
.ok()
.map(|v| v.parse::<i32>())
.map_or(Ok(None), |r| r.map(Some))
.context("Invalid exit code")?
.unwrap_or(0);
process::exit(code);
}

fn main() {
let code = match run() {
Ok(_) => 0,
Err(ref e) => {
write!(&mut io::stderr(), "{}", e).expect("writing to stderr won't fail");
1
}
};
process::exit(code);
}
Loading