diff --git a/examples/raw_upload/src/main.rs b/examples/raw_upload/src/main.rs index 38766f61..8005f03d 100644 --- a/examples/raw_upload/src/main.rs +++ b/examples/raw_upload/src/main.rs @@ -3,14 +3,14 @@ extern crate rocket; -use std::io; +#[cfg(test)] mod tests; +use std::io; use rocket::Data; -use rocket::response::content::Plain; #[post("/upload", format = "text/plain", data = "")] -fn upload(data: Data) -> io::Result> { - data.stream_to_file("/tmp/upload.txt").map(|n| Plain(n.to_string())) +fn upload(data: Data) -> io::Result { + data.stream_to_file("/tmp/upload.txt").map(|n| n.to_string()) } #[get("/")] @@ -18,6 +18,10 @@ fn index() -> &'static str { "Upload your text files by POSTing them to /upload." } -fn main() { - rocket::ignite().mount("/", routes![index, upload]).launch(); +fn rocket() -> rocket::Rocket { + rocket::ignite().mount("/", routes![index, upload]) +} + +fn main() { + rocket().launch(); } diff --git a/examples/raw_upload/src/tests.rs b/examples/raw_upload/src/tests.rs new file mode 100644 index 00000000..ebc2e2f9 --- /dev/null +++ b/examples/raw_upload/src/tests.rs @@ -0,0 +1,36 @@ +use rocket::testing::MockRequest; +use rocket::http::{Status, ContentType}; +use rocket::http::Method::*; + +use std::io::Read; +use std::fs::File; + +#[test] +fn test_index() { + let rocket = super::rocket(); + let mut req = MockRequest::new(Get, "/"); + let mut res = req.dispatch_with(&rocket); + + assert_eq!(res.body_string(), Some(super::index().to_string())); +} + +#[test] +fn test_raw_upload() { + const UPLOAD_CONTENTS: &str = "Hey! I'm going to be uploaded. :D Yay!"; + + let rocket = super::rocket(); + let mut req = MockRequest::new(Post, "/upload") + .header(ContentType::Plain) + .body(UPLOAD_CONTENTS); + + // Do the upload. Make sure we get the expected results. + let mut res = req.dispatch_with(&rocket); + assert_eq!(res.status(), Status::Ok); + assert_eq!(res.body_string(), Some(UPLOAD_CONTENTS.len().to_string())); + + // Ensure we find the body in the /tmp/upload.txt file. + let mut file_contents = String::new(); + let mut file = File::open("/tmp/upload.txt").expect("open upload.txt file"); + file.read_to_string(&mut file_contents).expect("read upload.txt"); + assert_eq!(&file_contents, UPLOAD_CONTENTS); +}