diff --git a/examples/content_types/Cargo.toml b/examples/content_types/Cargo.toml index 973be5bd..cd4388f1 100644 --- a/examples/content_types/Cargo.toml +++ b/examples/content_types/Cargo.toml @@ -10,3 +10,6 @@ rocket_codegen = { path = "../../codegen" } serde = "0.8" serde_json = "0.8" serde_derive = "0.8" + +[dev-dependencies] +rocket = { path = "../../lib", features = ["testing"] } diff --git a/examples/content_types/src/main.rs b/examples/content_types/src/main.rs index d33f789b..84b2b0ca 100644 --- a/examples/content_types/src/main.rs +++ b/examples/content_types/src/main.rs @@ -3,7 +3,11 @@ extern crate rocket; extern crate serde_json; -#[macro_use] extern crate serde_derive; +#[macro_use] +extern crate serde_derive; + +#[cfg(test)] +mod tests; use rocket::{Request, Error}; use rocket::http::ContentType; @@ -34,14 +38,15 @@ fn not_found(_: Error, request: &Request) -> String { format!("

This server only supports JSON requests, not '{}'.

", request.content_type()) } else { - format!("

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

-

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

", - request.uri()) + format!("

Sorry, '{}' is an invalid path! Try \ + /hello/<name>/<age> instead.

", + request.uri()) } } fn main() { rocket::ignite() - .mount("/hello", routes![hello]).catch(errors![not_found]) + .mount("/hello", routes![hello]) + .catch(errors![not_found]) .launch(); } diff --git a/examples/content_types/src/tests.rs b/examples/content_types/src/tests.rs new file mode 100644 index 00000000..b7b0f254 --- /dev/null +++ b/examples/content_types/src/tests.rs @@ -0,0 +1,40 @@ +use super::rocket; +use super::serde_json; +use super::Person; +use rocket::http::{ContentType, Method, Status}; +use rocket::testing::MockRequest; + +fn test(uri: &str, content_type: ContentType, status: Status, body: String) { + let rocket = rocket::ignite() + .mount("/hello", routes![super::hello]) + .catch(errors![super::not_found]); + let mut request = MockRequest::new(Method::Get, uri).header(content_type); + let mut response = request.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 person = Person { + name: "Michael".to_string(), + age: 80, + }; + let body = serde_json::to_string(&person).unwrap(); + test("/hello/Michael/80", ContentType::JSON, Status::Ok, body); +} + +#[test] +fn test_hello_invalid_content_type() { + let body = format!("

This server only supports JSON requests, not '{}'.

", + ContentType::HTML); + test("/hello/Michael/80", ContentType::HTML, Status::NotFound, body); +} + +#[test] +fn test_404() { + let body = "

Sorry, '/unknown' is an invalid path! Try \ + /hello/<name>/<age> instead.

"; + test("/unknown", ContentType::JSON, Status::NotFound, body.to_string()); +}