diff options
author | Guillaume Pasquet <dev@etenil.net> | 2022-02-20 09:30:46 +0000 |
---|---|---|
committer | Guillaume Pasquet <dev@etenil.net> | 2022-02-20 09:30:46 +0000 |
commit | f69d2801069850b48c6424b50d0107799d56e2f8 (patch) | |
tree | eaba8081a01fa69bcb23576daf6b3178e8c13765 | |
parent | ca6531ed467d1772f7b4afed05a69d666b071c14 (diff) |
Handle errors (more) gracefully
-rw-r--r-- | .gitignore | 1 | ||||
-rw-r--r-- | Cargo.lock | 2 | ||||
-rw-r--r-- | Cargo.toml | 4 | ||||
-rw-r--r-- | src/barbfile.rs | 2 | ||||
-rw-r--r-- | src/executor.rs | 44 | ||||
-rw-r--r-- | src/main.rs | 17 | ||||
-rw-r--r-- | test_api/test_api.py | 19 | ||||
-rw-r--r-- | test_api/test_api_404_error.barb | 2 | ||||
-rw-r--r-- | test_api/test_api_500_error.barb | 2 | ||||
-rw-r--r-- | test_api/test_api_get.barb | 1 | ||||
-rw-r--r-- | test_api/test_api_nonexist_error.barb | 2 | ||||
-rw-r--r-- | test_api/test_api_post.barb | 3 |
12 files changed, 86 insertions, 13 deletions
@@ -1 +1,2 @@ /target +.venv @@ -36,7 +36,7 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "barb" -version = "0.1.2" +version = "0.1.3" dependencies = [ "clap 3.0.14", "jsonformat", @@ -1,7 +1,7 @@ [package] name = "barb" -version = "0.1.2" -edition = "2018" +version = "0.1.3" +edition = "2021" license = "GPL-3.0-or-later" description = "Command-line tool to perform file-based HTTP(s) requests." repository = "https://gitlab.com/guillaume54/barb" diff --git a/src/barbfile.rs b/src/barbfile.rs index a039253..1a17796 100644 --- a/src/barbfile.rs +++ b/src/barbfile.rs @@ -158,7 +158,7 @@ impl FromStr for BarbFile { } if let Some(_) = line.find(':') { - headers.push(decode_header(line).unwrap()); + headers.push(decode_header(line).map_err(|_| BarbParseError {})?); } if let None = filter { 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")); + } } diff --git a/src/main.rs b/src/main.rs index 4ddc809..f3891ad 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,14 +50,13 @@ impl Args { } } -fn run_file(args: &Args, executor: &mut Executor, file_name: &String) { +fn run_file(args: &Args, executor: &mut Executor, file_name: &String) -> Result<(), String> { let bfile = BarbFile::from_str( fs::read_to_string(file_name.as_str()) - .expect("Failed to read file") + .map_err(|_| format!("Failed to read file '{}'", file_name))? .as_str(), - ) - .expect("Failed to parse file"); - let response = executor.execute(bfile, args.req_headers()).unwrap(); + ).map_err(|_| format!("Failed to parse file '{}'", file_name))?; + let response = executor.execute(bfile, args.req_headers())?; if args.print_headers() { println!("{} {}", response.status(), response.status_text()); @@ -65,6 +64,7 @@ fn run_file(args: &Args, executor: &mut Executor, file_name: &String) { println!( "{}: {}", header_name, + // Header is guaranteed to exist response.header(header_name.as_str()).unwrap() ); } @@ -82,6 +82,8 @@ fn run_file(args: &Args, executor: &mut Executor, file_name: &String) { } ); } + + Ok(()) } fn main() { @@ -90,6 +92,9 @@ fn main() { let mut executor = Executor::new(Context::new(env::vars())); for file in args.files_iter() { - run_file(&args, &mut executor, &file); + match run_file(&args, &mut executor, &file) { + Ok(()) => (), + Err(err) => println!("{}", err) + } } } diff --git a/test_api/test_api.py b/test_api/test_api.py new file mode 100644 index 0000000..bd8303d --- /dev/null +++ b/test_api/test_api.py @@ -0,0 +1,19 @@ +from bottle import get, post, run, HTTPError + +@get("/") +def get_root(): + return {"status": "OK"} + +@post("/") +def post_root(): + return {"status": "SUCCESS"} + +@get("/errors/404") +def error_404(): + raise HTTPError(404, body={"error": "no exist"}) + +@get("/errors/500") +def error_500(): + raise HTTPError(500, body={"error": "server error"}) + +run(host="localhost", port=8080) diff --git a/test_api/test_api_404_error.barb b/test_api/test_api_404_error.barb new file mode 100644 index 0000000..d2c9809 --- /dev/null +++ b/test_api/test_api_404_error.barb @@ -0,0 +1,2 @@ +#GET^http://localhost:8080/errors/404 + diff --git a/test_api/test_api_500_error.barb b/test_api/test_api_500_error.barb new file mode 100644 index 0000000..1017ab2 --- /dev/null +++ b/test_api/test_api_500_error.barb @@ -0,0 +1,2 @@ +#GET^http://localhost:8080/errors/500 + diff --git a/test_api/test_api_get.barb b/test_api/test_api_get.barb new file mode 100644 index 0000000..6bdf592 --- /dev/null +++ b/test_api/test_api_get.barb @@ -0,0 +1 @@ +#GET^http://localhost:8080/ diff --git a/test_api/test_api_nonexist_error.barb b/test_api/test_api_nonexist_error.barb new file mode 100644 index 0000000..9f95a60 --- /dev/null +++ b/test_api/test_api_nonexist_error.barb @@ -0,0 +1,2 @@ +#GET^http://localhost:60000/ + diff --git a/test_api/test_api_post.barb b/test_api/test_api_post.barb new file mode 100644 index 0000000..2f905b1 --- /dev/null +++ b/test_api/test_api_post.barb @@ -0,0 +1,3 @@ +#POST^http://localhost:8080/ + +{"value": 1234} |