Add tests for the content_types example

This commit is contained in:
Seth Lopez 2016-12-29 21:53:48 -05:00
parent f43f77dbfc
commit e91dd2e137
3 changed files with 53 additions and 5 deletions

View File

@ -10,3 +10,6 @@ rocket_codegen = { path = "../../codegen" }
serde = "0.8" serde = "0.8"
serde_json = "0.8" serde_json = "0.8"
serde_derive = "0.8" serde_derive = "0.8"
[dev-dependencies]
rocket = { path = "../../lib", features = ["testing"] }

View File

@ -3,7 +3,11 @@
extern crate rocket; extern crate rocket;
extern crate serde_json; 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::{Request, Error};
use rocket::http::ContentType; use rocket::http::ContentType;
@ -34,14 +38,15 @@ fn not_found(_: Error, request: &Request) -> String {
format!("<p>This server only supports JSON requests, not '{}'.</p>", format!("<p>This server only supports JSON requests, not '{}'.</p>",
request.content_type()) request.content_type())
} else { } else {
format!("<p>Sorry, '{}' is not a valid path!</p> format!("<p>Sorry, '{}' is an invalid path! Try \
<p>Try visiting /hello/&lt;name&gt;/&lt;age&gt; instead.</p>", /hello/&lt;name&gt;/&lt;age&gt; instead.</p>",
request.uri()) request.uri())
} }
} }
fn main() { fn main() {
rocket::ignite() rocket::ignite()
.mount("/hello", routes![hello]).catch(errors![not_found]) .mount("/hello", routes![hello])
.catch(errors![not_found])
.launch(); .launch();
} }

View File

@ -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!("<p>This server only supports JSON requests, not '{}'.</p>",
ContentType::HTML);
test("/hello/Michael/80", ContentType::HTML, Status::NotFound, body);
}
#[test]
fn test_404() {
let body = "<p>Sorry, '/unknown' is an invalid path! Try \
/hello/&lt;name&gt;/&lt;age&gt; instead.</p>";
test("/unknown", ContentType::JSON, Status::NotFound, body.to_string());
}