diff --git a/examples/stream/src/main.rs b/examples/stream/src/main.rs index 2dbd1079..34916be7 100644 --- a/examples/stream/src/main.rs +++ b/examples/stream/src/main.rs @@ -3,6 +3,8 @@ extern crate rocket; +#[cfg(test)] mod tests; + use rocket::response::{content, Stream}; use std::io::{self, repeat, Repeat, Read, Take}; @@ -10,6 +12,9 @@ use std::fs::File; type LimitedRepeat = Take; +// Generate this file using: head -c BYTES /dev/random > big_file.dat +const FILENAME: &'static str = "big_file.dat"; + #[get("/")] fn root() -> content::Plain> { content::Plain(Stream::from(repeat('a' as u8).take(25000))) @@ -17,11 +22,13 @@ fn root() -> content::Plain> { #[get("/big_file")] fn file() -> io::Result> { - // Generate this file using: head -c BYTES /dev/random > big_file.dat - const FILENAME: &'static str = "big_file.dat"; File::open(FILENAME).map(|file| Stream::from(file)) } -fn main() { - rocket::ignite().mount("/", routes![root, file]).launch(); +fn rocket() -> rocket::Rocket { + rocket::ignite().mount("/", routes![root, file]) +} + +fn main() { + rocket().launch(); } diff --git a/examples/stream/src/tests.rs b/examples/stream/src/tests.rs new file mode 100644 index 00000000..5307b015 --- /dev/null +++ b/examples/stream/src/tests.rs @@ -0,0 +1,36 @@ +use std::fs::{self, File}; +use std::io::prelude::*; + +use rocket::testing::MockRequest; +use rocket::http::Method::*; + +#[test] +fn test_root() { + let rocket = super::rocket(); + let mut req = MockRequest::new(Get, "/"); + let mut res = req.dispatch_with(&rocket); + + // Check that we have exactly 25,000 'a'. + let res_str = res.body_string().unwrap(); + assert_eq!(res_str.len(), 25000); + for byte in res_str.as_bytes() { + assert_eq!(*byte, b'a'); + } +} + +#[test] +fn test_file() { + // Create the 'big_file' + const CONTENTS: &str = "big_file contents...not so big here"; + let mut file = File::create(super::FILENAME).expect("create big_file"); + file.write_all(CONTENTS.as_bytes()).expect("write to big_file"); + + // Get the big file contents, hopefully. + let rocket = super::rocket(); + let mut req = MockRequest::new(Get, "/big_file"); + let mut res = req.dispatch_with(&rocket); + assert_eq!(res.body_string(), Some(CONTENTS.into())); + + // Delete the 'big_file'. + fs::remove_file(super::FILENAME).expect("remove big_file"); +}