From eb5296b3300fc1930fda98f528304f7d467df069 Mon Sep 17 00:00:00 2001 From: Sevag Hanssian Date: Wed, 4 Oct 2017 15:44:21 -0400 Subject: [PATCH] Adds stdin() function This commit adds an stdin() function to supply stdin to the function. --- src/assert.rs | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/src/assert.rs b/src/assert.rs index da769c9..cb4125c 100644 --- a/src/assert.rs +++ b/src/assert.rs @@ -1,7 +1,8 @@ use std::default; -use std::process::Command; +use std::process::{Command, Stdio}; use std::path::PathBuf; use std::vec::Vec; +use std::io::Write; use errors::*; use output::{OutputAssertion, OutputKind}; @@ -14,6 +15,7 @@ pub struct Assert { expect_success: Option, expect_exit_code: Option, expect_output: Vec, + stdin_contents: Option, } impl default::Default for Assert { @@ -28,6 +30,7 @@ impl default::Default for Assert { expect_success: Some(true), expect_exit_code: None, expect_output: vec![], + stdin_contents: None, } } } @@ -87,6 +90,23 @@ impl Assert { self } + /// Add stdin to the command. + /// + /// # Examples + /// + /// ```rust + /// extern crate assert_cli; + /// + /// assert_cli::Assert::command(&["cat"]) + /// .stdin("42") + /// .stdout().contains("42") + /// .unwrap(); + /// ``` + pub fn stdin(mut self, contents: &str) -> Self { + self.stdin_contents = Some(String::from(contents)); + self + } + /// Sets the working directory for the command. /// /// # Examples @@ -232,12 +252,22 @@ impl Assert { let cmd = &self.cmd[0]; let args: Vec<_> = self.cmd.iter().skip(1).collect(); let mut command = Command::new(cmd); + let command = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); let command = command.args(&args); let command = match self.current_dir { Some(ref dir) => command.current_dir(dir), None => command, }; - let output = command.output()?; + + let mut spawned = command.spawn()?; + + if let Some(ref contents) = self.stdin_contents { + spawned.stdin.as_mut().expect("Couldn't get mut ref to command stdin").write_all(contents.as_bytes())?; + } + let output = spawned.wait_with_output()?; if let Some(expect_success) = self.expect_success { if expect_success != output.status.success() {