From 7e84f2e6db1028f60193ecd40ee935fe629902cb Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sun, 20 Jan 2019 12:48:24 +0100 Subject: introcue stdin buffer for tests --- src/testutils.rs | 15 ++++++++++++++- src/utils/fileutil.rs | 21 ++++++++++++++------- 2 files changed, 28 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/testutils.rs b/src/testutils.rs index 308a793..7593f98 100644 --- a/src/testutils.rs +++ b/src/testutils.rs @@ -4,7 +4,8 @@ use std::path::PathBuf; use std::cell::RefCell; thread_local! { - pub static STDOUT_BUF: RefCell = RefCell::new(String::new()) + pub static STDOUT_BUF: RefCell = RefCell::new(String::new()); + pub static STDIN_BUF: RefCell = RefCell::new(String::new()); } use defaults; @@ -36,3 +37,15 @@ pub fn test_stdout_clear() -> String { result }) } + +pub fn test_stdin_write(text: &str) { + STDIN_BUF.with(|cell| cell.borrow_mut().push_str(&text)); +} + +pub fn test_stdin_clear() -> Vec { + STDIN_BUF.with(|cell| { + let result = cell.borrow().lines().map(|line| line.to_owned()).collect(); + *cell.borrow_mut() = String::new(); + result + }) +} diff --git a/src/utils/fileutil.rs b/src/utils/fileutil.rs index c60ac51..fca810e 100644 --- a/src/utils/fileutil.rs +++ b/src/utils/fileutil.rs @@ -53,12 +53,6 @@ pub fn read_lines_from_file(filepath: &Path) -> io::Result io::Result { - let stdin = std::io::stdin(); - let stdinlock = stdin.lock(); - read_single_char(stdinlock) -} - pub fn read_single_char(mut source: impl BufRead) -> io::Result { let mut buf = String::new(); source.read_line(&mut buf)?; @@ -66,13 +60,26 @@ pub fn read_single_char(mut source: impl BufRead) -> io::Result { buf.chars().next().ok_or_else(|| io::Error::new(io::ErrorKind::Other, "calendar has no path")) } +pub fn read_single_char_from_stdin() -> io::Result { + let stdin = std::io::stdin(); + let stdinlock = stdin.lock(); + read_single_char(stdinlock) +} + +#[cfg(not(test))] pub fn read_lines_from_stdin() -> io::Result> { let stdin = io::stdin(); let lines = stdin.lock().lines(); - lines.collect() } +#[cfg(test)] +pub fn read_lines_from_stdin() -> io::Result> { + use testutils; + let lines = testutils::test_stdin_clear(); + Ok(lines) +} + pub fn read_file_to_string(path: &Path) -> io::Result { let mut file = fs::File::open(&path)?; let mut contents = String::new(); -- cgit v1.2.3