diff options
Diffstat (limited to 'src/executor.rs')
-rw-r--r-- | src/executor.rs | 66 |
1 files changed, 53 insertions, 13 deletions
diff --git a/src/executor.rs b/src/executor.rs index d9bfaee..189df6f 100644 --- a/src/executor.rs +++ b/src/executor.rs @@ -1,20 +1,26 @@ use crate::barbfile::{BarbFile, Header}; use std::collections::HashMap; -use std::env; use ureq; -struct Context { +pub struct Context { vars: HashMap<String, String>, } impl Context { - pub fn new() -> Context { - let mut vars = HashMap::new(); - vars.extend(env::vars()); - + pub fn new<I>(vars: I) -> Context + where + I: Iterator<Item = (String, String)>, + { + let mut toto = HashMap::new(); + toto.extend(vars); + + Context { vars: toto } + } + + pub fn empty() -> Context { Context { - vars + vars: HashMap::new() } } @@ -41,25 +47,32 @@ impl Context { } pub struct Executor { - context: Context + context: Context, } impl Executor { - pub fn new() -> Executor { + pub fn new(context: Context) -> Executor { Executor { - context: Context::new() + context } } pub fn execute(&mut self, bfile: BarbFile) -> Result<ureq::Response, String> { let mut req = ureq::request( bfile.method_as_string().as_str(), - self.context.substitute(&bfile.url()).as_str() + self.context.substitute(&bfile.url()).as_str(), ); for header in bfile.headers() { - req = req.set(header.name(), self.context.substitute(header.value()).as_str()); - println!("{} {}", header.name(), self.context.substitute(header.value())); + req = req.set( + header.name(), + self.context.substitute(header.value()).as_str(), + ); + println!( + "{} {}", + header.name(), + self.context.substitute(header.value()) + ); } match bfile.method().takes_body() { @@ -74,3 +87,30 @@ impl Executor { } // TODO: tests +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_context_key_str() { + let ctx = Context::empty(); + assert_eq!(ctx.key_str(&String::from("foo")), String::from("{foo}")); + } + + #[test] + fn test_context_substitute() { + let vars: Vec<(String, String)> = vec![ + (String::from("foo"), String::from("bar")), + (String::from("bar"), String::from("baz")), + ]; + let ctx = Context::new(vars.into_iter()); + assert_eq!( + ctx.substitute(&String::from("blah blah {foo} blah")), + String::from("blah blah bar blah") + ); + assert_eq!( + ctx.substitute(&String::from("blah {foo} {bar} blah")), + String::from("blah bar baz blah") + ); + } +} |