From a482d458f4fb34038d5dde5bd79dbaa387594b1f Mon Sep 17 00:00:00 2001 From: sgoudham Date: Tue, 3 May 2022 00:07:50 +0100 Subject: [PATCH] [TEM #2] - Add FileReader trait for testing --- src/utils.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/utils.rs diff --git a/src/utils.rs b/src/utils.rs new file mode 100644 index 0000000..5b32eee --- /dev/null +++ b/src/utils.rs @@ -0,0 +1,50 @@ +use std::collections::HashMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Error, Result}; + +pub(crate) trait FileReader { + fn read_to_string(&self, file_name: &Path, template_text: &str) -> Result; +} + +#[derive(PartialEq, Debug, Clone, Default)] +pub(crate) struct SystemFileReader; + +#[derive(PartialEq, Debug, Clone, Default)] +pub(crate) struct TestFileReader { + pub(crate) captured_contents: HashMap, +} + +impl FileReader for SystemFileReader { + fn read_to_string(&self, file_name: &Path, template_text: &str) -> Result { + fs::read_to_string(file_name).with_context(|| { + format!( + "Could not read template file {} ({})", + template_text, + file_name.display(), + ) + }) + } +} + +impl From> for TestFileReader { + fn from(map: HashMap) -> Self { + TestFileReader { + captured_contents: map, + } + } +} + +impl FileReader for TestFileReader { + fn read_to_string(&self, file_name: &Path, template_text: &str) -> Result { + match self.captured_contents.get(file_name) { + Some(file_contents) => Ok(file_contents.to_string()), + None => Err(Error::msg(format!( + "Could not read template file {} ({})", + template_text, + file_name.display(), + ))), + } + } +} \ No newline at end of file