diff options
Diffstat (limited to 'src/executor.rs')
-rw-r--r-- | src/executor.rs | 44 |
1 files changed, 41 insertions, 3 deletions
diff --git a/src/executor.rs b/src/executor.rs index b5f8e96..4930c5f 100644 --- a/src/executor.rs +++ b/src/executor.rs @@ -2,6 +2,7 @@ use crate::barbfile::BarbFile; use std::collections::HashMap; use ureq; +use ureq::Error as UreqError; pub struct Context { vars: HashMap<String, String>, @@ -18,6 +19,7 @@ impl Context { Context { vars: toto } } + #[cfg(test)] pub fn empty() -> Context { Context { vars: HashMap::new(), @@ -55,7 +57,7 @@ impl Executor { Executor { context } } - pub fn execute(&mut self, bfile: BarbFile, print_headers: bool) -> Result<ureq::Response, String> { + fn make_req(&self, bfile: &BarbFile, print_headers: bool) -> ureq::Request { let mut req = ureq::request( bfile.method_as_string().as_str(), self.context.substitute(&bfile.url()).as_str(), @@ -74,15 +76,27 @@ impl Executor { ); } } + req + } - match bfile.method().takes_body() { + fn run(&self, bfile: &BarbFile, req: ureq::Request) -> Result<ureq::Response, String> { + let resp = match bfile.method().takes_body() { true => match bfile.body() { Some(body) => req.send_string(body.as_str()), None => req.call(), }, false => req.call(), + }; + + match resp { + Ok(resp) => Ok(resp), + Err(UreqError::Status(_, resp)) => Ok(resp), + Err(UreqError::Transport(transp)) => Err(String::from(transp.to_string())) } - .map_err(|_| String::from("Error")) + } + + pub fn execute(&mut self, bfile: BarbFile, print_headers: bool) -> Result<ureq::Response, String> { + self.run(&bfile, self.make_req(&bfile, print_headers)) } } @@ -90,6 +104,7 @@ impl Executor { #[cfg(test)] mod tests { use super::*; + use std::str::FromStr; #[test] fn test_context_key_str() { @@ -113,4 +128,27 @@ mod tests { String::from("blah bar baz blah") ); } + + #[test] + fn test_make_req_simple_get() { + let executor = Executor::new(Context::empty()); + let bfile = BarbFile::from_str("#GET^http://foo.bar\n\n").unwrap(); + let req = executor.make_req(&bfile, false); + + assert_eq!(req.url(), "http://foo.bar"); + assert_eq!(req.method(), "GET"); + } + + #[test] + fn test_make_req_simple_headers() { + let executor = Executor::new(Context::empty()); + let bfile = BarbFile::from_str( + "#GET^http://foo.bar\n#Foo: Bar\n#Bar: Baz\n\n" + ).unwrap(); + let req = executor.make_req(&bfile, false); + + assert_eq!(req.header_names(), vec![String::from("foo"), String::from("bar")]); + assert_eq!(req.header("foo"), Some("Bar")); + assert_eq!(req.header("bar"), Some("Baz")); + } } |