Use the blocking testing API everywhere.

Co-authored-by: Sergio Benitez <sb@sergio.bz>
This commit is contained in:
Jeb Rosen 2020-07-05 11:35:36 -07:00 committed by Sergio Benitez
parent 6482fa2fba
commit 06975bfaea
64 changed files with 864 additions and 877 deletions

View File

@ -328,12 +328,11 @@ impl Template {
/// use std::collections::HashMap;
///
/// use rocket_contrib::templates::Template;
/// use rocket::local::asynchronous::Client;
/// use rocket::local::blocking::Client;
///
/// fn main() {
/// # rocket::async_test(async {
/// let rocket = rocket::ignite().attach(Template::fairing());
/// let client = Client::new(rocket).await.expect("valid rocket");
/// let client = Client::new(rocket).expect("valid rocket");
///
/// // Create a `context`. Here, just an empty `HashMap`.
/// let mut context = HashMap::new();
@ -341,7 +340,6 @@ impl Template {
/// # context.insert("test", "test");
/// # #[allow(unused_variables)]
/// let template = Template::show(client.cargo(), "index", context);
/// # });
/// }
/// ```
#[inline]

View File

@ -9,7 +9,7 @@ mod compress_responder_tests {
use rocket::http::hyper::header::{ContentEncoding, Encoding};
use rocket::http::Status;
use rocket::http::{ContentType, Header};
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::response::{Content, Response};
use rocket_contrib::compression::Compress;

View File

@ -10,7 +10,7 @@ mod compression_fairing_tests {
use rocket::http::hyper::header::{ContentEncoding, Encoding};
use rocket::http::Status;
use rocket::http::{ContentType, Header};
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::response::{Content, Response};
use rocket_contrib::compression::Compression;

View File

@ -7,7 +7,7 @@ extern crate rocket;
#[cfg(feature = "helmet")]
mod helmet_tests {
use rocket::http::{Status, uri::Uri};
use rocket::local::asynchronous::{Client, LocalResponse};
use rocket::local::blocking::{Client, LocalResponse};
use rocket_contrib::helmet::*;
use time::Duration;
@ -34,15 +34,15 @@ mod helmet_tests {
macro_rules! dispatch {
($helmet:expr, $closure:expr) => {{
let rocket = rocket::ignite().mount("/", routes![hello]).attach($helmet);
let client = Client::new(rocket).await.unwrap();
let response = client.get("/").dispatch().await;
let client = Client::new(rocket).unwrap();
let response = client.get("/").dispatch();
assert_eq!(response.status(), Status::Ok);
$closure(response)
}}
}
#[rocket::async_test]
async fn default_headers_test() {
#[test]
fn default_headers_test() {
dispatch!(SpaceHelmet::default(), |response: LocalResponse<'_>| {
assert_header!(response, "X-XSS-Protection", "1");
assert_header!(response, "X-Frame-Options", "SAMEORIGIN");
@ -50,8 +50,8 @@ mod helmet_tests {
})
}
#[rocket::async_test]
async fn disable_headers_test() {
#[test]
fn disable_headers_test() {
let helmet = SpaceHelmet::default().disable::<XssFilter>();
dispatch!(helmet, |response: LocalResponse<'_>| {
assert_header!(response, "X-Frame-Options", "SAMEORIGIN");
@ -84,8 +84,8 @@ mod helmet_tests {
});
}
#[rocket::async_test]
async fn additional_headers_test() {
#[test]
fn additional_headers_test() {
let helmet = SpaceHelmet::default()
.enable(Hsts::default())
.enable(ExpectCt::default())
@ -108,8 +108,8 @@ mod helmet_tests {
})
}
#[rocket::async_test]
async fn uri_test() {
#[test]
fn uri_test() {
let allow_uri = Uri::parse("https://www.google.com").unwrap();
let report_uri = Uri::parse("https://www.google.com").unwrap();
let enforce_uri = Uri::parse("https://www.google.com").unwrap();

View File

@ -8,7 +8,7 @@ mod static_tests {
use rocket::{self, Rocket, Route};
use rocket_contrib::serve::{StaticFiles, Options};
use rocket::http::Status;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
fn static_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
@ -45,9 +45,9 @@ mod static_tests {
"inner/",
];
async fn assert_file(client: &Client, prefix: &str, path: &str, exists: bool) {
fn assert_file(client: &Client, prefix: &str, path: &str, exists: bool) {
let full_path = format!("/{}/{}", prefix, path);
let response = client.get(full_path).dispatch().await;
let response = client.get(full_path).dispatch();
if exists {
assert_eq!(response.status(), Status::Ok);
@ -59,52 +59,52 @@ mod static_tests {
let mut file = File::open(path).expect("open file");
let mut expected_contents = String::new();
file.read_to_string(&mut expected_contents).expect("read file");
assert_eq!(response.into_string().await, Some(expected_contents));
assert_eq!(response.into_string(), Some(expected_contents));
} else {
assert_eq!(response.status(), Status::NotFound);
}
}
async fn assert_all(client: &Client, prefix: &str, paths: &[&str], exist: bool) {
fn assert_all(client: &Client, prefix: &str, paths: &[&str], exist: bool) {
for path in paths.iter() {
assert_file(client, prefix, path, exist).await;
assert_file(client, prefix, path, exist);
}
}
#[rocket::async_test]
async fn test_static_no_index() {
let client = Client::new(rocket()).await.expect("valid rocket");
assert_all(&client, "no_index", REGULAR_FILES, true).await;
assert_all(&client, "no_index", HIDDEN_FILES, false).await;
assert_all(&client, "no_index", INDEXED_DIRECTORIES, false).await;
#[test]
fn test_static_no_index() {
let client = Client::new(rocket()).expect("valid rocket");
assert_all(&client, "no_index", REGULAR_FILES, true);
assert_all(&client, "no_index", HIDDEN_FILES, false);
assert_all(&client, "no_index", INDEXED_DIRECTORIES, false);
}
#[rocket::async_test]
async fn test_static_hidden() {
let client = Client::new(rocket()).await.expect("valid rocket");
assert_all(&client, "dots", REGULAR_FILES, true).await;
assert_all(&client, "dots", HIDDEN_FILES, true).await;
assert_all(&client, "dots", INDEXED_DIRECTORIES, false).await;
#[test]
fn test_static_hidden() {
let client = Client::new(rocket()).expect("valid rocket");
assert_all(&client, "dots", REGULAR_FILES, true);
assert_all(&client, "dots", HIDDEN_FILES, true);
assert_all(&client, "dots", INDEXED_DIRECTORIES, false);
}
#[rocket::async_test]
async fn test_static_index() {
let client = Client::new(rocket()).await.expect("valid rocket");
assert_all(&client, "index", REGULAR_FILES, true).await;
assert_all(&client, "index", HIDDEN_FILES, false).await;
assert_all(&client, "index", INDEXED_DIRECTORIES, true).await;
#[test]
fn test_static_index() {
let client = Client::new(rocket()).expect("valid rocket");
assert_all(&client, "index", REGULAR_FILES, true);
assert_all(&client, "index", HIDDEN_FILES, false);
assert_all(&client, "index", INDEXED_DIRECTORIES, true);
assert_all(&client, "default", REGULAR_FILES, true).await;
assert_all(&client, "default", HIDDEN_FILES, false).await;
assert_all(&client, "default", INDEXED_DIRECTORIES, true).await;
assert_all(&client, "default", REGULAR_FILES, true);
assert_all(&client, "default", HIDDEN_FILES, false);
assert_all(&client, "default", INDEXED_DIRECTORIES, true);
}
#[rocket::async_test]
async fn test_static_all() {
let client = Client::new(rocket()).await.expect("valid rocket");
assert_all(&client, "both", REGULAR_FILES, true).await;
assert_all(&client, "both", HIDDEN_FILES, true).await;
assert_all(&client, "both", INDEXED_DIRECTORIES, true).await;
#[test]
fn test_static_all() {
let client = Client::new(rocket()).expect("valid rocket");
assert_all(&client, "both", REGULAR_FILES, true);
assert_all(&client, "both", HIDDEN_FILES, true);
assert_all(&client, "both", INDEXED_DIRECTORIES, true);
}
#[test]
@ -121,8 +121,8 @@ mod static_tests {
}
}
#[rocket::async_test]
async fn test_forwarding() {
#[test]
fn test_forwarding() {
use rocket::http::RawStr;
use rocket::{get, routes};
@ -133,19 +133,19 @@ mod static_tests {
fn catch_two(a: &RawStr, b: &RawStr) -> String { format!("{}/{}", a, b) }
let rocket = rocket().mount("/default", routes![catch_one, catch_two]);
let client = Client::new(rocket).await.expect("valid rocket");
let client = Client::new(rocket).expect("valid rocket");
let response = client.get("/default/ireallydontexist").dispatch().await;
let response = client.get("/default/ireallydontexist").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await.unwrap(), "ireallydontexist");
assert_eq!(response.into_string().unwrap(), "ireallydontexist");
let response = client.get("/default/idont/exist").dispatch().await;
let response = client.get("/default/idont/exist").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await.unwrap(), "idont/exist");
assert_eq!(response.into_string().unwrap(), "idont/exist");
assert_all(&client, "both", REGULAR_FILES, true).await;
assert_all(&client, "both", HIDDEN_FILES, true).await;
assert_all(&client, "both", INDEXED_DIRECTORIES, true).await;
assert_all(&client, "both", REGULAR_FILES, true);
assert_all(&client, "both", HIDDEN_FILES, true);
assert_all(&client, "both", INDEXED_DIRECTORIES, true);
}
#[test]

View File

@ -42,7 +42,7 @@ mod templates_tests {
use super::*;
use std::collections::HashMap;
use rocket::http::Status;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
const UNESCAPED_EXPECTED: &'static str
= "\nh_start\ntitle: _test_\nh_end\n\n\n<script />\n\nfoot\n";
@ -66,20 +66,20 @@ mod templates_tests {
assert_eq!(template, Some(ESCAPED_EXPECTED.into()));
}
#[rocket::async_test]
async fn test_template_metadata_with_tera() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn test_template_metadata_with_tera() {
let client = Client::new(rocket()).unwrap();
let response = client.get("/tera/txt_test").dispatch().await;
let response = client.get("/tera/txt_test").dispatch();
assert_eq!(response.status(), Status::Ok);
let response = client.get("/tera/html_test").dispatch().await;
let response = client.get("/tera/html_test").dispatch();
assert_eq!(response.status(), Status::Ok);
let response = client.get("/tera/not_existing").dispatch().await;
let response = client.get("/tera/not_existing").dispatch();
assert_eq!(response.status(), Status::NotFound);
let response = client.get("/hbs/txt_test").dispatch().await;
let response = client.get("/hbs/txt_test").dispatch();
assert_eq!(response.status(), Status::NotFound);
}
}
@ -89,7 +89,7 @@ mod templates_tests {
use super::*;
use std::collections::HashMap;
use rocket::http::Status;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
const EXPECTED: &'static str
= "Hello _test_!\n\n<main> &lt;script /&gt; hi </main>\nDone.\n\n";
@ -107,28 +107,28 @@ mod templates_tests {
assert_eq!(template, Some(EXPECTED.into()));
}
#[rocket::async_test]
async fn test_template_metadata_with_handlebars() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn test_template_metadata_with_handlebars() {
let client = Client::new(rocket()).unwrap();
let response = client.get("/hbs/test").dispatch().await;
let response = client.get("/hbs/test").dispatch();
assert_eq!(response.status(), Status::Ok);
let response = client.get("/hbs/not_existing").dispatch().await;
let response = client.get("/hbs/not_existing").dispatch();
assert_eq!(response.status(), Status::NotFound);
let response = client.get("/tera/test").dispatch().await;
let response = client.get("/tera/test").dispatch();
assert_eq!(response.status(), Status::NotFound);
}
#[rocket::async_test]
#[test]
#[cfg(debug_assertions)]
async fn test_template_reload() {
fn test_template_reload() {
use std::fs::File;
use std::io::Write;
use std::time::Duration;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
const RELOAD_TEMPLATE: &str = "hbs/reload";
const INITIAL_TEXT: &str = "initial";
@ -146,8 +146,8 @@ mod templates_tests {
write_file(&reload_path, INITIAL_TEXT);
// set up the client. if we can't reload templates, then just quit
let client = Client::new(rocket()).await.unwrap();
let res = client.get("/is_reloading").dispatch().await;
let client = Client::new(rocket()).unwrap();
let res = client.get("/is_reloading").dispatch();
if res.status() != Status::Ok {
return;
}
@ -161,7 +161,7 @@ mod templates_tests {
for _ in 0..6 {
// dispatch any request to trigger a template reload
client.get("/").dispatch().await;
client.get("/").dispatch();
// if the new content is correct, we are done
let new_rendered = Template::show(client.cargo(), RELOAD_TEMPLATE, ());
@ -171,7 +171,7 @@ mod templates_tests {
}
// otherwise, retry a few times, waiting 250ms in between
tokio::time::delay_for(Duration::from_millis(250)).await;
std::thread::sleep(Duration::from_millis(250));
}
panic!("failed to reload modified template in 1.5s");

View File

@ -2,7 +2,7 @@
#[macro_use] extern crate rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
#[get("/easy/<id>")]
fn easy(id: i32) -> String {
@ -33,19 +33,19 @@ macro_rules! foo {
// regression test for `#[get] panicking if used inside a macro
foo!("/hello/<name>", name);
#[rocket::async_test]
async fn test_reexpansion() {
#[test]
fn test_reexpansion() {
let rocket = rocket::ignite().mount("/", routes![easy, hard, hi]);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
let response = client.get("/easy/327").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "easy id: 327");
let response = client.get("/easy/327").dispatch();
assert_eq!(response.into_string().unwrap(), "easy id: 327");
let response = client.get("/hard/72").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "hard id: 72");
let response = client.get("/hard/72").dispatch();
assert_eq!(response.into_string().unwrap(), "hard id: 72");
let response = client.get("/hello/fish").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "fish");
let response = client.get("/hello/fish").dispatch();
assert_eq!(response.into_string().unwrap(), "fish");
}
macro_rules! index {
@ -59,11 +59,11 @@ macro_rules! index {
index!(i32);
#[rocket::async_test]
async fn test_index() {
#[test]
fn test_index() {
let rocket = rocket::ignite().mount("/", routes![index]).manage(100i32);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "Thing: 100");
let response = client.get("/").dispatch();
assert_eq!(response.into_string().unwrap(), "Thing: 100");
}

View File

@ -3,7 +3,7 @@
#[macro_use] extern crate rocket;
use rocket::{Request, Data, Outcome::*};
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::request::Form;
use rocket::data::{self, FromDataSimple};
use rocket::http::{RawStr, ContentType, Status};
@ -41,21 +41,21 @@ fn form(form: Form<Inner<'_>>) -> String { form.field.url_decode_lossy() }
#[post("/s", data = "<simple>")]
fn simple(simple: Simple) -> String { simple.0 }
#[rocket::async_test]
async fn test_data() {
#[test]
fn test_data() {
let rocket = rocket::ignite().mount("/", routes![form, simple]);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
let response = client.post("/f")
.header(ContentType::Form)
.body("field=this%20is%20here")
.dispatch().await;
.dispatch();
assert_eq!(response.into_string().await.unwrap(), "this is here");
assert_eq!(response.into_string().unwrap(), "this is here");
let response = client.post("/s").body("this is here").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "this is here");
let response = client.post("/s").body("this is here").dispatch();
assert_eq!(response.into_string().unwrap(), "this is here");
let response = client.post("/s").body("this%20is%20here").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "this%20is%20here");
let response = client.post("/s").body("this%20is%20here").dispatch();
assert_eq!(response.into_string().unwrap(), "this%20is%20here");
}

View File

@ -2,7 +2,7 @@
#[macro_use] extern crate rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{ContentType, MediaType, Accept, Status};
// Test that known formats work as expected, including not colliding.
@ -33,36 +33,36 @@ fn binary() -> &'static str { "binary" }
#[get("/", rank = 3)]
fn other() -> &'static str { "other" }
#[rocket::async_test]
async fn test_formats() {
#[test]
fn test_formats() {
let rocket = rocket::ignite()
.mount("/", routes![json, xml, json_long, msgpack_long, msgpack,
plain, binary, other]);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
let response = client.post("/").header(ContentType::JSON).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "json");
let response = client.post("/").header(ContentType::JSON).dispatch();
assert_eq!(response.into_string().unwrap(), "json");
let response = client.post("/").header(ContentType::MsgPack).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "msgpack_long");
let response = client.post("/").header(ContentType::MsgPack).dispatch();
assert_eq!(response.into_string().unwrap(), "msgpack_long");
let response = client.post("/").header(ContentType::XML).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "xml");
let response = client.post("/").header(ContentType::XML).dispatch();
assert_eq!(response.into_string().unwrap(), "xml");
let response = client.get("/").header(Accept::Plain).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "plain");
let response = client.get("/").header(Accept::Plain).dispatch();
assert_eq!(response.into_string().unwrap(), "plain");
let response = client.get("/").header(Accept::Binary).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "binary");
let response = client.get("/").header(Accept::Binary).dispatch();
assert_eq!(response.into_string().unwrap(), "binary");
let response = client.get("/").header(ContentType::JSON).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "plain");
let response = client.get("/").header(ContentType::JSON).dispatch();
assert_eq!(response.into_string().unwrap(), "plain");
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "plain");
let response = client.get("/").dispatch();
assert_eq!(response.into_string().unwrap(), "plain");
let response = client.put("/").header(ContentType::HTML).dispatch().await;
let response = client.put("/").header(ContentType::HTML).dispatch();
assert_eq!(response.status(), Status::NotFound);
}
@ -80,36 +80,36 @@ fn get_bar_baz() -> &'static str { "get_bar_baz" }
#[put("/", format = "bar/baz")]
fn put_bar_baz() -> &'static str { "put_bar_baz" }
#[rocket::async_test]
async fn test_custom_formats() {
#[test]
fn test_custom_formats() {
let rocket = rocket::ignite()
.mount("/", routes![get_foo, post_foo, get_bar_baz, put_bar_baz]);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
let foo_a = Accept::new(&[MediaType::new("application", "foo").into()]);
let foo_ct = ContentType::new("application", "foo");
let bar_baz_ct = ContentType::new("bar", "baz");
let bar_baz_a = Accept::new(&[MediaType::new("bar", "baz").into()]);
let response = client.get("/").header(foo_a).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "get_foo");
let response = client.get("/").header(foo_a).dispatch();
assert_eq!(response.into_string().unwrap(), "get_foo");
let response = client.post("/").header(foo_ct).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "post_foo");
let response = client.post("/").header(foo_ct).dispatch();
assert_eq!(response.into_string().unwrap(), "post_foo");
let response = client.get("/").header(bar_baz_a).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "get_bar_baz");
let response = client.get("/").header(bar_baz_a).dispatch();
assert_eq!(response.into_string().unwrap(), "get_bar_baz");
let response = client.put("/").header(bar_baz_ct).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "put_bar_baz");
let response = client.put("/").header(bar_baz_ct).dispatch();
assert_eq!(response.into_string().unwrap(), "put_bar_baz");
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "get_foo");
let response = client.get("/").dispatch();
assert_eq!(response.into_string().unwrap(), "get_foo");
let response = client.put("/").header(ContentType::HTML).dispatch().await;
let response = client.put("/").header(ContentType::HTML).dispatch();
assert_eq!(response.status(), Status::NotFound);
let response = client.post("/").header(ContentType::HTML).dispatch().await;
let response = client.post("/").header(ContentType::HTML).dispatch();
assert_eq!(response.status(), Status::NotFound);
}

View File

@ -2,7 +2,7 @@
#[macro_use] extern crate rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
// Test that manual/auto ranking works as expected.
@ -18,22 +18,22 @@ fn get2(_number: u32) -> &'static str { "2" }
#[get("/<_number>", rank = 3)]
fn get3(_number: u64) -> &'static str { "3" }
#[rocket::async_test]
async fn test_ranking() {
#[test]
fn test_ranking() {
let rocket = rocket::ignite().mount("/", routes![get0, get1, get2, get3]);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
let response = client.get("/0").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "0");
let response = client.get("/0").dispatch();
assert_eq!(response.into_string().unwrap(), "0");
let response = client.get(format!("/{}", 1 << 8)).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "1");
let response = client.get(format!("/{}", 1 << 8)).dispatch();
assert_eq!(response.into_string().unwrap(), "1");
let response = client.get(format!("/{}", 1 << 16)).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "2");
let response = client.get(format!("/{}", 1 << 16)).dispatch();
assert_eq!(response.into_string().unwrap(), "2");
let response = client.get(format!("/{}", 1u64 << 32)).dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "3");
let response = client.get(format!("/{}", 1u64 << 32)).dispatch();
assert_eq!(response.into_string().unwrap(), "3");
}
// Test a collision due to same auto rank.
@ -41,12 +41,12 @@ async fn test_ranking() {
#[get("/<_n>")]
fn get0b(_n: u8) { }
#[rocket::async_test]
async fn test_rank_collision() {
#[test]
fn test_rank_collision() {
use rocket::error::LaunchErrorKind;
let rocket = rocket::ignite().mount("/", routes![get0, get0b]);
let client_result = Client::new(rocket).await;
let client_result = Client::new(rocket);
match client_result.as_ref().map_err(|e| e.kind()) {
Err(LaunchErrorKind::Collision(..)) => { /* o.k. */ },
Ok(_) => panic!("client succeeded unexpectedly"),

View File

@ -11,7 +11,7 @@ use std::path::PathBuf;
use rocket::{Request, Outcome::*};
use rocket::http::ext::Normalize;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::data::{self, Data, FromDataSimple};
use rocket::request::Form;
use rocket::http::{Status, RawStr, ContentType};
@ -79,13 +79,13 @@ fn post2(
fn test_unused_params(_unused_param: String, _unused_query: String, _unused_data: Data) {
}
#[rocket::async_test]
async fn test_full_route() {
#[test]
fn test_full_route() {
let rocket = rocket::ignite()
.mount("/1", routes![post1])
.mount("/2", routes![post2]);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
let a = "A%20A";
let name = "Bob%20McDonald";
@ -99,30 +99,30 @@ async fn test_full_route() {
let uri = format!("{}{}", path_part, query_part);
let expected_uri = format!("{}?sky=blue&sky={}&{}", path_part, sky, query);
let response = client.post(&uri).body(simple).dispatch().await;
let response = client.post(&uri).body(simple).dispatch();
assert_eq!(response.status(), Status::NotFound);
let response = client.post(format!("/1{}", uri)).body(simple).dispatch().await;
let response = client.post(format!("/1{}", uri)).body(simple).dispatch();
assert_eq!(response.status(), Status::NotFound);
let response = client
.post(format!("/1{}", uri))
.header(ContentType::JSON)
.body(simple)
.dispatch().await;
.dispatch();
assert_eq!(response.into_string().await.unwrap(), format!("({}, {}, {}, {}, {}, {}) ({})",
assert_eq!(response.into_string().unwrap(), format!("({}, {}, {}, {}, {}, {}) ({})",
sky, name, "A A", "inside", path, simple, expected_uri));
let response = client.post(format!("/2{}", uri)).body(simple).dispatch().await;
let response = client.post(format!("/2{}", uri)).body(simple).dispatch();
assert_eq!(response.status(), Status::NotFound);
let response = client
.post(format!("/2{}", uri))
.header(ContentType::JSON)
.body(simple)
.dispatch().await;
.dispatch();
assert_eq!(response.into_string().await.unwrap(), format!("({}, {}, {}, {}, {}, {}) ({})",
assert_eq!(response.into_string().unwrap(), format!("({}, {}, {}, {}, {}, {}) ({})",
sky, name, "A A", "inside", path, simple, expected_uri));
}

View File

@ -42,7 +42,7 @@ impl<'r, R> Created<R> {
///
/// ```rust
/// # #![feature(proc_macro_hygiene)]
/// # use rocket::{get, routes, local::asynchronous::Client};
/// # use rocket::{get, routes, local::blocking::Client};
/// use rocket::response::status;
///
/// #[get("/")]
@ -50,15 +50,13 @@ impl<'r, R> Created<R> {
/// status::Created::new("http://myservice.com/resource.json")
/// }
///
/// # rocket::async_test(async move {
/// # let rocket = rocket::ignite().mount("/", routes![create]);
/// # let client = Client::new(rocket).await.unwrap();
/// let response = client.get("/").dispatch().await;
/// # let client = Client::new(rocket).unwrap();
/// let response = client.get("/").dispatch();
///
/// let loc = response.headers().get_one("Location");
/// assert_eq!(loc, Some("http://myservice.com/resource.json"));
/// assert!(response.body().is_none());
/// });
/// ```
pub fn new<L: Into<Cow<'static, str>>>(location: L) -> Self {
Created(location.into(), None, None)
@ -73,7 +71,7 @@ impl<'r, R> Created<R> {
///
/// ```rust
/// # #![feature(proc_macro_hygiene)]
/// # use rocket::{get, routes, local::asynchronous::Client};
/// # use rocket::{get, routes, local::blocking::Client};
/// use rocket::response::status;
///
/// #[get("/")]
@ -82,10 +80,9 @@ impl<'r, R> Created<R> {
/// .body("{ 'resource': 'Hello, world!' }")
/// }
///
/// # rocket::async_test(async move {
/// # let rocket = rocket::ignite().mount("/", routes![create]);
/// # let client = Client::new(rocket).await.unwrap();
/// let response = client.get("/").dispatch().await;
/// # let client = Client::new(rocket).unwrap();
/// let response = client.get("/").dispatch();
///
/// let loc = response.headers().get_one("Location");
/// assert_eq!(loc, Some("http://myservice.com/resource.json"));
@ -93,9 +90,8 @@ impl<'r, R> Created<R> {
/// let etag = response.headers().get_one("ETag");
/// assert_eq!(etag, None);
///
/// let body = response.into_string().await;
/// let body = response.into_string();
/// assert_eq!(body.unwrap(), "{ 'resource': 'Hello, world!' }");
/// # });
/// ```
pub fn body(mut self, responder: R) -> Self {
self.1 = Some(responder);
@ -109,7 +105,7 @@ impl<'r, R> Created<R> {
///
/// ```rust
/// # #![feature(proc_macro_hygiene)]
/// # use rocket::{get, routes, local::asynchronous::Client};
/// # use rocket::{get, routes, local::blocking::Client};
/// use rocket::response::status;
///
/// #[get("/")]
@ -118,10 +114,9 @@ impl<'r, R> Created<R> {
/// .tagged_body("{ 'resource': 'Hello, world!' }")
/// }
///
/// # rocket::async_test(async move {
/// # let rocket = rocket::ignite().mount("/", routes![create]);
/// # let client = Client::new(rocket).await.unwrap();
/// let response = client.get("/").dispatch().await;
/// # let client = Client::new(rocket).unwrap();
/// let response = client.get("/").dispatch();
///
/// let loc = response.headers().get_one("Location");
/// assert_eq!(loc, Some("http://myservice.com/resource.json"));
@ -129,9 +124,8 @@ impl<'r, R> Created<R> {
/// let etag = response.headers().get_one("ETag");
/// assert_eq!(etag, Some(r#""13046220615156895040""#));
///
/// let body = response.into_string().await;
/// let body = response.into_string();
/// assert_eq!(body.unwrap(), "{ 'resource': 'Hello, world!' }");
/// # });
/// ```
pub fn tagged_body(mut self, responder: R) -> Self where R: Hash {
let mut hasher = &mut DefaultHasher::default();

View File

@ -16,18 +16,18 @@ fn rocket() -> Redirect {
mod test_absolute_uris_okay {
use super::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
#[rocket::async_test]
async fn redirect_works() {
#[test]
fn redirect_works() {
let rocket = rocket::ignite().mount("/", routes![google, rocket]);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
let response = client.get("/google").dispatch().await;
let response = client.get("/google").dispatch();
let location = response.headers().get_one("Location");
assert_eq!(location, Some("https://www.google.com"));
let response = client.get("/rocket").dispatch().await;
let response = client.get("/rocket").dispatch();
let location = response.headers().get_one("Location");
assert_eq!(location, Some("https://rocket.rs:80"));
}

View File

@ -6,7 +6,7 @@ use rocket::Response;
use rocket::http::Header;
#[get("/do_not_overwrite")]
async fn do_not_overwrite() -> Response<'static> {
fn do_not_overwrite() -> Response<'static> {
Response::build()
.header(Header::new("Server", "Test"))
.finalize()
@ -17,18 +17,18 @@ fn use_default() { }
mod conditionally_set_server_header {
use super::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
#[rocket::async_test]
async fn do_not_overwrite_server_header() {
#[test]
fn do_not_overwrite_server_header() {
let rocket = rocket::ignite().mount("/", routes![do_not_overwrite, use_default]);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
let response = client.get("/do_not_overwrite").dispatch().await;
let response = client.get("/do_not_overwrite").dispatch();
let server = response.headers().get_one("Server");
assert_eq!(server, Some("Test"));
let response = client.get("/use_default").dispatch().await;
let response = client.get("/use_default").dispatch();
let server = response.headers().get_one("Server");
assert_eq!(server, Some("Rocket"));
}

View File

@ -43,16 +43,16 @@ fn number(params: Form<ThingForm>) -> DerivedResponder {
DerivedResponder { data: params.thing.to_string() }
}
#[rocket::async_test]
async fn test_derive_reexports() {
use rocket::local::asynchronous::Client;
#[test]
fn test_derive_reexports() {
use rocket::local::blocking::Client;
let rocket = rocket::ignite().mount("/", routes![index, number]);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "hello");
let response = client.get("/").dispatch();
assert_eq!(response.into_string().unwrap(), "hello");
let response = client.get("/?thing=b").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "b");
let response = client.get("/?thing=b").dispatch();
assert_eq!(response.into_string().unwrap(), "b");
}

View File

@ -22,12 +22,12 @@ mod fairing_before_head_strip {
use rocket::fairing::AdHoc;
use rocket::http::Method;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
use rocket::State;
#[rocket::async_test]
async fn not_auto_handled() {
#[test]
fn not_auto_handled() {
let rocket = rocket::ignite()
.mount("/", routes![head])
.attach(AdHoc::on_request("Check HEAD", |req, _| {
@ -42,14 +42,14 @@ mod fairing_before_head_strip {
})
}));
let client = Client::new(rocket).await.unwrap();
let response = client.head("/").dispatch().await;
let client = Client::new(rocket).unwrap();
let response = client.head("/").dispatch();
assert_eq!(response.status(), Status::Ok);
assert!(response.body().is_none());
}
#[rocket::async_test]
async fn auto_handled() {
#[test]
fn auto_handled() {
#[derive(Default)]
struct Counter(AtomicUsize);
@ -73,8 +73,8 @@ mod fairing_before_head_strip {
})
}));
let client = Client::new(rocket).await.unwrap();
let response = client.head("/").dispatch().await;
let client = Client::new(rocket).unwrap();
let response = client.head("/").dispatch();
assert_eq!(response.status(), Status::Ok);
assert!(response.body().is_none());
}

View File

@ -23,40 +23,40 @@ fn used(flash: Option<FlashMessage<'_, '_>>) -> Option<String> {
}
mod flash_lazy_remove_tests {
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
#[rocket::async_test]
async fn test() {
#[test]
fn test() {
use super::*;
let r = rocket::ignite().mount("/", routes![set, unused, used]);
let client = Client::new(r).await.unwrap();
let client = Client::new(r).unwrap();
// Ensure the cookie's not there at first.
let response = client.get("/unused").dispatch().await;
let response = client.get("/unused").dispatch();
assert_eq!(response.status(), Status::NotFound);
// Set the flash cookie.
client.post("/").dispatch().await;
client.post("/").dispatch();
// Try once.
let response = client.get("/unused").dispatch().await;
let response = client.get("/unused").dispatch();
assert_eq!(response.status(), Status::Ok);
// Try again; should still be there.
let response = client.get("/unused").dispatch().await;
let response = client.get("/unused").dispatch();
assert_eq!(response.status(), Status::Ok);
// Now use it.
let response = client.get("/use").dispatch().await;
assert_eq!(response.into_string().await, Some(FLASH_MESSAGE.into()));
let response = client.get("/use").dispatch();
assert_eq!(response.into_string(), Some(FLASH_MESSAGE.into()));
// Now it should be gone.
let response = client.get("/unused").dispatch().await;
let response = client.get("/unused").dispatch();
assert_eq!(response.status(), Status::NotFound);
// Still gone.
let response = client.get("/use").dispatch().await;
let response = client.get("/use").dispatch();
assert_eq!(response.status(), Status::NotFound);
}
}

View File

@ -17,27 +17,27 @@ fn bug(form_data: Form<FormData>) -> &'static str {
mod tests {
use super::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{Status, ContentType};
#[rocket::async_test]
async fn method_eval() {
let client = Client::new(rocket::ignite().mount("/", routes![bug])).await.unwrap();
#[test]
fn method_eval() {
let client = Client::new(rocket::ignite().mount("/", routes![bug])).unwrap();
let response = client.post("/")
.header(ContentType::Form)
.body("_method=patch&form_data=Form+data")
.dispatch().await;
.dispatch();
assert_eq!(response.into_string().await, Some("OK".into()));
assert_eq!(response.into_string(), Some("OK".into()));
}
#[rocket::async_test]
async fn get_passes_through() {
let client = Client::new(rocket::ignite().mount("/", routes![bug])).await.unwrap();
#[test]
fn get_passes_through() {
let client = Client::new(rocket::ignite().mount("/", routes![bug])).unwrap();
let response = client.get("/")
.header(ContentType::Form)
.body("_method=patch&form_data=Form+data")
.dispatch().await;
.dispatch();
assert_eq!(response.status(), Status::NotFound);
}

View File

@ -16,29 +16,29 @@ fn bug(form_data: Form<FormData>) -> String {
mod tests {
use super::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::ContentType;
use rocket::http::Status;
async fn check_decoding(raw: &str, decoded: &str) {
let client = Client::new(rocket::ignite().mount("/", routes![bug])).await.unwrap();
fn check_decoding(raw: &str, decoded: &str) {
let client = Client::new(rocket::ignite().mount("/", routes![bug])).unwrap();
let response = client.post("/")
.header(ContentType::Form)
.body(format!("form_data={}", raw))
.dispatch().await;
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(Some(decoded.to_string()), response.into_string().await);
assert_eq!(Some(decoded.to_string()), response.into_string());
}
#[rocket::async_test]
async fn test_proper_decoding() {
check_decoding("password", "password").await;
check_decoding("", "").await;
check_decoding("+", " ").await;
check_decoding("%2B", "+").await;
check_decoding("1+1", "1 1").await;
check_decoding("1%2B1", "1+1").await;
check_decoding("%3Fa%3D1%26b%3D2", "?a=1&b=2").await;
#[test]
fn test_proper_decoding() {
check_decoding("password", "password");
check_decoding("", "");
check_decoding("+", " ");
check_decoding("%2B", "+");
check_decoding("1+1", "1 1");
check_decoding("1%2B1", "1+1");
check_decoding("%3Fa%3D1%26b%3D2", "?a=1&b=2");
}
}

View File

@ -23,38 +23,38 @@ mod head_handling_tests {
use super::*;
use rocket::Route;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{Status, ContentType};
fn routes() -> Vec<Route> {
routes![index, empty, other]
}
#[rocket::async_test]
async fn auto_head() {
let client = Client::new(rocket::ignite().mount("/", routes())).await.unwrap();
let response = client.head("/").dispatch().await;
#[test]
fn auto_head() {
let client = Client::new(rocket::ignite().mount("/", routes())).unwrap();
let response = client.head("/").dispatch();
let content_type: Vec<_> = response.headers().get("Content-Type").collect();
assert_eq!(content_type, vec![ContentType::Plain.to_string()]);
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body().unwrap().known_size(), Some(13));
assert!(response.into_bytes().await.unwrap().is_empty());
assert!(response.into_bytes().unwrap().is_empty());
let response = client.head("/empty").dispatch().await;
let response = client.head("/empty").dispatch();
assert_eq!(response.status(), Status::NoContent);
assert!(response.into_bytes().await.is_none());
assert!(response.into_bytes().is_none());
}
#[rocket::async_test]
async fn user_head() {
let client = Client::new(rocket::ignite().mount("/", routes())).await.unwrap();
let response = client.head("/other").dispatch().await;
#[test]
fn user_head() {
let client = Client::new(rocket::ignite().mount("/", routes())).unwrap();
let response = client.head("/other").dispatch();
let content_type: Vec<_> = response.headers().get("Content-Type").collect();
assert_eq!(content_type, vec![ContentType::JSON.to_string()]);
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body().unwrap().known_size(), Some(17));
assert!(response.into_bytes().await.unwrap().is_empty());
assert!(response.into_bytes().unwrap().is_empty());
}
}

View File

@ -17,7 +17,7 @@ fn index(form: Form<Simple>) -> String {
mod limits_tests {
use rocket;
use rocket::config::{Environment, Config, Limits};
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{Status, ContentType};
fn rocket_with_forms_limit(limit: u64) -> rocket::Rocket {
@ -28,47 +28,47 @@ mod limits_tests {
rocket::custom(config).mount("/", routes![super::index])
}
#[rocket::async_test]
async fn large_enough() {
let client = Client::new(rocket_with_forms_limit(128)).await.unwrap();
#[test]
fn large_enough() {
let client = Client::new(rocket_with_forms_limit(128)).unwrap();
let response = client.post("/")
.body("value=Hello+world")
.header(ContentType::Form)
.dispatch().await;
.dispatch();
assert_eq!(response.into_string().await, Some("Hello world".into()));
assert_eq!(response.into_string(), Some("Hello world".into()));
}
#[rocket::async_test]
async fn just_large_enough() {
let client = Client::new(rocket_with_forms_limit(17)).await.unwrap();
#[test]
fn just_large_enough() {
let client = Client::new(rocket_with_forms_limit(17)).unwrap();
let response = client.post("/")
.body("value=Hello+world")
.header(ContentType::Form)
.dispatch().await;
.dispatch();
assert_eq!(response.into_string().await, Some("Hello world".into()));
assert_eq!(response.into_string(), Some("Hello world".into()));
}
#[rocket::async_test]
async fn much_too_small() {
let client = Client::new(rocket_with_forms_limit(4)).await.unwrap();
#[test]
fn much_too_small() {
let client = Client::new(rocket_with_forms_limit(4)).unwrap();
let response = client.post("/")
.body("value=Hello+world")
.header(ContentType::Form)
.dispatch().await;
.dispatch();
assert_eq!(response.status(), Status::UnprocessableEntity);
}
#[rocket::async_test]
async fn contracted() {
let client = Client::new(rocket_with_forms_limit(10)).await.unwrap();
#[test]
fn contracted() {
let client = Client::new(rocket_with_forms_limit(10)).unwrap();
let response = client.post("/")
.body("value=Hello+world")
.header(ContentType::Form)
.dispatch().await;
.dispatch();
assert_eq!(response.into_string().await, Some("Hell".into()));
assert_eq!(response.into_string(), Some("Hell".into()));
}
}

View File

@ -54,40 +54,40 @@ mod local_request_content_type_tests {
use super::*;
use rocket::Rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::ContentType;
fn rocket() -> Rocket {
rocket::ignite().mount("/", routes![rg_ct, data_has_ct, data_no_ct])
}
#[rocket::async_test]
async fn has_no_ct() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn has_no_ct() {
let client = Client::new(rocket()).unwrap();
let req = client.post("/");
assert_eq!(req.clone().dispatch().await.into_string().await, Some("Absent".to_string()));
assert_eq!(req.clone().dispatch().await.into_string().await, Some("Absent".to_string()));
assert_eq!(req.dispatch().await.into_string().await, Some("Absent".to_string()));
assert_eq!(req.clone().dispatch().into_string(), Some("Absent".to_string()));
assert_eq!(req.clone().dispatch().into_string(), Some("Absent".to_string()));
assert_eq!(req.dispatch().into_string(), Some("Absent".to_string()));
let req = client.post("/data");
assert_eq!(req.clone().dispatch().await.into_string().await, Some("Data Absent".to_string()));
assert_eq!(req.clone().dispatch().await.into_string().await, Some("Data Absent".to_string()));
assert_eq!(req.dispatch().await.into_string().await, Some("Data Absent".to_string()));
assert_eq!(req.clone().dispatch().into_string(), Some("Data Absent".to_string()));
assert_eq!(req.clone().dispatch().into_string(), Some("Data Absent".to_string()));
assert_eq!(req.dispatch().into_string(), Some("Data Absent".to_string()));
}
#[rocket::async_test]
async fn has_ct() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn has_ct() {
let client = Client::new(rocket()).unwrap();
let req = client.post("/").header(ContentType::JSON);
assert_eq!(req.clone().dispatch().await.into_string().await, Some("Present".to_string()));
assert_eq!(req.clone().dispatch().await.into_string().await, Some("Present".to_string()));
assert_eq!(req.dispatch().await.into_string().await, Some("Present".to_string()));
assert_eq!(req.clone().dispatch().into_string(), Some("Present".to_string()));
assert_eq!(req.clone().dispatch().into_string(), Some("Present".to_string()));
assert_eq!(req.dispatch().into_string(), Some("Present".to_string()));
let req = client.post("/data").header(ContentType::JSON);
assert_eq!(req.clone().dispatch().await.into_string().await, Some("Data Present".to_string()));
assert_eq!(req.clone().dispatch().await.into_string().await, Some("Data Present".to_string()));
assert_eq!(req.dispatch().await.into_string().await, Some("Data Present".to_string()));
assert_eq!(req.clone().dispatch().into_string(), Some("Data Present".to_string()));
assert_eq!(req.clone().dispatch().into_string(), Some("Data Present".to_string()));
assert_eq!(req.dispatch().into_string(), Some("Data Present".to_string()));
}
}

View File

@ -18,29 +18,29 @@ mod private_cookie_test {
mod tests {
use super::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Cookie;
use rocket::http::Status;
#[rocket::async_test]
async fn private_cookie_is_returned() {
#[test]
fn private_cookie_is_returned() {
let rocket = rocket::ignite().mount("/", routes![return_private_cookie]);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
let req = client.get("/").private_cookie(Cookie::new("cookie_name", "cookie_value"));
let response = req.dispatch().await;
let response = req.dispatch();
assert_eq!(response.headers().get_one("Set-Cookie"), None);
assert_eq!(response.into_string().await, Some("cookie_value".into()));
assert_eq!(response.into_string(), Some("cookie_value".into()));
}
#[rocket::async_test]
async fn regular_cookie_is_not_returned() {
#[test]
fn regular_cookie_is_not_returned() {
let rocket = rocket::ignite().mount("/", routes![return_private_cookie]);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
let req = client.get("/").cookie(Cookie::new("cookie_name", "cookie_value"));
let response = req.dispatch().await;
let response = req.dispatch();
assert_eq!(response.status(), Status::NotFound);
}

View File

@ -44,20 +44,20 @@ fn rocket() -> rocket::Rocket {
mod nested_fairing_attaches_tests {
use super::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
#[rocket::async_test]
async fn test_counts() {
let client = Client::new(rocket()).await.unwrap();
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await, Some("1, 1".into()));
#[test]
fn test_counts() {
let client = Client::new(rocket()).unwrap();
let response = client.get("/").dispatch();
assert_eq!(response.into_string(), Some("1, 1".into()));
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await, Some("1, 2".into()));
let response = client.get("/").dispatch();
assert_eq!(response.into_string(), Some("1, 2".into()));
client.get("/").dispatch().await;
client.get("/").dispatch().await;
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await, Some("1, 5".into()));
client.get("/").dispatch();
client.get("/").dispatch();
let response = client.get("/").dispatch();
assert_eq!(response.into_string(), Some("1, 5".into()));
}
}

View File

@ -26,7 +26,7 @@ mod tests {
use super::*;
use rocket::Rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{Status, ContentType};
fn rocket() -> Rocket {
@ -37,16 +37,16 @@ mod tests {
macro_rules! check_dispatch {
($mount:expr, $ct:expr, $body:expr) => (
let client = Client::new(rocket()).await.unwrap();
let client = Client::new(rocket()).unwrap();
let mut req = client.post($mount);
let ct: Option<ContentType> = $ct;
if let Some(ct) = ct {
req.add_header(ct);
}
let response = req.dispatch().await;
let response = req.dispatch();
let status = response.status();
let body_str = response.into_string().await;
let body_str = response.into_string();
let body: Option<&'static str> = $body;
match body {
Some(string) => assert_eq!(body_str, Some(string.to_string())),
@ -55,15 +55,15 @@ mod tests {
)
}
#[rocket::async_test]
async fn exact_match_or_forward() {
#[test]
fn exact_match_or_forward() {
check_dispatch!("/first", Some(ContentType::JSON), Some("specified"));
check_dispatch!("/first", None, Some("unspecified"));
check_dispatch!("/first", Some(ContentType::HTML), Some("unspecified"));
}
#[rocket::async_test]
async fn exact_match_or_none() {
#[test]
fn exact_match_or_none() {
check_dispatch!("/second", Some(ContentType::JSON), Some("specified_json"));
check_dispatch!("/second", Some(ContentType::HTML), Some("specified_html"));
check_dispatch!("/second", Some(ContentType::CSV), None);

View File

@ -11,13 +11,13 @@ fn not_found() -> Redirect {
mod tests {
use super::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
#[rocket::async_test]
async fn error_catcher_redirect() {
let client = Client::new(rocket::ignite().register(catchers![not_found])).await.unwrap();
let response = client.get("/unknown").dispatch().await;
#[test]
fn error_catcher_redirect() {
let client = Client::new(rocket::ignite().register(catchers![not_found])).unwrap();
let response = client.get("/unknown").dispatch();
println!("Response:\n{:?}", response);
let location: Vec<_> = response.headers().get("location").collect();

View File

@ -13,23 +13,23 @@ fn files(route: &Route, path: PathBuf) -> String {
mod route_guard_tests {
use super::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
async fn assert_path(client: &Client, path: &str) {
let res = client.get(path).dispatch().await;
assert_eq!(res.into_string().await, Some(path.into()));
fn assert_path(client: &Client, path: &str) {
let res = client.get(path).dispatch();
assert_eq!(res.into_string(), Some(path.into()));
}
#[rocket::async_test]
async fn check_mount_path() {
#[test]
fn check_mount_path() {
let rocket = rocket::ignite()
.mount("/first", routes![files])
.mount("/second", routes![files]);
let client = Client::new(rocket).await.unwrap();
assert_path(&client, "/first/some/path").await;
assert_path(&client, "/second/some/path").await;
assert_path(&client, "/first/second/b/c").await;
assert_path(&client, "/second/a/b/c").await;
let client = Client::new(rocket).unwrap();
assert_path(&client, "/first/some/path");
assert_path(&client, "/second/some/path");
assert_path(&client, "/first/second/b/c");
assert_path(&client, "/second/a/b/c");
}
}

View File

@ -31,14 +31,14 @@ fn dual(user: String, path: Segments<'_>) -> String {
mod tests {
use super::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
#[rocket::async_test]
async fn segments_works() {
#[test]
fn segments_works() {
let rocket = rocket::ignite()
.mount("/", routes![test, two, one_two, none, dual])
.mount("/point", routes![test, two, one_two, dual]);
let client = Client::new(rocket).await.unwrap();
let client = Client::new(rocket).unwrap();
// We construct a path that matches each of the routes above. We ensure the
// prefix is stripped, confirming that dynamic segments are working.
@ -47,8 +47,8 @@ mod tests {
"/static", "/point/static"]
{
let path = "this/is/the/path/we/want";
let response = client.get(format!("{}/{}", prefix, path)).dispatch().await;
assert_eq!(response.into_string().await, Some(path.into()));
let response = client.get(format!("{}/{}", prefix, path)).dispatch();
assert_eq!(response.into_string(), Some(path.into()));
}
}
}

View File

@ -22,51 +22,51 @@ fn lenient<'r>(form: LenientForm<MyForm<'r>>) -> String {
mod strict_and_lenient_forms_tests {
use super::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{Status, ContentType};
const FIELD_VALUE: &str = "just_some_value";
async fn client() -> Client {
Client::new(rocket::ignite().mount("/", routes![strict, lenient])).await.unwrap()
fn client() -> Client {
Client::new(rocket::ignite().mount("/", routes![strict, lenient])).unwrap()
}
#[rocket::async_test]
async fn test_strict_form() {
let client = client().await;
#[test]
fn test_strict_form() {
let client = client();
let response = client.post("/strict")
.header(ContentType::Form)
.body(format!("field={}", FIELD_VALUE))
.dispatch().await;
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await, Some(FIELD_VALUE.into()));
assert_eq!(response.into_string(), Some(FIELD_VALUE.into()));
let response = client.post("/strict")
.header(ContentType::Form)
.body(format!("field={}&extra=whoops", FIELD_VALUE))
.dispatch().await;
.dispatch();
assert_eq!(response.status(), Status::UnprocessableEntity);
}
#[rocket::async_test]
async fn test_lenient_form() {
let client = client().await;
#[test]
fn test_lenient_form() {
let client = client();
let response = client.post("/lenient")
.header(ContentType::Form)
.body(format!("field={}", FIELD_VALUE))
.dispatch().await;
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await, Some(FIELD_VALUE.into()));
assert_eq!(response.into_string(), Some(FIELD_VALUE.into()));
let response = client.post("/lenient")
.header(ContentType::Form)
.body(format!("field={}&extra=whoops", FIELD_VALUE))
.dispatch().await;
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await, Some(FIELD_VALUE.into()));
assert_eq!(response.into_string(), Some(FIELD_VALUE.into()));
}
}

View File

@ -1,33 +1,33 @@
// use rocket::http::Header;
// use rocket::local::Client;
//
// #[test]
// fn test_local_request_clone_soundness() {
// let client = Client::new(rocket::ignite()).unwrap();
//
// // creates two LocalRequest instances that shouldn't share the same req
// let r1 = client.get("/").header(Header::new("key", "val1"));
// let mut r2 = r1.clone();
//
// // save the iterator, which internally holds a slice
// let mut iter = r1.inner().headers().get("key");
//
// // insert headers to force header map reallocation.
// for i in 0..100 {
// r2.add_header(Header::new(i.to_string(), i.to_string()));
// }
//
// // Replace the original key/val.
// r2.add_header(Header::new("key", "val2"));
//
// // Heap massage: so we've got crud to print.
// let _: Vec<usize> = vec![0, 0xcafebabe, 31337, 0];
//
// // Ensure we're good.
// let s = iter.next().unwrap();
// println!("{}", s);
//
// // And that we've got the right data.
// assert_eq!(r1.inner().headers().get("key").collect::<Vec<_>>(), vec!["val1"]);
// assert_eq!(r2.inner().headers().get("key").collect::<Vec<_>>(), vec!["val1", "val2"]);
// }
use rocket::http::Header;
use rocket::local::blocking::Client;
#[test]
fn test_local_request_clone_soundness() {
let client = Client::new(rocket::ignite()).unwrap();
// creates two LocalRequest instances that shouldn't share the same req
let r1 = client.get("/").header(Header::new("key", "val1"));
let mut r2 = r1.clone();
// save the iterator, which internally holds a slice
let mut iter = r1.inner().headers().get("key");
// insert headers to force header map reallocation.
for i in 0..100 {
r2.add_header(Header::new(i.to_string(), i.to_string()));
}
// Replace the original key/val.
r2.add_header(Header::new("key", "val2"));
// Heap massage: so we've got crud to print.
let _: Vec<usize> = vec![0, 0xcafebabe, 31337, 0];
// Ensure we're good.
let s = iter.next().unwrap();
println!("{}", s);
// And that we've got the right data.
assert_eq!(r1.inner().headers().get("key").collect::<Vec<_>>(), vec!["val1"]);
assert_eq!(r2.inner().headers().get("key").collect::<Vec<_>>(), vec!["val1", "val2"]);
}

View File

@ -29,31 +29,31 @@ fn rocket() -> rocket::Rocket {
mod tests {
use super::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{Status, uri::Uri};
#[rocket::async_test]
async fn uri_percent_encoding_redirect() {
#[test]
fn uri_percent_encoding_redirect() {
let expected_location = vec!["/hello/John%5B%5D%7C%5C%25@%5E"];
let client = Client::new(rocket()).await.unwrap();
let client = Client::new(rocket()).unwrap();
let response = client.get("/raw").dispatch().await;
let response = client.get("/raw").dispatch();
let location: Vec<_> = response.headers().get("location").collect();
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(&location, &expected_location);
let response = client.get("/uri").dispatch().await;
let response = client.get("/uri").dispatch();
let location: Vec<_> = response.headers().get("location").collect();
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(&location, &expected_location);
}
#[rocket::async_test]
async fn uri_percent_encoding_get() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn uri_percent_encoding_get() {
let client = Client::new(rocket()).unwrap();
let name = Uri::percent_encode(NAME);
let response = client.get(format!("/hello/{}", name)).dispatch().await;
let response = client.get(format!("/hello/{}", name)).dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await.unwrap(), format!("Hello, {}!", NAME));
assert_eq!(response.into_string().unwrap(), format!("Hello, {}!", NAME));
}
}

View File

@ -2,7 +2,7 @@ use rocket::{self, State};
use rocket::fairing::AdHoc;
use rocket::config::{self, Config, Environment, LoggingLevel};
use rocket::http::Status;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
struct LocalConfig(Config);
@ -62,9 +62,7 @@ pub fn test_config(environment: Environment) {
}))
.mount("/", routes![check_config]);
rocket::async_test(async move {
let client = Client::new(rocket).await.unwrap();
let response = client.get("/check_config").dispatch().await;
let client = Client::new(rocket).unwrap();
let response = client.get("/check_config").dispatch();
assert_eq!(response.status(), Status::Ok);
})
}

View File

@ -1,41 +1,41 @@
use super::Person;
use rocket::http::{Accept, ContentType, Header, MediaType, Method, Status};
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
async fn test<H>(method: Method, uri: &str, header: H, status: Status, body: String)
fn test<H>(method: Method, uri: &str, header: H, status: Status, body: String)
where H: Into<Header<'static>>
{
let client = Client::new(super::rocket()).await.unwrap();
let response = client.req(method, uri).header(header).dispatch().await;
let client = Client::new(super::rocket()).unwrap();
let response = client.req(method, uri).header(header).dispatch();
assert_eq!(response.status(), status);
assert_eq!(response.into_string().await, Some(body));
assert_eq!(response.into_string(), Some(body));
}
#[rocket::async_test]
async fn test_hello() {
#[test]
fn test_hello() {
let person = Person { name: "Michael".to_string(), age: 80, };
let body = serde_json::to_string(&person).unwrap();
test(Method::Get, "/hello/Michael/80", Accept::JSON, Status::Ok, body.clone()).await;
test(Method::Get, "/hello/Michael/80", Accept::Any, Status::Ok, body.clone()).await;
test(Method::Get, "/hello/Michael/80", Accept::JSON, Status::Ok, body.clone());
test(Method::Get, "/hello/Michael/80", Accept::Any, Status::Ok, body.clone());
// No `Accept` header is an implicit */*.
test(Method::Get, "/hello/Michael/80", ContentType::XML, Status::Ok, body).await;
test(Method::Get, "/hello/Michael/80", ContentType::XML, Status::Ok, body);
let person = Person { name: "".to_string(), age: 99, };
let body = serde_json::to_string(&person).unwrap();
test(Method::Post, "/hello/99", ContentType::Plain, Status::Ok, body).await;
test(Method::Post, "/hello/99", ContentType::Plain, Status::Ok, body);
}
#[rocket::async_test]
async fn test_hello_invalid_content_type() {
#[test]
fn test_hello_invalid_content_type() {
let b = format!("<p>'{}' requests are not supported.</p>", MediaType::HTML);
test(Method::Get, "/hello/Michael/80", Accept::HTML, Status::NotFound, b.clone()).await;
test(Method::Post, "/hello/80", ContentType::HTML, Status::NotFound, b).await;
test(Method::Get, "/hello/Michael/80", Accept::HTML, Status::NotFound, b.clone());
test(Method::Post, "/hello/80", ContentType::HTML, Status::NotFound, b);
}
#[rocket::async_test]
async fn test_404() {
#[test]
fn test_404() {
let body = "<p>Sorry, '/unknown' is an invalid path! Try \
/hello/&lt;name&gt;/&lt;age&gt; instead.</p>";
test(Method::Get, "/unknown", Accept::JSON, Status::NotFound, body.to_string()).await;
test(Method::Get, "/unknown", Accept::JSON, Status::NotFound, body.to_string());
}

View File

@ -1,17 +1,17 @@
use std::collections::HashMap;
use super::rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::*;
use rocket_contrib::templates::Template;
#[rocket::async_test]
async fn test_submit() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn test_submit() {
let client = Client::new(rocket()).unwrap();
let response = client.post("/submit")
.header(ContentType::Form)
.body("message=Hello from Rocket!")
.dispatch().await;
.dispatch();
let cookie_headers: Vec<_> = response.headers().get("Set-Cookie").collect();
let location_headers: Vec<_> = response.headers().get("Location").collect();
@ -21,29 +21,29 @@ async fn test_submit() {
assert_eq!(location_headers, vec!["/".to_string()]);
}
async fn test_body(optional_cookie: Option<Cookie<'static>>, expected_body: String) {
fn test_body(optional_cookie: Option<Cookie<'static>>, expected_body: String) {
// Attach a cookie if one is given.
let client = Client::new(rocket()).await.unwrap();
let client = Client::new(rocket()).unwrap();
let response = match optional_cookie {
Some(cookie) => client.get("/").cookie(cookie).dispatch().await,
None => client.get("/").dispatch().await,
Some(cookie) => client.get("/").cookie(cookie).dispatch(),
None => client.get("/").dispatch(),
};
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await, Some(expected_body));
assert_eq!(response.into_string(), Some(expected_body));
}
#[rocket::async_test]
async fn test_index() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn test_index() {
let client = Client::new(rocket()).unwrap();
// Render the template with an empty context.
let mut context: HashMap<&str, &str> = HashMap::new();
let template = Template::show(client.cargo(), "index", &context).unwrap();
test_body(None, template).await;
test_body(None, template);
// Render the template with a context that contains the message.
context.insert("message", "Hello from Rocket!");
let template = Template::show(client.cargo(), "index", &context).unwrap();
test_body(Some(Cookie::new("message", "Hello from Rocket!")), template).await;
test_body(Some(Cookie::new("message", "Hello from Rocket!")), template);
}

View File

@ -1,31 +1,31 @@
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
async fn test(uri: &str, status: Status, body: String) {
fn test(uri: &str, status: Status, body: String) {
let rocket = rocket::ignite()
.mount("/", routes![super::hello])
.register(catchers![super::not_found]);
let client = Client::new(rocket).await.unwrap();
let response = client.get(uri).dispatch().await;
let client = Client::new(rocket).unwrap();
let response = client.get(uri).dispatch();
assert_eq!(response.status(), status);
assert_eq!(response.into_string().await, Some(body));
assert_eq!(response.into_string(), Some(body));
}
#[rocket::async_test]
async fn test_hello() {
#[test]
fn test_hello() {
let (name, age) = ("Arthur", 42);
let uri = format!("/hello/{}/{}", name, age);
test(&uri, Status::Ok, format!("Hello, {} year old named {}!", age, name)).await;
test(&uri, Status::Ok, format!("Hello, {} year old named {}!", age, name));
}
#[rocket::async_test]
async fn test_hello_invalid_age() {
#[test]
fn test_hello_invalid_age() {
for &(name, age) in &[("Ford", -129), ("Trillian", 128)] {
let uri = format!("/hello/{}/{}", name, age);
let body = format!("<p>Sorry, but '{}' is not a valid path!</p>
<p>Try visiting /hello/&lt;name&gt;/&lt;age&gt; instead.</p>",
uri);
test(&uri, Status::NotFound, body).await;
test(&uri, Status::NotFound, body);
}
}

View File

@ -1,38 +1,38 @@
use super::rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
#[rocket::async_test]
async fn rewrite_get_put() {
let client = Client::new(rocket()).await.unwrap();
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await, Some("Hello, fairings!".into()));
#[test]
fn rewrite_get_put() {
let client = Client::new(rocket()).unwrap();
let response = client.get("/").dispatch();
assert_eq!(response.into_string(), Some("Hello, fairings!".into()));
}
#[rocket::async_test]
async fn counts() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn counts() {
let client = Client::new(rocket()).unwrap();
// Issue 1 GET request.
client.get("/").dispatch().await;
client.get("/").dispatch();
// Check the GET count, taking into account _this_ GET request.
let response = client.get("/counts").dispatch().await;
assert_eq!(response.into_string().await, Some("Get: 2\nPost: 0".into()));
let response = client.get("/counts").dispatch();
assert_eq!(response.into_string(), Some("Get: 2\nPost: 0".into()));
// Issue 1 more GET request and a POST.
client.get("/").dispatch().await;
client.post("/").dispatch().await;
client.get("/").dispatch();
client.post("/").dispatch();
// Check the counts.
let response = client.get("/counts").dispatch().await;
assert_eq!(response.into_string().await, Some("Get: 4\nPost: 1".into()));
let response = client.get("/counts").dispatch();
assert_eq!(response.into_string(), Some("Get: 4\nPost: 1".into()));
}
#[rocket::async_test]
async fn token() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn token() {
let client = Client::new(rocket()).unwrap();
// Ensure the token is '123', which is what we have in `Rocket.toml`.
let res = client.get("/token").dispatch().await;
assert_eq!(res.into_string().await, Some("123".into()));
let res = client.get("/token").dispatch();
assert_eq!(res.into_string(), Some("123".into()));
}

View File

@ -1,24 +1,22 @@
use super::rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{ContentType, Status};
fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T)
where T: Into<Option<&'static str>> + Send
{
rocket::async_test(async move {
let client = Client::new(rocket()).await.unwrap();
let client = Client::new(rocket()).unwrap();
let query = format!("username={}&password={}&age={}", user, pass, age);
let response = client.post("/login")
.header(ContentType::Form)
.body(&query)
.dispatch().await;
.dispatch();
assert_eq!(response.status(), status);
if let Some(expected_str) = body.into() {
let body_str = response.into_string().await;
let body_str = response.into_string();
assert!(body_str.map_or(false, |s| s.contains(expected_str)));
}
})
}
#[test]
@ -46,15 +44,13 @@ fn test_invalid_age() {
}
fn check_bad_form(form_str: &str, status: Status) {
rocket::async_test(async {
let client = Client::new(rocket()).await.unwrap();
let client = Client::new(rocket()).unwrap();
let response = client.post("/login")
.header(ContentType::Form)
.body(form_str)
.dispatch().await;
.dispatch();
assert_eq!(response.status(), status);
})
}
#[test]

View File

@ -1,20 +1,20 @@
use super::{rocket, TemplateContext};
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Method::*;
use rocket::http::Status;
use rocket_contrib::templates::Template;
macro_rules! dispatch {
($method:expr, $path:expr, |$client:ident, $response:ident| $body:expr) => ({
let $client = Client::new(rocket()).await.unwrap();
let $response = $client.req($method, $path).dispatch().await;
let $client = Client::new(rocket()).unwrap();
let $response = $client.req($method, $path).dispatch();
$body
})
}
#[rocket::async_test]
async fn test_root() {
#[test]
fn test_root() {
// Check that the redirect works.
for method in &[Get, Head] {
dispatch!(*method, "/", |client, response| {
@ -34,13 +34,13 @@ async fn test_root() {
let expected = Template::show(client.cargo(), "error/404", &map).unwrap();
assert_eq!(response.status(), Status::NotFound);
assert_eq!(response.into_string().await, Some(expected));
assert_eq!(response.into_string(), Some(expected));
});
}
}
#[rocket::async_test]
async fn test_name() {
#[test]
fn test_name() {
// Check that the /hello/<name> route works.
dispatch!(Get, "/hello/Jack%20Daniels", |client, response| {
let context = TemplateContext {
@ -52,12 +52,12 @@ async fn test_name() {
let expected = Template::show(client.cargo(), "index", &context).unwrap();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await, Some(expected));
assert_eq!(response.into_string(), Some(expected));
});
}
#[rocket::async_test]
async fn test_404() {
#[test]
fn test_404() {
// Check that the error catcher works.
dispatch!(Get, "/hello/", |client, response| {
let mut map = std::collections::HashMap::new();
@ -65,6 +65,6 @@ async fn test_404() {
let expected = Template::show(client.cargo(), "error/404", &map).unwrap();
assert_eq!(response.status(), Status::NotFound);
assert_eq!(response.into_string().await, Some(expected));
assert_eq!(response.into_string(), Some(expected));
});
}

View File

@ -1,10 +1,10 @@
use rocket::{self, local::asynchronous::Client};
use rocket::{self, local::blocking::Client};
#[rocket::async_test]
async fn hello_world() {
let client = Client::new(super::rocket()).await.unwrap();
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await, Some("Hello, Rust 2018!".into()));
#[test]
fn hello_world() {
let client = Client::new(super::rocket()).unwrap();
let response = client.get("/").dispatch();
assert_eq!(response.into_string(), Some("Hello, Rust 2018!".into()));
}
// Tests unrelated to the example.
@ -31,19 +31,19 @@ mod scoped_uri_tests {
.mount("/", rocket::routes![inner::hello])
}
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
#[rocket::async_test]
async fn test_inner_hello() {
let client = Client::new(rocket()).await.unwrap();
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await, Some("Hello! Try /Rust%202018.".into()));
#[test]
fn test_inner_hello() {
let client = Client::new(rocket()).unwrap();
let response = client.get("/").dispatch();
assert_eq!(response.into_string(), Some("Hello! Try /Rust%202018.".into()));
}
#[rocket::async_test]
async fn test_hello_name() {
let client = Client::new(rocket()).await.unwrap();
let response = client.get("/Rust%202018").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "Hello, Rust 2018! This is /Rust%202018.");
#[test]
fn test_hello_name() {
let client = Client::new(rocket()).unwrap();
let response = client.get("/Rust%202018").dispatch();
assert_eq!(response.into_string().unwrap(), "Hello, Rust 2018! This is /Rust%202018.");
}
}

View File

@ -1,34 +1,34 @@
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
async fn test(uri: String, expected: String) {
let client = Client::new(super::rocket()).await.unwrap();
assert_eq!(client.get(&uri).dispatch().await.into_string().await, Some(expected));
fn test(uri: String, expected: String) {
let client = Client::new(super::rocket()).unwrap();
assert_eq!(client.get(&uri).dispatch().into_string(), Some(expected));
}
async fn test_404(uri: &'static str) {
let client = Client::new(super::rocket()).await.unwrap();
assert_eq!(client.get(uri).dispatch().await.status(), Status::NotFound);
fn test_404(uri: &'static str) {
let client = Client::new(super::rocket()).unwrap();
assert_eq!(client.get(uri).dispatch().status(), Status::NotFound);
}
#[rocket::async_test]
async fn test_hello() {
#[test]
fn test_hello() {
for &(name, age) in &[("Mike", 22), ("Michael", 80), ("A", 0), ("a", 127)] {
test(format!("/hello/{}/{}", name, age),
format!("Hello, {} year old named {}!", age, name)).await;
format!("Hello, {} year old named {}!", age, name));
}
}
#[rocket::async_test]
async fn test_failing_hello() {
test_404("/hello/Mike/1000").await;
test_404("/hello/Mike/-129").await;
test_404("/hello/Mike/-1").await;
#[test]
fn test_failing_hello() {
test_404("/hello/Mike/1000");
test_404("/hello/Mike/-129");
test_404("/hello/Mike/-1");
}
#[rocket::async_test]
async fn test_hi() {
#[test]
fn test_hi() {
for name in &["Mike", "A", "123", "hi", "c"] {
test(format!("/hello/{}", name), name.to_string()).await;
test(format!("/hello/{}", name), name.to_string());
}
}

View File

@ -1,8 +1,8 @@
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
#[rocket::async_test]
async fn hello_world() {
let client = Client::new(super::rocket()).await.unwrap();
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await, Some("Hello, world!".into()));
#[test]
fn hello_world() {
let client = Client::new(super::rocket()).unwrap();
let response = client.get("/").dispatch();
assert_eq!(response.into_string(), Some("Hello, world!".into()));
}

View File

@ -1,71 +1,71 @@
use crate::rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{Status, ContentType};
#[rocket::async_test]
async fn bad_get_put() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn bad_get_put() {
let client = Client::new(rocket()).unwrap();
// Try to get a message with an ID that doesn't exist.
let res = client.get("/message/99").header(ContentType::JSON).dispatch().await;
let res = client.get("/message/99").header(ContentType::JSON).dispatch();
assert_eq!(res.status(), Status::NotFound);
let body = res.into_string().await.unwrap();
let body = res.into_string().unwrap();
assert!(body.contains("error"));
assert!(body.contains("Resource was not found."));
// Try to get a message with an invalid ID.
let res = client.get("/message/hi").header(ContentType::JSON).dispatch().await;
let res = client.get("/message/hi").header(ContentType::JSON).dispatch();
assert_eq!(res.status(), Status::NotFound);
assert!(res.into_string().await.unwrap().contains("error"));
assert!(res.into_string().unwrap().contains("error"));
// Try to put a message without a proper body.
let res = client.put("/message/80").header(ContentType::JSON).dispatch().await;
let res = client.put("/message/80").header(ContentType::JSON).dispatch();
assert_eq!(res.status(), Status::BadRequest);
// Try to put a message for an ID that doesn't exist.
let res = client.put("/message/80")
.header(ContentType::JSON)
.body(r#"{ "contents": "Bye bye, world!" }"#)
.dispatch().await;
.dispatch();
assert_eq!(res.status(), Status::NotFound);
}
#[rocket::async_test]
async fn post_get_put_get() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn post_get_put_get() {
let client = Client::new(rocket()).unwrap();
// Check that a message with ID 1 doesn't exist.
let res = client.get("/message/1").header(ContentType::JSON).dispatch().await;
let res = client.get("/message/1").header(ContentType::JSON).dispatch();
assert_eq!(res.status(), Status::NotFound);
// Add a new message with ID 1.
let res = client.post("/message/1")
.header(ContentType::JSON)
.body(r#"{ "contents": "Hello, world!" }"#)
.dispatch().await;
.dispatch();
assert_eq!(res.status(), Status::Ok);
// Check that the message exists with the correct contents.
let res = client.get("/message/1").header(ContentType::JSON).dispatch().await;
let res = client.get("/message/1").header(ContentType::JSON).dispatch();
assert_eq!(res.status(), Status::Ok);
let body = res.into_string().await.unwrap();
let body = res.into_string().unwrap();
assert!(body.contains("Hello, world!"));
// Change the message contents.
let res = client.put("/message/1")
.header(ContentType::JSON)
.body(r#"{ "contents": "Bye bye, world!" }"#)
.dispatch().await;
.dispatch();
assert_eq!(res.status(), Status::Ok);
// Check that the message exists with the updated contents.
let res = client.get("/message/1").header(ContentType::JSON).dispatch().await;
let res = client.get("/message/1").header(ContentType::JSON).dispatch();
assert_eq!(res.status(), Status::Ok);
let body = res.into_string().await.unwrap();
let body = res.into_string().unwrap();
assert!(!body.contains("Hello, world!"));
assert!(body.contains("Bye bye, world!"));
}

View File

@ -1,13 +1,13 @@
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
#[rocket::async_test]
async fn test_push_pop() {
let client = Client::new(super::rocket()).await.unwrap();
#[test]
fn test_push_pop() {
let client = Client::new(super::rocket()).unwrap();
let response = client.put("/push?event=test1").dispatch().await;
let response = client.put("/push?event=test1").dispatch();
assert_eq!(response.status(), Status::Ok);
let response = client.get("/pop").dispatch().await;
assert_eq!(response.into_string().await, Some("test1".to_string()));
let response = client.get("/pop").dispatch();
assert_eq!(response.into_string(), Some("test1".to_string()));
}

View File

@ -1,14 +1,12 @@
use super::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{ContentType, Status};
fn test(uri: &str, content_type: ContentType, status: Status, body: String) {
rocket::async_test(async move {
let client = Client::new(rocket()).await.unwrap();
let response = client.get(uri).header(content_type).dispatch().await;
let client = Client::new(rocket()).unwrap();
let response = client.get(uri).header(content_type).dispatch();
assert_eq!(response.status(), status);
assert_eq!(response.into_string().await, Some(body));
})
assert_eq!(response.into_string(), Some(body));
}
#[test]
@ -30,9 +28,9 @@ fn test_echo() {
test(&uri, ContentType::Plain, Status::Ok, "echo this text".into());
}
#[rocket::async_test]
async fn test_upload() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn test_upload() {
let client = Client::new(rocket()).unwrap();
let expected_body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
sed do eiusmod tempor incididunt ut labore et dolore \
magna aliqua".to_string();
@ -41,14 +39,14 @@ async fn test_upload() {
let response = client.post("/upload")
.header(ContentType::Plain)
.body(&expected_body)
.dispatch().await;
.dispatch();
assert_eq!(response.status(), Status::Ok);
// Ensure we get back the same body.
let response = client.get("/upload").dispatch().await;
let response = client.get("/upload").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await, Some(expected_body));
assert_eq!(response.into_string(), Some(expected_body));
}
#[test]

View File

@ -1,5 +1,5 @@
use crate::rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{Status, ContentType};
#[derive(Serialize, Deserialize)]
@ -8,27 +8,27 @@ struct Message {
contents: String
}
#[rocket::async_test]
async fn msgpack_get() {
let client = Client::new(rocket()).await.unwrap();
let res = client.get("/message/1").header(ContentType::MsgPack).dispatch().await;
#[test]
fn msgpack_get() {
let client = Client::new(rocket()).unwrap();
let res = client.get("/message/1").header(ContentType::MsgPack).dispatch();
assert_eq!(res.status(), Status::Ok);
assert_eq!(res.content_type(), Some(ContentType::MsgPack));
// Check that the message is `[1, "Hello, world!"]`
assert_eq!(&res.into_bytes().await.unwrap(),
assert_eq!(&res.into_bytes().unwrap(),
&[146, 1, 173, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]);
}
#[rocket::async_test]
async fn msgpack_post() {
#[test]
fn msgpack_post() {
// Dispatch request with a message of `[2, "Goodbye, world!"]`.
let client = Client::new(rocket()).await.unwrap();
let client = Client::new(rocket()).unwrap();
let res = client.post("/message")
.header(ContentType::MsgPack)
.body(&[146, 2, 175, 71, 111, 111, 100, 98, 121, 101, 44, 32, 119, 111, 114, 108, 100, 33])
.dispatch().await;
.dispatch();
assert_eq!(res.status(), Status::Ok);
assert_eq!(res.into_string().await, Some("Goodbye, world!".into()));
assert_eq!(res.into_string(), Some("Goodbye, world!".into()));
}

View File

@ -1,30 +1,30 @@
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
async fn test_200(uri: &str, expected_body: &str) {
let client = Client::new(super::rocket()).await.unwrap();
let response = client.get(uri).dispatch().await;
fn test_200(uri: &str, expected_body: &str) {
let client = Client::new(super::rocket()).unwrap();
let response = client.get(uri).dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await, Some(expected_body.to_string()));
assert_eq!(response.into_string(), Some(expected_body.to_string()));
}
async fn test_303(uri: &str, expected_location: &str) {
let client = Client::new(super::rocket()).await.unwrap();
let response = client.get(uri).dispatch().await;
fn test_303(uri: &str, expected_location: &str) {
let client = Client::new(super::rocket()).unwrap();
let response = client.get(uri).dispatch();
let location_headers: Vec<_> = response.headers().get("Location").collect();
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(location_headers, vec![expected_location]);
}
#[rocket::async_test]
async fn test() {
test_200("/users/Sergio", "Hello, Sergio!").await;
#[test]
fn test() {
test_200("/users/Sergio", "Hello, Sergio!");
test_200("/users/login",
"Hi! That user doesn't exist. Maybe you need to log in?").await;
"Hi! That user doesn't exist. Maybe you need to log in?");
}
#[rocket::async_test]
async fn test_redirects() {
test_303("/", "/users/login").await;
test_303("/users/unknown", "/users/login").await;
#[test]
fn test_redirects() {
test_303("/", "/users/login");
test_303("/users/unknown", "/users/login");
}

View File

@ -1,59 +1,59 @@
use super::{rocket, index};
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{Status, ContentType};
fn extract_id(from: &str) -> Option<String> {
from.rfind('/').map(|i| &from[(i + 1)..]).map(|s| s.trim_end().to_string())
}
#[rocket::async_test]
async fn check_index() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn check_index() {
let client = Client::new(rocket()).unwrap();
// Ensure the index returns what we expect.
let response = client.get("/").dispatch().await;
let response = client.get("/").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.content_type(), Some(ContentType::Plain));
assert_eq!(response.into_string().await, Some(index().into()))
assert_eq!(response.into_string(), Some(index().into()))
}
async fn upload_paste(client: &Client, body: &str) -> String {
let response = client.post("/").body(body).dispatch().await;
fn upload_paste(client: &Client, body: &str) -> String {
let response = client.post("/").body(body).dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.content_type(), Some(ContentType::Plain));
extract_id(&response.into_string().await.unwrap()).unwrap()
extract_id(&response.into_string().unwrap()).unwrap()
}
async fn download_paste(client: &Client, id: &str) -> String {
let response = client.get(format!("/{}", id)).dispatch().await;
fn download_paste(client: &Client, id: &str) -> String {
let response = client.get(format!("/{}", id)).dispatch();
assert_eq!(response.status(), Status::Ok);
response.into_string().await.unwrap()
response.into_string().unwrap()
}
#[rocket::async_test]
async fn pasting() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn pasting() {
let client = Client::new(rocket()).unwrap();
// Do a trivial upload, just to make sure it works.
let body_1 = "Hello, world!";
let id_1 = upload_paste(&client, body_1).await;
assert_eq!(download_paste(&client, &id_1).await, body_1);
let id_1 = upload_paste(&client, body_1);
assert_eq!(download_paste(&client, &id_1), body_1);
// Make sure we can keep getting that paste.
assert_eq!(download_paste(&client, &id_1).await, body_1);
assert_eq!(download_paste(&client, &id_1).await, body_1);
assert_eq!(download_paste(&client, &id_1).await, body_1);
assert_eq!(download_paste(&client, &id_1), body_1);
assert_eq!(download_paste(&client, &id_1), body_1);
assert_eq!(download_paste(&client, &id_1), body_1);
// Upload some unicode.
let body_2 = "こんにちは";
let id_2 = upload_paste(&client, body_2).await;
assert_eq!(download_paste(&client, &id_2).await, body_2);
let id_2 = upload_paste(&client, body_2);
assert_eq!(download_paste(&client, &id_2), body_2);
// Make sure we can get both pastes.
assert_eq!(download_paste(&client, &id_1).await, body_1);
assert_eq!(download_paste(&client, &id_2).await, body_2);
assert_eq!(download_paste(&client, &id_1).await, body_1);
assert_eq!(download_paste(&client, &id_2).await, body_2);
assert_eq!(download_paste(&client, &id_1), body_1);
assert_eq!(download_paste(&client, &id_2), body_2);
assert_eq!(download_paste(&client, &id_1), body_1);
assert_eq!(download_paste(&client, &id_2), body_2);
// Now a longer upload.
let body_3 = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
@ -63,8 +63,8 @@ async fn pasting() {
in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.";
let id_3 = upload_paste(&client, body_3).await;
assert_eq!(download_paste(&client, &id_3).await, body_3);
assert_eq!(download_paste(&client, &id_1).await, body_1);
assert_eq!(download_paste(&client, &id_2).await, body_2);
let id_3 = upload_paste(&client, body_3);
assert_eq!(download_paste(&client, &id_3), body_3);
assert_eq!(download_paste(&client, &id_1), body_1);
assert_eq!(download_paste(&client, &id_2), body_2);
}

View File

@ -1,77 +1,77 @@
use super::rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
macro_rules! run_test {
($query:expr, |$response:ident| $body:expr) => ({
let client = Client::new(rocket()).await.unwrap();
let client = Client::new(rocket()).unwrap();
#[allow(unused_mut)]
let mut $response = client.get(format!("/hello{}", $query)).dispatch().await;
let mut $response = client.get(format!("/hello{}", $query)).dispatch();
$body
})
}
#[rocket::async_test]
async fn age_and_name_params() {
#[test]
fn age_and_name_params() {
run_test!("?age=10&first-name=john", |response| {
assert_eq!(response.into_string().await,
assert_eq!(response.into_string(),
Some("Hello, 10 year old named john!".into()));
});
run_test!("?age=20&first-name=john", |response| {
assert_eq!(response.into_string().await,
assert_eq!(response.into_string(),
Some("20 years old? Hi, john!".into()));
});
}
#[rocket::async_test]
async fn age_param_only() {
#[test]
fn age_param_only() {
run_test!("?age=10", |response| {
assert_eq!(response.into_string().await,
assert_eq!(response.into_string(),
Some("We're gonna need a name, and only a name.".into()));
});
run_test!("?age=20", |response| {
assert_eq!(response.into_string().await,
assert_eq!(response.into_string(),
Some("We're gonna need a name, and only a name.".into()));
});
}
#[rocket::async_test]
async fn name_param_only() {
#[test]
fn name_param_only() {
run_test!("?first-name=John", |response| {
assert_eq!(response.into_string().await, Some("Hello John!".into()));
assert_eq!(response.into_string(), Some("Hello John!".into()));
});
}
#[rocket::async_test]
async fn no_params() {
#[test]
fn no_params() {
run_test!("", |response| {
assert_eq!(response.into_string().await,
assert_eq!(response.into_string(),
Some("We're gonna need a name, and only a name.".into()));
});
run_test!("?", |response| {
assert_eq!(response.into_string().await,
assert_eq!(response.into_string(),
Some("We're gonna need a name, and only a name.".into()));
});
}
#[rocket::async_test]
async fn extra_params() {
#[test]
fn extra_params() {
run_test!("?age=20&first-name=Bob&extra", |response| {
assert_eq!(response.into_string().await,
assert_eq!(response.into_string(),
Some("20 years old? Hi, Bob!".into()));
});
run_test!("?age=30&first-name=Bob&extra", |response| {
assert_eq!(response.into_string().await,
assert_eq!(response.into_string(),
Some("We're gonna need a name, and only a name.".into()));
});
}
#[rocket::async_test]
async fn wrong_path() {
#[test]
fn wrong_path() {
run_test!("/other?age=20&first-name=Bob", |response| {
assert_eq!(response.status(), Status::NotFound);
});

View File

@ -1,30 +1,30 @@
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
async fn test(uri: String, expected: String) {
let client = Client::new(super::rocket()).await.unwrap();
let response = client.get(&uri).dispatch().await;
assert_eq!(response.into_string().await, Some(expected));
fn test(uri: String, expected: String) {
let client = Client::new(super::rocket()).unwrap();
let response = client.get(&uri).dispatch();
assert_eq!(response.into_string(), Some(expected));
}
#[rocket::async_test]
async fn test_hello() {
#[test]
fn test_hello() {
for &(name, age) in &[("Mike", 22), ("Michael", 80), ("A", 0), ("a", 127)] {
test(format!("/hello/{}/{}", name, age),
format!("Hello, {} year old named {}!", age, name)).await;
format!("Hello, {} year old named {}!", age, name));
}
}
#[rocket::async_test]
async fn test_failing_hello_hi() {
#[test]
fn test_failing_hello_hi() {
// Invalid integers.
for &(name, age) in &[("Mike", 1000), ("Michael", 128), ("A", -800), ("a", -200)] {
test(format!("/hello/{}/{}", name, age),
format!("Hi {}! Your age ({}) is kind of funky.", name, age)).await;
format!("Hi {}! Your age ({}) is kind of funky.", name, age));
}
// Non-integers.
for &(name, age) in &[("Mike", "!"), ("Michael", "hi"), ("A", "blah"), ("a", "0-1")] {
test(format!("/hello/{}/{}", name, age),
format!("Hi {}! Your age ({}) is kind of funky.", name, age)).await;
format!("Hi {}! Your age ({}) is kind of funky.", name, age));
}
}

View File

@ -1,9 +1,9 @@
use super::rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
#[rocket::async_test]
async fn hello() {
let client = Client::new(rocket()).await.unwrap();
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await, Some("Rocketeer".into()));
#[test]
fn hello() {
let client = Client::new(rocket()).unwrap();
let response = client.get("/").dispatch();
assert_eq!(response.into_string(), Some("Rocketeer".into()));
}

View File

@ -1,4 +1,4 @@
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{Status, ContentType};
use std::env;
@ -7,28 +7,28 @@ use std::fs::{self, File};
const UPLOAD_CONTENTS: &str = "Hey! I'm going to be uploaded. :D Yay!";
#[rocket::async_test]
async fn test_index() {
let client = Client::new(super::rocket()).await.unwrap();
let res = client.get("/").dispatch().await;
assert_eq!(res.into_string().await, Some(super::index().to_string()));
#[test]
fn test_index() {
let client = Client::new(super::rocket()).unwrap();
let res = client.get("/").dispatch();
assert_eq!(res.into_string(), Some(super::index().to_string()));
}
#[rocket::async_test]
async fn test_raw_upload() {
#[test]
fn test_raw_upload() {
// Delete the upload file before we begin.
let upload_file = env::temp_dir().join("upload.txt");
let _ = fs::remove_file(&upload_file);
// Do the upload. Make sure we get the expected results.
let client = Client::new(super::rocket()).await.unwrap();
let client = Client::new(super::rocket()).unwrap();
let res = client.post("/upload")
.header(ContentType::Plain)
.body(UPLOAD_CONTENTS)
.dispatch().await;
.dispatch();
assert_eq!(res.status(), Status::Ok);
assert_eq!(res.into_string().await, Some(UPLOAD_CONTENTS.len().to_string()));
assert_eq!(res.into_string(), Some(UPLOAD_CONTENTS.len().to_string()));
// Ensure we find the body in the /tmp/upload.txt file.
let mut file_contents = String::new();

View File

@ -1,15 +1,15 @@
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
async fn client() -> Client {
fn client() -> Client {
let rocket = rocket::ignite().mount("/", routes![super::root, super::login]);
Client::new(rocket).await.unwrap()
Client::new(rocket).unwrap()
}
#[rocket::async_test]
async fn test_root() {
let client = client().await;
let response = client.get("/").dispatch().await;
#[test]
fn test_root() {
let client = client();
let response = client.get("/").dispatch();
assert!(response.body().is_none());
assert_eq!(response.status(), Status::SeeOther);
@ -22,9 +22,9 @@ async fn test_root() {
}
}
#[rocket::async_test]
async fn test_login() {
let client = client().await;
let r = client.get("/login").dispatch().await;
assert_eq!(r.into_string().await, Some("Hi! Please log in before continuing.".into()));
#[test]
fn test_login() {
let client = client();
let r = client.get("/login").dispatch();
assert_eq!(r.into_string(), Some("Hi! Please log in before continuing.".into()));
}

View File

@ -29,29 +29,29 @@ fn rocket() -> rocket::Rocket {
#[cfg(test)]
mod test {
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Header;
async fn test_header_count<'h>(headers: Vec<Header<'static>>) {
let client = Client::new(super::rocket()).await.unwrap();
fn test_header_count<'h>(headers: Vec<Header<'static>>) {
let client = Client::new(super::rocket()).unwrap();
let mut req = client.get("/");
for header in headers.iter().cloned() {
req.add_header(header);
}
let response = req.dispatch().await;
let response = req.dispatch();
let expect = format!("Your request contained {} headers!", headers.len());
assert_eq!(response.into_string().await, Some(expect));
assert_eq!(response.into_string(), Some(expect));
}
#[rocket::async_test]
async fn test_n_headers() {
#[test]
fn test_n_headers() {
for i in 0..50 {
let headers = (0..i)
.map(|n| Header::new(n.to_string(), n.to_string()))
.collect();
test_header_count(headers).await;
test_header_count(headers);
}
}
}

View File

@ -1,18 +1,18 @@
use std::sync::atomic::Ordering;
use super::{rocket, Atomics};
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
#[rocket::async_test]
async fn test() {
let client = Client::new(rocket()).await.unwrap();
client.get("/sync").dispatch().await;
#[test]
fn test() {
let client = Client::new(rocket()).unwrap();
client.get("/sync").dispatch();
let atomics = client.cargo().state::<Atomics>().unwrap();
assert_eq!(atomics.uncached.load(Ordering::Relaxed), 2);
assert_eq!(atomics.cached.load(Ordering::Relaxed), 1);
client.get("/async").dispatch().await;
client.get("/async").dispatch();
let atomics = client.cargo().state::<Atomics>().unwrap();
assert_eq!(atomics.uncached.load(Ordering::Relaxed), 4);

View File

@ -1,5 +1,5 @@
use super::rocket;
use rocket::local::asynchronous::{Client, LocalResponse};
use rocket::local::blocking::{Client, LocalResponse};
use rocket::http::{Status, Cookie, ContentType};
fn user_id_cookie(response: &LocalResponse<'_>) -> Option<Cookie<'static>> {
@ -12,58 +12,58 @@ fn user_id_cookie(response: &LocalResponse<'_>) -> Option<Cookie<'static>> {
cookie.map(|c| c.into_owned())
}
async fn login(client: &Client, user: &str, pass: &str) -> Option<Cookie<'static>> {
fn login(client: &Client, user: &str, pass: &str) -> Option<Cookie<'static>> {
let response = client.post("/login")
.header(ContentType::Form)
.body(format!("username={}&password={}", user, pass))
.dispatch().await;
.dispatch();
user_id_cookie(&response)
}
#[rocket::async_test]
async fn redirect_on_index() {
let client = Client::new(rocket()).await.unwrap();
let response = client.get("/").dispatch().await;
#[test]
fn redirect_on_index() {
let client = Client::new(rocket()).unwrap();
let response = client.get("/").dispatch();
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get_one("Location"), Some("/login"));
}
#[rocket::async_test]
async fn can_login() {
let client = Client::new(rocket()).await.unwrap();
#[test]
fn can_login() {
let client = Client::new(rocket()).unwrap();
let response = client.get("/login").dispatch().await;
let response = client.get("/login").dispatch();
assert_eq!(response.status(), Status::Ok);
let body = response.into_string().await.unwrap();
let body = response.into_string().unwrap();
assert!(body.contains("Please login to continue."));
}
#[rocket::async_test]
async fn login_fails() {
let client = Client::new(rocket()).await.unwrap();
assert!(login(&client, "Seergio", "password").await.is_none());
assert!(login(&client, "Sergio", "idontknow").await.is_none());
#[test]
fn login_fails() {
let client = Client::new(rocket()).unwrap();
assert!(login(&client, "Seergio", "password").is_none());
assert!(login(&client, "Sergio", "idontknow").is_none());
}
#[rocket::async_test]
async fn login_logout_succeeds() {
let client = Client::new(rocket()).await.unwrap();
let login_cookie = login(&client, "Sergio", "password").await.expect("logged in");
#[test]
fn login_logout_succeeds() {
let client = Client::new(rocket()).unwrap();
let login_cookie = login(&client, "Sergio", "password").expect("logged in");
// Ensure we're logged in.
let response = client.get("/").cookie(login_cookie.clone()).dispatch().await;
let response = client.get("/").cookie(login_cookie.clone()).dispatch();
assert_eq!(response.status(), Status::Ok);
let body = response.into_string().await.unwrap();
let body = response.into_string().unwrap();
assert!(body.contains("Logged in with user ID 1"));
// One more.
let response = client.get("/login").cookie(login_cookie.clone()).dispatch().await;
let response = client.get("/login").cookie(login_cookie.clone()).dispatch();
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get_one("Location"), Some("/"));
// Logout.
let response = client.post("/logout").cookie(login_cookie).dispatch().await;
let response = client.post("/logout").cookie(login_cookie).dispatch();
let cookie = user_id_cookie(&response).expect("logout cookie");
assert!(cookie.value().is_empty());
@ -72,9 +72,9 @@ async fn login_logout_succeeds() {
assert_eq!(response.headers().get_one("Location"), Some("/login"));
// The page should show the success message, and no errors.
let response = client.get("/login").dispatch().await;
let response = client.get("/login").dispatch();
assert_eq!(response.status(), Status::Ok);
let body = response.into_string().await.unwrap();
let body = response.into_string().unwrap();
assert!(body.contains("Successfully logged out."));
assert!(!body.contains("Error"));
}

View File

@ -1,28 +1,28 @@
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
async fn register_hit(client: &Client) {
let response = client.get("/").dispatch().await;
fn register_hit(client: &Client) {
let response = client.get("/").dispatch();
assert_eq!(response.status(), Status::Ok);
}
async fn get_count(client: &Client) -> usize {
let response = client.get("/count").dispatch().await;
response.into_string().await.and_then(|s| s.parse().ok()).unwrap()
fn get_count(client: &Client) -> usize {
let response = client.get("/count").dispatch();
response.into_string().and_then(|s| s.parse().ok()).unwrap()
}
#[rocket::async_test]
async fn test_count() {
let client = Client::new(super::rocket()).await.unwrap();
#[test]
fn test_count() {
let client = Client::new(super::rocket()).unwrap();
// Count should start at 0.
assert_eq!(get_count(&client).await, 0);
assert_eq!(get_count(&client), 0);
for _ in 0..99 { register_hit(&client).await; }
assert_eq!(get_count(&client).await, 99);
for _ in 0..99 { register_hit(&client); }
assert_eq!(get_count(&client), 99);
register_hit(&client).await;
assert_eq!(get_count(&client).await, 100);
register_hit(&client);
assert_eq!(get_count(&client), 100);
}
#[rocket::async_test]

View File

@ -1,19 +1,19 @@
use std::fs::File;
use std::io::Read;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
use super::rocket;
async fn test_query_file<T> (path: &str, file: T, status: Status)
fn test_query_file<T> (path: &str, file: T, status: Status)
where T: Into<Option<&'static str>>
{
let client = Client::new(rocket()).await.unwrap();
let response = client.get(path).dispatch().await;
let client = Client::new(rocket()).unwrap();
let response = client.get(path).dispatch();
assert_eq!(response.status(), status);
let body_data = response.into_bytes().await;
let body_data = response.into_bytes();
if let Some(filename) = file.into() {
let expected_data = read_file_content(filename);
assert!(body_data.map_or(false, |s| s == expected_data));
@ -28,29 +28,29 @@ fn read_file_content(path: &str) -> Vec<u8> {
file_content
}
#[rocket::async_test]
async fn test_index_html() {
test_query_file("/", "static/index.html", Status::Ok).await;
test_query_file("/?v=1", "static/index.html", Status::Ok).await;
test_query_file("/?this=should&be=ignored", "static/index.html", Status::Ok).await;
#[test]
fn test_index_html() {
test_query_file("/", "static/index.html", Status::Ok);
test_query_file("/?v=1", "static/index.html", Status::Ok);
test_query_file("/?this=should&be=ignored", "static/index.html", Status::Ok);
}
#[rocket::async_test]
async fn test_hidden_file() {
test_query_file("/hidden/hi.txt", "static/hidden/hi.txt", Status::Ok).await;
test_query_file("/hidden/hi.txt?v=1", "static/hidden/hi.txt", Status::Ok).await;
test_query_file("/hidden/hi.txt?v=1&a=b", "static/hidden/hi.txt", Status::Ok).await;
#[test]
fn test_hidden_file() {
test_query_file("/hidden/hi.txt", "static/hidden/hi.txt", Status::Ok);
test_query_file("/hidden/hi.txt?v=1", "static/hidden/hi.txt", Status::Ok);
test_query_file("/hidden/hi.txt?v=1&a=b", "static/hidden/hi.txt", Status::Ok);
}
#[rocket::async_test]
async fn test_icon_file() {
test_query_file("/rocket-icon.jpg", "static/rocket-icon.jpg", Status::Ok).await;
test_query_file("/rocket-icon.jpg", "static/rocket-icon.jpg", Status::Ok).await;
#[test]
fn test_icon_file() {
test_query_file("/rocket-icon.jpg", "static/rocket-icon.jpg", Status::Ok);
test_query_file("/rocket-icon.jpg", "static/rocket-icon.jpg", Status::Ok);
}
#[rocket::async_test]
async fn test_invalid_path() {
test_query_file("/thou_shalt_not_exist", None, Status::NotFound).await;
test_query_file("/thou/shalt/not/exist", None, Status::NotFound).await;
test_query_file("/thou/shalt/not/exist?a=b&c=d", None, Status::NotFound).await;
#[test]
fn test_invalid_path() {
test_query_file("/thou_shalt_not_exist", None, Status::NotFound);
test_query_file("/thou/shalt/not/exist", None, Status::NotFound);
test_query_file("/thou/shalt/not/exist?a=b&c=d", None, Status::NotFound);
}

View File

@ -1,32 +1,32 @@
use std::fs::{self, File};
use std::io::prelude::*;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
#[rocket::async_test]
async fn test_root() {
let client = Client::new(super::rocket()).await.unwrap();
let res = client.get("/").dispatch().await;
#[test]
fn test_root() {
let client = Client::new(super::rocket()).unwrap();
let res = client.get("/").dispatch();
// Check that we have exactly 25,000 'a'.
let res_str = res.into_string().await.unwrap();
let res_str = res.into_string().unwrap();
assert_eq!(res_str.len(), 25000);
for byte in res_str.as_bytes() {
assert_eq!(*byte, b'a');
}
}
#[rocket::async_test]
async fn test_file() {
#[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 client = Client::new(super::rocket()).await.unwrap();
let res = client.get("/big_file").dispatch().await;
assert_eq!(res.into_string().await, Some(CONTENTS.into()));
let client = Client::new(super::rocket()).unwrap();
let res = client.get("/big_file").dispatch();
assert_eq!(res.into_string(), Some(CONTENTS.into()));
// Delete the 'big_file'.
fs::remove_file(super::FILENAME).expect("remove big_file");

View File

@ -1,19 +1,19 @@
use super::rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Method::*;
use rocket::http::Status;
use rocket_contrib::templates::Template;
macro_rules! dispatch {
($method:expr, $path:expr, |$client:ident, $response:ident| $body:expr) => ({
let $client = Client::new(rocket()).await.unwrap();
let $response = $client.req($method, $path).dispatch().await;
let $client = Client::new(rocket()).unwrap();
let $response = $client.req($method, $path).dispatch();
$body
})
}
#[rocket::async_test]
async fn test_root() {
#[test]
fn test_root() {
// Check that the redirect works.
for method in &[Get, Head] {
dispatch!(*method, "/", |client, response| {
@ -33,13 +33,13 @@ async fn test_root() {
let expected = Template::show(client.cargo(), "error/404", &map).unwrap();
assert_eq!(response.status(), Status::NotFound);
assert_eq!(response.into_string().await, Some(expected));
assert_eq!(response.into_string(), Some(expected));
});
}
}
#[rocket::async_test]
async fn test_name() {
#[test]
fn test_name() {
// Check that the /hello/<name> route works.
dispatch!(Get, "/hello/Jack", |client, response| {
let context = super::TemplateContext {
@ -49,12 +49,12 @@ async fn test_name() {
let expected = Template::show(client.cargo(), "index", &context).unwrap();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await, Some(expected));
assert_eq!(response.into_string(), Some(expected));
});
}
#[rocket::async_test]
async fn test_404() {
#[test]
fn test_404() {
// Check that the error catcher works.
dispatch!(Get, "/hello/", |client, response| {
let mut map = std::collections::HashMap::new();
@ -62,6 +62,6 @@ async fn test_404() {
let expected = Template::show(client.cargo(), "error/404", &map).unwrap();
assert_eq!(response.status(), Status::NotFound);
assert_eq!(response.into_string().await, Some(expected));
assert_eq!(response.into_string(), Some(expected));
});
}

View File

@ -15,14 +15,25 @@ fn rocket() -> rocket::Rocket {
#[cfg(test)]
mod test {
use super::rocket;
use rocket::local::asynchronous::Client;
use rocket::http::Status;
#[rocket::async_test]
async fn test_hello() {
async fn test_hello_async() {
use rocket::local::asynchronous::Client;
let client = Client::new(rocket()).await.unwrap();
let response = client.get("/").dispatch().await;
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await, Some("Hello, world!".into()));
}
#[test]
fn test_hello_blocking() {
use rocket::local::blocking::Client;
let client = Client::new(rocket()).unwrap();
let response = client.get("/").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string(), Some("Hello, world!".into()));
}
}

View File

@ -1,8 +1,8 @@
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
#[rocket::async_test]
async fn hello_world() {
let client = Client::new(super::rocket()).await.unwrap();
let response = client.get("/").dispatch().await;
assert_eq!(response.into_string().await, Some("Hello, world!".into()));
#[test]
fn hello_world() {
let client = Client::new(super::rocket()).unwrap();
let response = client.get("/").dispatch();
assert_eq!(response.into_string(), Some("Hello, world!".into()));
}

View File

@ -3,7 +3,7 @@ use super::task::Task;
use parking_lot::Mutex;
use rand::{Rng, thread_rng, distributions::Alphanumeric};
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::{Status, ContentType};
// We use a lock to synchronize between tests so DB operations don't collide.
@ -15,16 +15,14 @@ macro_rules! run_test {
(|$client:ident, $conn:ident| $block:expr) => ({
let _lock = DB_LOCK.lock();
rocket::async_test(async move {
let mut rocket = super::rocket();
let db = super::DbConn::get_one(rocket.inspect().await);
let $client = Client::new(rocket).await.expect("Rocket client");
let rocket = super::rocket();
let $client = Client::new(rocket).expect("Rocket client");
let db = super::DbConn::get_one($client.cargo());
let $conn = db.expect("failed to get database connection for testing");
Task::delete_all(&$conn).expect("failed to delete all tasks for testing");
$block
})
})
}
#[test]
@ -37,7 +35,7 @@ fn test_insertion_deletion() {
client.post("/todo")
.header(ContentType::Form)
.body("description=My+first+task")
.dispatch().await;
.dispatch();
// Ensure we have one more task in the database.
let new_tasks = Task::all(&conn).unwrap();
@ -49,7 +47,7 @@ fn test_insertion_deletion() {
// Issue a request to delete the task.
let id = new_tasks[0].id.unwrap();
client.delete(format!("/todo/{}", id)).dispatch().await;
client.delete(format!("/todo/{}", id)).dispatch();
// Ensure it's gone.
let final_tasks = Task::all(&conn).unwrap();
@ -67,17 +65,17 @@ fn test_toggle() {
client.post("/todo")
.header(ContentType::Form)
.body("description=test_for_completion")
.dispatch().await;
.dispatch();
let task = Task::all(&conn).unwrap()[0].clone();
assert_eq!(task.completed, false);
// Issue a request to toggle the task; ensure it is completed.
client.put(format!("/todo/{}", task.id.unwrap())).dispatch().await;
client.put(format!("/todo/{}", task.id.unwrap())).dispatch();
assert_eq!(Task::all(&conn).unwrap()[0].completed, true);
// Issue a request to toggle the task; ensure it's not completed again.
client.put(format!("/todo/{}", task.id.unwrap())).dispatch().await;
client.put(format!("/todo/{}", task.id.unwrap())).dispatch();
assert_eq!(Task::all(&conn).unwrap()[0].completed, false);
})
}
@ -97,7 +95,7 @@ fn test_many_insertions() {
client.post("/todo")
.header(ContentType::Form)
.body(format!("description={}", desc))
.dispatch().await;
.dispatch();
// Record the description we choose for this iteration.
descs.insert(0, desc);
@ -119,7 +117,7 @@ fn test_bad_form_submissions() {
// Submit an empty form. We should get a 422 but no flash error.
let res = client.post("/todo")
.header(ContentType::Form)
.dispatch().await;
.dispatch();
let mut cookies = res.headers().get("Set-Cookie");
assert_eq!(res.status(), Status::UnprocessableEntity);
@ -130,7 +128,7 @@ fn test_bad_form_submissions() {
let res = client.post("/todo")
.header(ContentType::Form)
.body("description=")
.dispatch().await;
.dispatch();
let mut cookies = res.headers().get("Set-Cookie");
assert!(cookies.any(|value| value.contains("error")));
@ -139,7 +137,7 @@ fn test_bad_form_submissions() {
let res = client.post("/todo")
.header(ContentType::Form)
.body("evil=smile")
.dispatch().await;
.dispatch();
let mut cookies = res.headers().get("Set-Cookie");
assert_eq!(res.status(), Status::UnprocessableEntity);

View File

@ -1,25 +1,25 @@
use super::rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
async fn test(uri: &str, expected: &str) {
let client = Client::new(rocket()).await.unwrap();
let res = client.get(uri).dispatch().await;
assert_eq!(res.into_string().await, Some(expected.into()));
fn test(uri: &str, expected: &str) {
let client = Client::new(rocket()).unwrap();
let res = client.get(uri).dispatch();
assert_eq!(res.into_string(), Some(expected.into()));
}
async fn test_404(uri: &str) {
let client = Client::new(rocket()).await.unwrap();
let res = client.get(uri).dispatch().await;
fn test_404(uri: &str) {
let client = Client::new(rocket()).unwrap();
let res = client.get(uri).dispatch();
assert_eq!(res.status(), Status::NotFound);
}
#[rocket::async_test]
async fn test_people() {
test("/people/7f205202-7ba1-4c39-b2fc-3e630722bf9f", "We found: Lacy").await;
test("/people/4da34121-bc7d-4fc1-aee6-bf8de0795333", "We found: Bob").await;
test("/people/ad962969-4e3d-4de7-ac4a-2d86d6d10839", "We found: George").await;
#[test]
fn test_people() {
test("/people/7f205202-7ba1-4c39-b2fc-3e630722bf9f", "We found: Lacy");
test("/people/4da34121-bc7d-4fc1-aee6-bf8de0795333", "We found: Bob");
test("/people/ad962969-4e3d-4de7-ac4a-2d86d6d10839", "We found: George");
test("/people/e18b3a5c-488f-4159-a240-2101e0da19fd",
"Person not found for UUID: e18b3a5c-488f-4159-a240-2101e0da19fd").await;
test_404("/people/invalid_uuid").await;
"Person not found for UUID: e18b3a5c-488f-4159-a240-2101e0da19fd");
test_404("/people/invalid_uuid");
}

View File

@ -103,7 +103,7 @@ use rocket::http::{ContentType, Status};
let rocket = rocket::ignite().mount("/", routes![hello]);
let client = Client::new(rocket).expect("valid rocket instance");
let mut response = client.get("/").dispatch().await;
let mut response = client.get("/").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.content_type(), Some(ContentType::Plain));
@ -148,7 +148,7 @@ First, we'll create a `test` module with the proper imports:
#[cfg(test)]
mod test {
use super::rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
#[test]
@ -167,12 +167,6 @@ You can also move the body of the `test` module into its own file, say
### Testing
First, note the `#[rocket::async_test]` attribute. Rust does not support `async
fn` for tests, so an asynchronous runtime needs to be set up. In most
applications this is done by `launch()`, but we are deliberately not calling
that in tests! Instead, we use `#[rocket::async_test]`, which runs the test
inside a runtime.
To test our "Hello, world!" application, we create a `Client` for our
`Rocket` instance. It's okay to use methods like `expect` and `unwrap` during
testing: we _want_ our tests to panic when something goes wrong.
@ -217,7 +211,7 @@ use rocket::http::{ContentType, Status};
# let mut response = client.get("/").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await, Some("Hello, world!".into()));
assert_eq!(response.into_string(), Some("Hello, world!".into()));
```
That's it! Altogether, this looks like:
@ -240,7 +234,7 @@ fn rocket() -> rocket::Rocket {
# */
mod test {
use super::rocket;
use rocket::local::asynchronous::Client;
use rocket::local::blocking::Client;
use rocket::http::Status;
# /*
@ -248,9 +242,9 @@ mod test {
# */ pub
fn hello_world() {
let client = Client::new(rocket()).expect("valid rocket instance");
let mut response = client.get("/").dispatch().await;
let mut response = client.get("/").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().await, Some("Hello, world!".into()));
assert_eq!(response.into_string(), Some("Hello, world!".into()));
}
}