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

Commit 875c4b1

Browse files
authored
Merge pull request #44 from sevagh/master
Add `stdin` function
2 parents 4240ee8 + eb5296b commit 875c4b1

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

src/assert.rs

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use std::default;
2-
use std::process::Command;
2+
use std::process::{Command, Stdio};
33
use std::path::PathBuf;
44
use std::vec::Vec;
5+
use std::io::Write;
56

67
use errors::*;
78
use output::{OutputAssertion, OutputKind};
@@ -14,6 +15,7 @@ pub struct Assert {
1415
expect_success: Option<bool>,
1516
expect_exit_code: Option<i32>,
1617
expect_output: Vec<OutputAssertion>,
18+
stdin_contents: Option<String>,
1719
}
1820

1921
impl default::Default for Assert {
@@ -28,6 +30,7 @@ impl default::Default for Assert {
2830
expect_success: Some(true),
2931
expect_exit_code: None,
3032
expect_output: vec![],
33+
stdin_contents: None,
3134
}
3235
}
3336
}
@@ -87,6 +90,23 @@ impl Assert {
8790
self
8891
}
8992

93+
/// Add stdin to the command.
94+
///
95+
/// # Examples
96+
///
97+
/// ```rust
98+
/// extern crate assert_cli;
99+
///
100+
/// assert_cli::Assert::command(&["cat"])
101+
/// .stdin("42")
102+
/// .stdout().contains("42")
103+
/// .unwrap();
104+
/// ```
105+
pub fn stdin(mut self, contents: &str) -> Self {
106+
self.stdin_contents = Some(String::from(contents));
107+
self
108+
}
109+
90110
/// Sets the working directory for the command.
91111
///
92112
/// # Examples
@@ -232,12 +252,22 @@ impl Assert {
232252
let cmd = &self.cmd[0];
233253
let args: Vec<_> = self.cmd.iter().skip(1).collect();
234254
let mut command = Command::new(cmd);
255+
let command = command
256+
.stdin(Stdio::piped())
257+
.stdout(Stdio::piped())
258+
.stderr(Stdio::piped());
235259
let command = command.args(&args);
236260
let command = match self.current_dir {
237261
Some(ref dir) => command.current_dir(dir),
238262
None => command,
239263
};
240-
let output = command.output()?;
264+
265+
let mut spawned = command.spawn()?;
266+
267+
if let Some(ref contents) = self.stdin_contents {
268+
spawned.stdin.as_mut().expect("Couldn't get mut ref to command stdin").write_all(contents.as_bytes())?;
269+
}
270+
let output = spawned.wait_with_output()?;
241271

242272
if let Some(expect_success) = self.expect_success {
243273
if expect_success != output.status.success() {

0 commit comments

Comments
 (0)