Skip to content

Iterative Improvements #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 9, 2021
Merged
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ toml_edit = { version = "0.8", features = ["serde"] }
escargot = { version = "0.5.6", optional = true }

normalize-line-endings = "0.3.0"
os_pipe = "0.9"
wait-timeout = "0.2.0"
difflib = { version = "0.4", optional = true }
tempfile = { version = "3.0", optional = true }
Expand Down
6 changes: 4 additions & 2 deletions src/cargo.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Interact with `cargo`

/// The absolute path to a binary target's executable.
///
/// The `bin_target_name` is the name of the binary
Expand Down Expand Up @@ -29,7 +31,7 @@ pub use examples::{compile_example, compile_examples};
pub(crate) mod examples {
/// Prepare an example for testing
///
/// Unlike [`trycmd::cargo_bin!`], this does not inherit all of the current compiler settings. It
/// Unlike [`cargo_bin!`][crate::cargo_bin!], this does not inherit all of the current compiler settings. It
/// will match the current target and profile but will not get feature flags. Pass those arguments
/// to the compiler via `args`.
///
Expand Down Expand Up @@ -83,7 +85,7 @@ pub(crate) mod examples {

/// Prepare all examples for testing
///
/// Unlike [`trycmd::cargo_bin!`], this does not inherit all of the current compiler settings. It
/// Unlike [`cargo_bin!`][crate::cargo_bin!], this does not inherit all of the current compiler settings. It
/// will match the current target and profile but will not get feature flags. Pass those arguments
/// to the compiler via `args`.
///
Expand Down
1 change: 1 addition & 0 deletions src/cases.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/// Entry point for running tests
#[derive(Debug, Default)]
pub struct TestCases {
runner: std::cell::RefCell<crate::RunnerSpec>,
Expand Down
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@
//! ```
//! To filter the tests to those with `name1`, `name2`, etc in their file names.

// Doesn't distinguish between incidental sharing vs essential sharing
#![allow(clippy::branches_sharing_code)]

pub mod cargo;
pub mod schema;

Expand Down
3 changes: 0 additions & 3 deletions src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ impl Default for Runner {

#[derive(Debug)]
pub(crate) struct Case {
pub(crate) name: String,
pub(crate) path: std::path::PathBuf,
pub(crate) expected: Option<crate::CommandStatus>,
pub(crate) timeout: Option<std::time::Duration>,
Expand All @@ -89,9 +88,7 @@ pub(crate) struct Case {

impl Case {
pub(crate) fn with_error(path: std::path::PathBuf, error: impl std::fmt::Display) -> Self {
let name = path.display().to_string();
Self {
name,
path,
expected: None,
timeout: None,
Expand Down
79 changes: 68 additions & 11 deletions src/schema.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
/// `cmd.toml` Schema
///
/// [`TryCmd`] is the top-level item in the `cmd.toml` files.
//! `cmd.toml` Schema
//!
//! [`TryCmd`] is the top-level item in the `cmd.toml` files.

use std::collections::BTreeMap;
use std::io::prelude::*;

/// Top-level data in `cmd.toml` files
#[derive(Clone, Default, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
Expand All @@ -14,6 +16,8 @@ pub struct TryCmd {
pub(crate) fs: Filesystem,
#[serde(default)]
pub(crate) env: Env,
#[serde(default)]
pub(crate) stderr_to_stdout: bool,
pub(crate) status: Option<CommandStatus>,
#[serde(default)]
pub(crate) binary: bool,
Expand Down Expand Up @@ -109,11 +113,35 @@ impl TryCmd {
cwd: Option<&std::path::Path>,
) -> Result<std::process::Output, String> {
let mut cmd = self.to_command(cwd)?;
cmd.stdin(std::process::Stdio::piped());
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
let child = cmd.spawn().map_err(|e| e.to_string())?;
crate::wait_with_input_output(child, stdin, self.timeout).map_err(|e| e.to_string())

if self.stderr_to_stdout {
cmd.stdin(std::process::Stdio::piped());
let (mut reader, writer) = os_pipe::pipe().map_err(|e| e.to_string())?;
let writer_clone = writer.try_clone().map_err(|e| e.to_string())?;
cmd.stdout(writer);
cmd.stderr(writer_clone);
let child = cmd.spawn().map_err(|e| e.to_string())?;

// Avoid a deadlock! This parent process is still holding open pipe
// writers (inside the Command object), and we have to close those
// before we read. Here we do this by dropping the Command object.
drop(cmd);

let mut output = crate::wait_with_input_output(child, stdin, self.timeout)
.map_err(|e| e.to_string())?;
assert!(output.stdout.is_empty());
assert!(output.stderr.is_empty());
reader
.read_to_end(&mut output.stdout)
.map_err(|e| e.to_string())?;
Ok(output)
} else {
cmd.stdin(std::process::Stdio::piped());
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
let child = cmd.spawn().map_err(|e| e.to_string())?;
crate::wait_with_input_output(child, stdin, self.timeout).map_err(|e| e.to_string())
}
}

pub(crate) fn status(&self) -> CommandStatus {
Expand All @@ -125,14 +153,24 @@ impl TryCmd {
}

fn parse_trycmd(s: &str) -> Result<Self, String> {
let mut env = Env::default();

let mut iter = shlex::Shlex::new(s.trim());
let bin = iter
.next()
.ok_or_else(|| String::from("No bin specified"))?;
let bin = loop {
let next = iter
.next()
.ok_or_else(|| String::from("No bin specified"))?;
if let Some((key, value)) = next.split_once('=') {
env.add.insert(key.to_owned(), value.to_owned());
} else {
break next;
}
};
let args = Args::Split(iter.collect());
Ok(Self {
bin: Some(Bin::Name(bin)),
args: Some(args),
env,
..Default::default()
})
}
Expand Down Expand Up @@ -377,6 +415,25 @@ mod test {
assert_eq!(expected, actual);
}

#[test]
fn parse_trycmd_env() {
let expected = TryCmd {
bin: Some(Bin::Name("cmd".into())),
args: Some(Args::default()),
env: Env {
add: IntoIterator::into_iter([
("KEY1".into(), "VALUE1".into()),
("KEY2".into(), "VALUE2 with space".into()),
])
.collect(),
..Default::default()
},
..Default::default()
};
let actual = TryCmd::parse_trycmd("KEY1=VALUE1 KEY2='VALUE2 with space' cmd").unwrap();
assert_eq!(expected, actual);
}

#[test]
fn parse_toml_minimal() {
let expected = TryCmd {
Expand Down
42 changes: 12 additions & 30 deletions src/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,25 +56,17 @@ impl RunnerSpec {
for path in paths {
match path {
Ok(path) => {
if let Some(name) = get_name(&path) {
cases.insert(
path.clone(),
crate::Case {
name: name.to_owned(),
path,
expected: spec.expected,
default_bin: self.default_bin.clone(),
timeout: self.timeout,
env: self.env.clone(),
error: None,
},
);
} else {
cases.insert(
path.clone(),
crate::Case::with_error(path, "path has no name"),
);
}
cases.insert(
path.clone(),
crate::Case {
path,
expected: spec.expected,
default_bin: self.default_bin.clone(),
timeout: self.timeout,
env: self.env.clone(),
error: None,
},
);
}
Err(err) => {
let path = err.path().to_owned();
Expand All @@ -91,12 +83,11 @@ impl RunnerSpec {
);
}
}
} else if let Some(name) = get_name(&spec.glob) {
} else {
let path = spec.glob.as_path();
cases.insert(
path.into(),
crate::Case {
name: name.into(),
path: path.into(),
expected: spec.expected,
default_bin: self.default_bin.clone(),
Expand All @@ -105,11 +96,6 @@ impl RunnerSpec {
error: None,
},
);
} else {
cases.insert(
spec.glob.clone(),
crate::Case::with_error(spec.glob.clone(), "path has no name"),
);
}
}

Expand Down Expand Up @@ -154,7 +140,3 @@ fn get_glob(path: &std::path::Path) -> Option<&str> {

None
}

fn get_name(path: &std::path::Path) -> Option<&str> {
path.file_name().and_then(|os| os.to_str())
}
4 changes: 4 additions & 0 deletions tests/cmd/schema.stdout
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@
}
]
},
"stderr-to-stdout": {
"default": false,
"type": "boolean"
},
"status": {
"anyOf": [
{
Expand Down
Empty file.
6 changes: 6 additions & 0 deletions tests/cmd/stderr-to-stdout.stdout
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Hello
World!

Goodnight
Moon!

12 changes: 12 additions & 0 deletions tests/cmd/stderr-to-stdout.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
bin.name = "bin-fixture"
stderr-to-stdout = true

[env.add]
stdout = """
Hello
World!
"""
stderr = """
Goodnight
Moon!
"""