From 5e3026237866ce7a964e9b91c94624bc80e8f486 Mon Sep 17 00:00:00 2001 From: Reilly Tucker Siemens Date: Sun, 1 Jan 2017 22:55:08 -0800 Subject: [PATCH] Add tests for errors example. --- examples/errors/Cargo.toml | 3 +++ examples/errors/src/main.rs | 3 +++ examples/errors/src/tests.rs | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 examples/errors/src/tests.rs diff --git a/examples/errors/Cargo.toml b/examples/errors/Cargo.toml index 73007681..a6c937d1 100644 --- a/examples/errors/Cargo.toml +++ b/examples/errors/Cargo.toml @@ -7,3 +7,6 @@ workspace = "../../" [dependencies] rocket = { path = "../../lib" } rocket_codegen = { path = "../../codegen" } + +[dev-dependencies] +rocket = { path = "../../lib", features = ["testing"] } diff --git a/examples/errors/src/main.rs b/examples/errors/src/main.rs index 90738ad5..f4670c9d 100644 --- a/examples/errors/src/main.rs +++ b/examples/errors/src/main.rs @@ -3,6 +3,9 @@ extern crate rocket; +#[cfg(test)] +mod tests; + #[get("/hello//")] fn hello(name: &str, age: i8) -> String { format!("Hello, {} year old named {}!", age, name) diff --git a/examples/errors/src/tests.rs b/examples/errors/src/tests.rs new file mode 100644 index 00000000..4cfd4567 --- /dev/null +++ b/examples/errors/src/tests.rs @@ -0,0 +1,32 @@ +use super::rocket; +use rocket::testing::MockRequest; +use rocket::http::{Method, Status}; + +fn test(uri: &str, status: Status, body: String) { + let rocket = rocket::ignite() + .mount("/", routes![super::hello]) + .catch(errors![super::not_found]); + let mut req = MockRequest::new(Method::Get, uri); + let mut response = req.dispatch_with(&rocket); + + assert_eq!(response.status(), status); + assert_eq!(response.body().and_then(|b| b.into_string()), Some(body)); +} + +#[test] +fn test_hello() { + let (name, age) = ("Arthur", 42); + let uri = format!("/hello/{}/{}", name, age); + test(&uri, Status::Ok, format!("Hello, {} year old named {}!", age, name)); +} + +#[test] +fn test_hello_invalid_age() { + for &(name, age) in &[("Ford", -129), ("Trillian", 128)] { + let uri = format!("/hello/{}/{}", name, age); + let body = format!("

Sorry, but '{}' is not a valid path!

+

Try visiting /hello/<name>/<age> instead.

", + uri); + test(&uri, Status::NotFound, body); + } +}