mirror of https://github.com/rwf2/Rocket.git
Add tests for the content_types example
This commit is contained in:
parent
f43f77dbfc
commit
e91dd2e137
|
@ -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"] }
|
||||
|
|
|
@ -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!("<p>This server only supports JSON requests, not '{}'.</p>",
|
||||
request.content_type())
|
||||
} else {
|
||||
format!("<p>Sorry, '{}' is not a valid path!</p>
|
||||
<p>Try visiting /hello/<name>/<age> instead.</p>",
|
||||
request.uri())
|
||||
format!("<p>Sorry, '{}' is an invalid path! Try \
|
||||
/hello/<name>/<age> instead.</p>",
|
||||
request.uri())
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
rocket::ignite()
|
||||
.mount("/hello", routes![hello]).catch(errors![not_found])
|
||||
.mount("/hello", routes![hello])
|
||||
.catch(errors![not_found])
|
||||
.launch();
|
||||
}
|
||||
|
|
|
@ -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/<name>/<age> instead.</p>";
|
||||
test("/unknown", ContentType::JSON, Status::NotFound, body.to_string());
|
||||
}
|
Loading…
Reference in New Issue