mirror of https://github.com/rwf2/Rocket.git
Use the blocking testing API everywhere.
Co-authored-by: Sergio Benitez <sb@sergio.bz>
This commit is contained in:
parent
6482fa2fba
commit
06975bfaea
|
@ -328,12 +328,11 @@ impl Template {
|
||||||
/// use std::collections::HashMap;
|
/// use std::collections::HashMap;
|
||||||
///
|
///
|
||||||
/// use rocket_contrib::templates::Template;
|
/// use rocket_contrib::templates::Template;
|
||||||
/// use rocket::local::asynchronous::Client;
|
/// use rocket::local::blocking::Client;
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// # rocket::async_test(async {
|
|
||||||
/// let rocket = rocket::ignite().attach(Template::fairing());
|
/// 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`.
|
/// // Create a `context`. Here, just an empty `HashMap`.
|
||||||
/// let mut context = HashMap::new();
|
/// let mut context = HashMap::new();
|
||||||
|
@ -341,7 +340,6 @@ impl Template {
|
||||||
/// # context.insert("test", "test");
|
/// # context.insert("test", "test");
|
||||||
/// # #[allow(unused_variables)]
|
/// # #[allow(unused_variables)]
|
||||||
/// let template = Template::show(client.cargo(), "index", context);
|
/// let template = Template::show(client.cargo(), "index", context);
|
||||||
/// # });
|
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline]
|
||||||
|
|
|
@ -9,7 +9,7 @@ mod compress_responder_tests {
|
||||||
use rocket::http::hyper::header::{ContentEncoding, Encoding};
|
use rocket::http::hyper::header::{ContentEncoding, Encoding};
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
use rocket::http::{ContentType, Header};
|
use rocket::http::{ContentType, Header};
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::response::{Content, Response};
|
use rocket::response::{Content, Response};
|
||||||
use rocket_contrib::compression::Compress;
|
use rocket_contrib::compression::Compress;
|
||||||
|
|
||||||
|
|
|
@ -10,7 +10,7 @@ mod compression_fairing_tests {
|
||||||
use rocket::http::hyper::header::{ContentEncoding, Encoding};
|
use rocket::http::hyper::header::{ContentEncoding, Encoding};
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
use rocket::http::{ContentType, Header};
|
use rocket::http::{ContentType, Header};
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::response::{Content, Response};
|
use rocket::response::{Content, Response};
|
||||||
use rocket_contrib::compression::Compression;
|
use rocket_contrib::compression::Compression;
|
||||||
|
|
||||||
|
|
|
@ -7,7 +7,7 @@ extern crate rocket;
|
||||||
#[cfg(feature = "helmet")]
|
#[cfg(feature = "helmet")]
|
||||||
mod helmet_tests {
|
mod helmet_tests {
|
||||||
use rocket::http::{Status, uri::Uri};
|
use rocket::http::{Status, uri::Uri};
|
||||||
use rocket::local::asynchronous::{Client, LocalResponse};
|
use rocket::local::blocking::{Client, LocalResponse};
|
||||||
|
|
||||||
use rocket_contrib::helmet::*;
|
use rocket_contrib::helmet::*;
|
||||||
use time::Duration;
|
use time::Duration;
|
||||||
|
@ -34,15 +34,15 @@ mod helmet_tests {
|
||||||
macro_rules! dispatch {
|
macro_rules! dispatch {
|
||||||
($helmet:expr, $closure:expr) => {{
|
($helmet:expr, $closure:expr) => {{
|
||||||
let rocket = rocket::ignite().mount("/", routes![hello]).attach($helmet);
|
let rocket = rocket::ignite().mount("/", routes![hello]).attach($helmet);
|
||||||
let client = Client::new(rocket).await.unwrap();
|
let client = Client::new(rocket).unwrap();
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
$closure(response)
|
$closure(response)
|
||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn default_headers_test() {
|
fn default_headers_test() {
|
||||||
dispatch!(SpaceHelmet::default(), |response: LocalResponse<'_>| {
|
dispatch!(SpaceHelmet::default(), |response: LocalResponse<'_>| {
|
||||||
assert_header!(response, "X-XSS-Protection", "1");
|
assert_header!(response, "X-XSS-Protection", "1");
|
||||||
assert_header!(response, "X-Frame-Options", "SAMEORIGIN");
|
assert_header!(response, "X-Frame-Options", "SAMEORIGIN");
|
||||||
|
@ -50,8 +50,8 @@ mod helmet_tests {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn disable_headers_test() {
|
fn disable_headers_test() {
|
||||||
let helmet = SpaceHelmet::default().disable::<XssFilter>();
|
let helmet = SpaceHelmet::default().disable::<XssFilter>();
|
||||||
dispatch!(helmet, |response: LocalResponse<'_>| {
|
dispatch!(helmet, |response: LocalResponse<'_>| {
|
||||||
assert_header!(response, "X-Frame-Options", "SAMEORIGIN");
|
assert_header!(response, "X-Frame-Options", "SAMEORIGIN");
|
||||||
|
@ -84,8 +84,8 @@ mod helmet_tests {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn additional_headers_test() {
|
fn additional_headers_test() {
|
||||||
let helmet = SpaceHelmet::default()
|
let helmet = SpaceHelmet::default()
|
||||||
.enable(Hsts::default())
|
.enable(Hsts::default())
|
||||||
.enable(ExpectCt::default())
|
.enable(ExpectCt::default())
|
||||||
|
@ -108,8 +108,8 @@ mod helmet_tests {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn uri_test() {
|
fn uri_test() {
|
||||||
let allow_uri = Uri::parse("https://www.google.com").unwrap();
|
let allow_uri = Uri::parse("https://www.google.com").unwrap();
|
||||||
let report_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();
|
let enforce_uri = Uri::parse("https://www.google.com").unwrap();
|
||||||
|
|
|
@ -8,7 +8,7 @@ mod static_tests {
|
||||||
use rocket::{self, Rocket, Route};
|
use rocket::{self, Rocket, Route};
|
||||||
use rocket_contrib::serve::{StaticFiles, Options};
|
use rocket_contrib::serve::{StaticFiles, Options};
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
fn static_root() -> PathBuf {
|
fn static_root() -> PathBuf {
|
||||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
@ -45,9 +45,9 @@ mod static_tests {
|
||||||
"inner/",
|
"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 full_path = format!("/{}/{}", prefix, path);
|
||||||
let response = client.get(full_path).dispatch().await;
|
let response = client.get(full_path).dispatch();
|
||||||
if exists {
|
if exists {
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
|
|
||||||
|
@ -59,52 +59,52 @@ mod static_tests {
|
||||||
let mut file = File::open(path).expect("open file");
|
let mut file = File::open(path).expect("open file");
|
||||||
let mut expected_contents = String::new();
|
let mut expected_contents = String::new();
|
||||||
file.read_to_string(&mut expected_contents).expect("read file");
|
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 {
|
} else {
|
||||||
assert_eq!(response.status(), Status::NotFound);
|
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() {
|
for path in paths.iter() {
|
||||||
assert_file(client, prefix, path, exist).await;
|
assert_file(client, prefix, path, exist);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_static_no_index() {
|
fn test_static_no_index() {
|
||||||
let client = Client::new(rocket()).await.expect("valid rocket");
|
let client = Client::new(rocket()).expect("valid rocket");
|
||||||
assert_all(&client, "no_index", REGULAR_FILES, true).await;
|
assert_all(&client, "no_index", REGULAR_FILES, true);
|
||||||
assert_all(&client, "no_index", HIDDEN_FILES, false).await;
|
assert_all(&client, "no_index", HIDDEN_FILES, false);
|
||||||
assert_all(&client, "no_index", INDEXED_DIRECTORIES, false).await;
|
assert_all(&client, "no_index", INDEXED_DIRECTORIES, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_static_hidden() {
|
fn test_static_hidden() {
|
||||||
let client = Client::new(rocket()).await.expect("valid rocket");
|
let client = Client::new(rocket()).expect("valid rocket");
|
||||||
assert_all(&client, "dots", REGULAR_FILES, true).await;
|
assert_all(&client, "dots", REGULAR_FILES, true);
|
||||||
assert_all(&client, "dots", HIDDEN_FILES, true).await;
|
assert_all(&client, "dots", HIDDEN_FILES, true);
|
||||||
assert_all(&client, "dots", INDEXED_DIRECTORIES, false).await;
|
assert_all(&client, "dots", INDEXED_DIRECTORIES, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_static_index() {
|
fn test_static_index() {
|
||||||
let client = Client::new(rocket()).await.expect("valid rocket");
|
let client = Client::new(rocket()).expect("valid rocket");
|
||||||
assert_all(&client, "index", REGULAR_FILES, true).await;
|
assert_all(&client, "index", REGULAR_FILES, true);
|
||||||
assert_all(&client, "index", HIDDEN_FILES, false).await;
|
assert_all(&client, "index", HIDDEN_FILES, false);
|
||||||
assert_all(&client, "index", INDEXED_DIRECTORIES, true).await;
|
assert_all(&client, "index", INDEXED_DIRECTORIES, true);
|
||||||
|
|
||||||
assert_all(&client, "default", REGULAR_FILES, true).await;
|
assert_all(&client, "default", REGULAR_FILES, true);
|
||||||
assert_all(&client, "default", HIDDEN_FILES, false).await;
|
assert_all(&client, "default", HIDDEN_FILES, false);
|
||||||
assert_all(&client, "default", INDEXED_DIRECTORIES, true).await;
|
assert_all(&client, "default", INDEXED_DIRECTORIES, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_static_all() {
|
fn test_static_all() {
|
||||||
let client = Client::new(rocket()).await.expect("valid rocket");
|
let client = Client::new(rocket()).expect("valid rocket");
|
||||||
assert_all(&client, "both", REGULAR_FILES, true).await;
|
assert_all(&client, "both", REGULAR_FILES, true);
|
||||||
assert_all(&client, "both", HIDDEN_FILES, true).await;
|
assert_all(&client, "both", HIDDEN_FILES, true);
|
||||||
assert_all(&client, "both", INDEXED_DIRECTORIES, true).await;
|
assert_all(&client, "both", INDEXED_DIRECTORIES, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -121,8 +121,8 @@ mod static_tests {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_forwarding() {
|
fn test_forwarding() {
|
||||||
use rocket::http::RawStr;
|
use rocket::http::RawStr;
|
||||||
use rocket::{get, routes};
|
use rocket::{get, routes};
|
||||||
|
|
||||||
|
@ -133,19 +133,19 @@ mod static_tests {
|
||||||
fn catch_two(a: &RawStr, b: &RawStr) -> String { format!("{}/{}", a, b) }
|
fn catch_two(a: &RawStr, b: &RawStr) -> String { format!("{}/{}", a, b) }
|
||||||
|
|
||||||
let rocket = rocket().mount("/default", routes![catch_one, catch_two]);
|
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.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.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", REGULAR_FILES, true);
|
||||||
assert_all(&client, "both", HIDDEN_FILES, true).await;
|
assert_all(&client, "both", HIDDEN_FILES, true);
|
||||||
assert_all(&client, "both", INDEXED_DIRECTORIES, true).await;
|
assert_all(&client, "both", INDEXED_DIRECTORIES, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
@ -42,7 +42,7 @@ mod templates_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
const UNESCAPED_EXPECTED: &'static str
|
const UNESCAPED_EXPECTED: &'static str
|
||||||
= "\nh_start\ntitle: _test_\nh_end\n\n\n<script />\n\nfoot\n";
|
= "\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()));
|
assert_eq!(template, Some(ESCAPED_EXPECTED.into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_template_metadata_with_tera() {
|
fn test_template_metadata_with_tera() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
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);
|
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);
|
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);
|
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);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -89,7 +89,7 @@ mod templates_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
const EXPECTED: &'static str
|
const EXPECTED: &'static str
|
||||||
= "Hello _test_!\n\n<main> <script /> hi </main>\nDone.\n\n";
|
= "Hello _test_!\n\n<main> <script /> hi </main>\nDone.\n\n";
|
||||||
|
@ -107,28 +107,28 @@ mod templates_tests {
|
||||||
assert_eq!(template, Some(EXPECTED.into()));
|
assert_eq!(template, Some(EXPECTED.into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_template_metadata_with_handlebars() {
|
fn test_template_metadata_with_handlebars() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
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);
|
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);
|
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);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
async fn test_template_reload() {
|
fn test_template_reload() {
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
const RELOAD_TEMPLATE: &str = "hbs/reload";
|
const RELOAD_TEMPLATE: &str = "hbs/reload";
|
||||||
const INITIAL_TEXT: &str = "initial";
|
const INITIAL_TEXT: &str = "initial";
|
||||||
|
@ -146,8 +146,8 @@ mod templates_tests {
|
||||||
write_file(&reload_path, INITIAL_TEXT);
|
write_file(&reload_path, INITIAL_TEXT);
|
||||||
|
|
||||||
// set up the client. if we can't reload templates, then just quit
|
// set up the client. if we can't reload templates, then just quit
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let res = client.get("/is_reloading").dispatch().await;
|
let res = client.get("/is_reloading").dispatch();
|
||||||
if res.status() != Status::Ok {
|
if res.status() != Status::Ok {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -161,7 +161,7 @@ mod templates_tests {
|
||||||
|
|
||||||
for _ in 0..6 {
|
for _ in 0..6 {
|
||||||
// dispatch any request to trigger a template reload
|
// dispatch any request to trigger a template reload
|
||||||
client.get("/").dispatch().await;
|
client.get("/").dispatch();
|
||||||
|
|
||||||
// if the new content is correct, we are done
|
// if the new content is correct, we are done
|
||||||
let new_rendered = Template::show(client.cargo(), RELOAD_TEMPLATE, ());
|
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
|
// 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");
|
panic!("failed to reload modified template in 1.5s");
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
#[macro_use] extern crate rocket;
|
#[macro_use] extern crate rocket;
|
||||||
|
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
#[get("/easy/<id>")]
|
#[get("/easy/<id>")]
|
||||||
fn easy(id: i32) -> String {
|
fn easy(id: i32) -> String {
|
||||||
|
@ -33,19 +33,19 @@ macro_rules! foo {
|
||||||
// regression test for `#[get] panicking if used inside a macro
|
// regression test for `#[get] panicking if used inside a macro
|
||||||
foo!("/hello/<name>", name);
|
foo!("/hello/<name>", name);
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_reexpansion() {
|
fn test_reexpansion() {
|
||||||
let rocket = rocket::ignite().mount("/", routes![easy, hard, hi]);
|
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;
|
let response = client.get("/easy/327").dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "easy id: 327");
|
assert_eq!(response.into_string().unwrap(), "easy id: 327");
|
||||||
|
|
||||||
let response = client.get("/hard/72").dispatch().await;
|
let response = client.get("/hard/72").dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "hard id: 72");
|
assert_eq!(response.into_string().unwrap(), "hard id: 72");
|
||||||
|
|
||||||
let response = client.get("/hello/fish").dispatch().await;
|
let response = client.get("/hello/fish").dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "fish");
|
assert_eq!(response.into_string().unwrap(), "fish");
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! index {
|
macro_rules! index {
|
||||||
|
@ -59,11 +59,11 @@ macro_rules! index {
|
||||||
|
|
||||||
index!(i32);
|
index!(i32);
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_index() {
|
fn test_index() {
|
||||||
let rocket = rocket::ignite().mount("/", routes![index]).manage(100i32);
|
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;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "Thing: 100");
|
assert_eq!(response.into_string().unwrap(), "Thing: 100");
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,7 +3,7 @@
|
||||||
#[macro_use] extern crate rocket;
|
#[macro_use] extern crate rocket;
|
||||||
|
|
||||||
use rocket::{Request, Data, Outcome::*};
|
use rocket::{Request, Data, Outcome::*};
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::request::Form;
|
use rocket::request::Form;
|
||||||
use rocket::data::{self, FromDataSimple};
|
use rocket::data::{self, FromDataSimple};
|
||||||
use rocket::http::{RawStr, ContentType, Status};
|
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>")]
|
#[post("/s", data = "<simple>")]
|
||||||
fn simple(simple: Simple) -> String { simple.0 }
|
fn simple(simple: Simple) -> String { simple.0 }
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_data() {
|
fn test_data() {
|
||||||
let rocket = rocket::ignite().mount("/", routes![form, simple]);
|
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")
|
let response = client.post("/f")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body("field=this%20is%20here")
|
.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;
|
let response = client.post("/s").body("this is here").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%20is%20here").dispatch().await;
|
let response = client.post("/s").body("this%20is%20here").dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "this%20is%20here");
|
assert_eq!(response.into_string().unwrap(), "this%20is%20here");
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
#[macro_use] extern crate rocket;
|
#[macro_use] extern crate rocket;
|
||||||
|
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{ContentType, MediaType, Accept, Status};
|
use rocket::http::{ContentType, MediaType, Accept, Status};
|
||||||
|
|
||||||
// Test that known formats work as expected, including not colliding.
|
// Test that known formats work as expected, including not colliding.
|
||||||
|
@ -33,36 +33,36 @@ fn binary() -> &'static str { "binary" }
|
||||||
#[get("/", rank = 3)]
|
#[get("/", rank = 3)]
|
||||||
fn other() -> &'static str { "other" }
|
fn other() -> &'static str { "other" }
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_formats() {
|
fn test_formats() {
|
||||||
let rocket = rocket::ignite()
|
let rocket = rocket::ignite()
|
||||||
.mount("/", routes![json, xml, json_long, msgpack_long, msgpack,
|
.mount("/", routes![json, xml, json_long, msgpack_long, msgpack,
|
||||||
plain, binary, other]);
|
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;
|
let response = client.post("/").header(ContentType::JSON).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "json");
|
assert_eq!(response.into_string().unwrap(), "json");
|
||||||
|
|
||||||
let response = client.post("/").header(ContentType::MsgPack).dispatch().await;
|
let response = client.post("/").header(ContentType::MsgPack).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "msgpack_long");
|
assert_eq!(response.into_string().unwrap(), "msgpack_long");
|
||||||
|
|
||||||
let response = client.post("/").header(ContentType::XML).dispatch().await;
|
let response = client.post("/").header(ContentType::XML).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "xml");
|
assert_eq!(response.into_string().unwrap(), "xml");
|
||||||
|
|
||||||
let response = client.get("/").header(Accept::Plain).dispatch().await;
|
let response = client.get("/").header(Accept::Plain).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "plain");
|
assert_eq!(response.into_string().unwrap(), "plain");
|
||||||
|
|
||||||
let response = client.get("/").header(Accept::Binary).dispatch().await;
|
let response = client.get("/").header(Accept::Binary).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "binary");
|
assert_eq!(response.into_string().unwrap(), "binary");
|
||||||
|
|
||||||
let response = client.get("/").header(ContentType::JSON).dispatch().await;
|
let response = client.get("/").header(ContentType::JSON).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "plain");
|
assert_eq!(response.into_string().unwrap(), "plain");
|
||||||
|
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "plain");
|
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);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -80,36 +80,36 @@ fn get_bar_baz() -> &'static str { "get_bar_baz" }
|
||||||
#[put("/", format = "bar/baz")]
|
#[put("/", format = "bar/baz")]
|
||||||
fn put_bar_baz() -> &'static str { "put_bar_baz" }
|
fn put_bar_baz() -> &'static str { "put_bar_baz" }
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_custom_formats() {
|
fn test_custom_formats() {
|
||||||
let rocket = rocket::ignite()
|
let rocket = rocket::ignite()
|
||||||
.mount("/", routes![get_foo, post_foo, get_bar_baz, put_bar_baz]);
|
.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_a = Accept::new(&[MediaType::new("application", "foo").into()]);
|
||||||
let foo_ct = ContentType::new("application", "foo");
|
let foo_ct = ContentType::new("application", "foo");
|
||||||
let bar_baz_ct = ContentType::new("bar", "baz");
|
let bar_baz_ct = ContentType::new("bar", "baz");
|
||||||
let bar_baz_a = Accept::new(&[MediaType::new("bar", "baz").into()]);
|
let bar_baz_a = Accept::new(&[MediaType::new("bar", "baz").into()]);
|
||||||
|
|
||||||
let response = client.get("/").header(foo_a).dispatch().await;
|
let response = client.get("/").header(foo_a).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "get_foo");
|
assert_eq!(response.into_string().unwrap(), "get_foo");
|
||||||
|
|
||||||
let response = client.post("/").header(foo_ct).dispatch().await;
|
let response = client.post("/").header(foo_ct).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "post_foo");
|
assert_eq!(response.into_string().unwrap(), "post_foo");
|
||||||
|
|
||||||
let response = client.get("/").header(bar_baz_a).dispatch().await;
|
let response = client.get("/").header(bar_baz_a).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "get_bar_baz");
|
assert_eq!(response.into_string().unwrap(), "get_bar_baz");
|
||||||
|
|
||||||
let response = client.put("/").header(bar_baz_ct).dispatch().await;
|
let response = client.put("/").header(bar_baz_ct).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "put_bar_baz");
|
assert_eq!(response.into_string().unwrap(), "put_bar_baz");
|
||||||
|
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "get_foo");
|
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);
|
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);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
#[macro_use] extern crate rocket;
|
#[macro_use] extern crate rocket;
|
||||||
|
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
// Test that manual/auto ranking works as expected.
|
// Test that manual/auto ranking works as expected.
|
||||||
|
|
||||||
|
@ -18,22 +18,22 @@ fn get2(_number: u32) -> &'static str { "2" }
|
||||||
#[get("/<_number>", rank = 3)]
|
#[get("/<_number>", rank = 3)]
|
||||||
fn get3(_number: u64) -> &'static str { "3" }
|
fn get3(_number: u64) -> &'static str { "3" }
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_ranking() {
|
fn test_ranking() {
|
||||||
let rocket = rocket::ignite().mount("/", routes![get0, get1, get2, get3]);
|
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;
|
let response = client.get("/0").dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "0");
|
assert_eq!(response.into_string().unwrap(), "0");
|
||||||
|
|
||||||
let response = client.get(format!("/{}", 1 << 8)).dispatch().await;
|
let response = client.get(format!("/{}", 1 << 8)).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "1");
|
assert_eq!(response.into_string().unwrap(), "1");
|
||||||
|
|
||||||
let response = client.get(format!("/{}", 1 << 16)).dispatch().await;
|
let response = client.get(format!("/{}", 1 << 16)).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "2");
|
assert_eq!(response.into_string().unwrap(), "2");
|
||||||
|
|
||||||
let response = client.get(format!("/{}", 1u64 << 32)).dispatch().await;
|
let response = client.get(format!("/{}", 1u64 << 32)).dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "3");
|
assert_eq!(response.into_string().unwrap(), "3");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test a collision due to same auto rank.
|
// Test a collision due to same auto rank.
|
||||||
|
@ -41,12 +41,12 @@ async fn test_ranking() {
|
||||||
#[get("/<_n>")]
|
#[get("/<_n>")]
|
||||||
fn get0b(_n: u8) { }
|
fn get0b(_n: u8) { }
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_rank_collision() {
|
fn test_rank_collision() {
|
||||||
use rocket::error::LaunchErrorKind;
|
use rocket::error::LaunchErrorKind;
|
||||||
|
|
||||||
let rocket = rocket::ignite().mount("/", routes![get0, get0b]);
|
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()) {
|
match client_result.as_ref().map_err(|e| e.kind()) {
|
||||||
Err(LaunchErrorKind::Collision(..)) => { /* o.k. */ },
|
Err(LaunchErrorKind::Collision(..)) => { /* o.k. */ },
|
||||||
Ok(_) => panic!("client succeeded unexpectedly"),
|
Ok(_) => panic!("client succeeded unexpectedly"),
|
||||||
|
|
|
@ -11,7 +11,7 @@ use std::path::PathBuf;
|
||||||
|
|
||||||
use rocket::{Request, Outcome::*};
|
use rocket::{Request, Outcome::*};
|
||||||
use rocket::http::ext::Normalize;
|
use rocket::http::ext::Normalize;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::data::{self, Data, FromDataSimple};
|
use rocket::data::{self, Data, FromDataSimple};
|
||||||
use rocket::request::Form;
|
use rocket::request::Form;
|
||||||
use rocket::http::{Status, RawStr, ContentType};
|
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) {
|
fn test_unused_params(_unused_param: String, _unused_query: String, _unused_data: Data) {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_full_route() {
|
fn test_full_route() {
|
||||||
let rocket = rocket::ignite()
|
let rocket = rocket::ignite()
|
||||||
.mount("/1", routes![post1])
|
.mount("/1", routes![post1])
|
||||||
.mount("/2", routes![post2]);
|
.mount("/2", routes![post2]);
|
||||||
|
|
||||||
let client = Client::new(rocket).await.unwrap();
|
let client = Client::new(rocket).unwrap();
|
||||||
|
|
||||||
let a = "A%20A";
|
let a = "A%20A";
|
||||||
let name = "Bob%20McDonald";
|
let name = "Bob%20McDonald";
|
||||||
|
@ -99,30 +99,30 @@ async fn test_full_route() {
|
||||||
let uri = format!("{}{}", path_part, query_part);
|
let uri = format!("{}{}", path_part, query_part);
|
||||||
let expected_uri = format!("{}?sky=blue&sky={}&{}", path_part, sky, query);
|
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);
|
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);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
|
|
||||||
let response = client
|
let response = client
|
||||||
.post(format!("/1{}", uri))
|
.post(format!("/1{}", uri))
|
||||||
.header(ContentType::JSON)
|
.header(ContentType::JSON)
|
||||||
.body(simple)
|
.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));
|
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);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
|
|
||||||
let response = client
|
let response = client
|
||||||
.post(format!("/2{}", uri))
|
.post(format!("/2{}", uri))
|
||||||
.header(ContentType::JSON)
|
.header(ContentType::JSON)
|
||||||
.body(simple)
|
.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));
|
sky, name, "A A", "inside", path, simple, expected_uri));
|
||||||
}
|
}
|
||||||
|
|
|
@ -42,7 +42,7 @@ impl<'r, R> Created<R> {
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// # #![feature(proc_macro_hygiene)]
|
/// # #![feature(proc_macro_hygiene)]
|
||||||
/// # use rocket::{get, routes, local::asynchronous::Client};
|
/// # use rocket::{get, routes, local::blocking::Client};
|
||||||
/// use rocket::response::status;
|
/// use rocket::response::status;
|
||||||
///
|
///
|
||||||
/// #[get("/")]
|
/// #[get("/")]
|
||||||
|
@ -50,15 +50,13 @@ impl<'r, R> Created<R> {
|
||||||
/// status::Created::new("http://myservice.com/resource.json")
|
/// status::Created::new("http://myservice.com/resource.json")
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// # rocket::async_test(async move {
|
|
||||||
/// # let rocket = rocket::ignite().mount("/", routes![create]);
|
/// # let rocket = rocket::ignite().mount("/", routes![create]);
|
||||||
/// # let client = Client::new(rocket).await.unwrap();
|
/// # let client = Client::new(rocket).unwrap();
|
||||||
/// let response = client.get("/").dispatch().await;
|
/// let response = client.get("/").dispatch();
|
||||||
///
|
///
|
||||||
/// let loc = response.headers().get_one("Location");
|
/// let loc = response.headers().get_one("Location");
|
||||||
/// assert_eq!(loc, Some("http://myservice.com/resource.json"));
|
/// assert_eq!(loc, Some("http://myservice.com/resource.json"));
|
||||||
/// assert!(response.body().is_none());
|
/// assert!(response.body().is_none());
|
||||||
/// });
|
|
||||||
/// ```
|
/// ```
|
||||||
pub fn new<L: Into<Cow<'static, str>>>(location: L) -> Self {
|
pub fn new<L: Into<Cow<'static, str>>>(location: L) -> Self {
|
||||||
Created(location.into(), None, None)
|
Created(location.into(), None, None)
|
||||||
|
@ -73,7 +71,7 @@ impl<'r, R> Created<R> {
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// # #![feature(proc_macro_hygiene)]
|
/// # #![feature(proc_macro_hygiene)]
|
||||||
/// # use rocket::{get, routes, local::asynchronous::Client};
|
/// # use rocket::{get, routes, local::blocking::Client};
|
||||||
/// use rocket::response::status;
|
/// use rocket::response::status;
|
||||||
///
|
///
|
||||||
/// #[get("/")]
|
/// #[get("/")]
|
||||||
|
@ -82,10 +80,9 @@ impl<'r, R> Created<R> {
|
||||||
/// .body("{ 'resource': 'Hello, world!' }")
|
/// .body("{ 'resource': 'Hello, world!' }")
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// # rocket::async_test(async move {
|
|
||||||
/// # let rocket = rocket::ignite().mount("/", routes![create]);
|
/// # let rocket = rocket::ignite().mount("/", routes![create]);
|
||||||
/// # let client = Client::new(rocket).await.unwrap();
|
/// # let client = Client::new(rocket).unwrap();
|
||||||
/// let response = client.get("/").dispatch().await;
|
/// let response = client.get("/").dispatch();
|
||||||
///
|
///
|
||||||
/// let loc = response.headers().get_one("Location");
|
/// let loc = response.headers().get_one("Location");
|
||||||
/// assert_eq!(loc, Some("http://myservice.com/resource.json"));
|
/// 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");
|
/// let etag = response.headers().get_one("ETag");
|
||||||
/// assert_eq!(etag, None);
|
/// assert_eq!(etag, None);
|
||||||
///
|
///
|
||||||
/// let body = response.into_string().await;
|
/// let body = response.into_string();
|
||||||
/// assert_eq!(body.unwrap(), "{ 'resource': 'Hello, world!' }");
|
/// assert_eq!(body.unwrap(), "{ 'resource': 'Hello, world!' }");
|
||||||
/// # });
|
|
||||||
/// ```
|
/// ```
|
||||||
pub fn body(mut self, responder: R) -> Self {
|
pub fn body(mut self, responder: R) -> Self {
|
||||||
self.1 = Some(responder);
|
self.1 = Some(responder);
|
||||||
|
@ -109,7 +105,7 @@ impl<'r, R> Created<R> {
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// # #![feature(proc_macro_hygiene)]
|
/// # #![feature(proc_macro_hygiene)]
|
||||||
/// # use rocket::{get, routes, local::asynchronous::Client};
|
/// # use rocket::{get, routes, local::blocking::Client};
|
||||||
/// use rocket::response::status;
|
/// use rocket::response::status;
|
||||||
///
|
///
|
||||||
/// #[get("/")]
|
/// #[get("/")]
|
||||||
|
@ -118,10 +114,9 @@ impl<'r, R> Created<R> {
|
||||||
/// .tagged_body("{ 'resource': 'Hello, world!' }")
|
/// .tagged_body("{ 'resource': 'Hello, world!' }")
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// # rocket::async_test(async move {
|
|
||||||
/// # let rocket = rocket::ignite().mount("/", routes![create]);
|
/// # let rocket = rocket::ignite().mount("/", routes![create]);
|
||||||
/// # let client = Client::new(rocket).await.unwrap();
|
/// # let client = Client::new(rocket).unwrap();
|
||||||
/// let response = client.get("/").dispatch().await;
|
/// let response = client.get("/").dispatch();
|
||||||
///
|
///
|
||||||
/// let loc = response.headers().get_one("Location");
|
/// let loc = response.headers().get_one("Location");
|
||||||
/// assert_eq!(loc, Some("http://myservice.com/resource.json"));
|
/// 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");
|
/// let etag = response.headers().get_one("ETag");
|
||||||
/// assert_eq!(etag, Some(r#""13046220615156895040""#));
|
/// assert_eq!(etag, Some(r#""13046220615156895040""#));
|
||||||
///
|
///
|
||||||
/// let body = response.into_string().await;
|
/// let body = response.into_string();
|
||||||
/// assert_eq!(body.unwrap(), "{ 'resource': 'Hello, world!' }");
|
/// assert_eq!(body.unwrap(), "{ 'resource': 'Hello, world!' }");
|
||||||
/// # });
|
|
||||||
/// ```
|
/// ```
|
||||||
pub fn tagged_body(mut self, responder: R) -> Self where R: Hash {
|
pub fn tagged_body(mut self, responder: R) -> Self where R: Hash {
|
||||||
let mut hasher = &mut DefaultHasher::default();
|
let mut hasher = &mut DefaultHasher::default();
|
||||||
|
|
|
@ -16,18 +16,18 @@ fn rocket() -> Redirect {
|
||||||
|
|
||||||
mod test_absolute_uris_okay {
|
mod test_absolute_uris_okay {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn redirect_works() {
|
fn redirect_works() {
|
||||||
let rocket = rocket::ignite().mount("/", routes![google, rocket]);
|
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");
|
let location = response.headers().get_one("Location");
|
||||||
assert_eq!(location, Some("https://www.google.com"));
|
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");
|
let location = response.headers().get_one("Location");
|
||||||
assert_eq!(location, Some("https://rocket.rs:80"));
|
assert_eq!(location, Some("https://rocket.rs:80"));
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,7 +6,7 @@ use rocket::Response;
|
||||||
use rocket::http::Header;
|
use rocket::http::Header;
|
||||||
|
|
||||||
#[get("/do_not_overwrite")]
|
#[get("/do_not_overwrite")]
|
||||||
async fn do_not_overwrite() -> Response<'static> {
|
fn do_not_overwrite() -> Response<'static> {
|
||||||
Response::build()
|
Response::build()
|
||||||
.header(Header::new("Server", "Test"))
|
.header(Header::new("Server", "Test"))
|
||||||
.finalize()
|
.finalize()
|
||||||
|
@ -17,18 +17,18 @@ fn use_default() { }
|
||||||
|
|
||||||
mod conditionally_set_server_header {
|
mod conditionally_set_server_header {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn do_not_overwrite_server_header() {
|
fn do_not_overwrite_server_header() {
|
||||||
let rocket = rocket::ignite().mount("/", routes![do_not_overwrite, use_default]);
|
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");
|
let server = response.headers().get_one("Server");
|
||||||
assert_eq!(server, Some("Test"));
|
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");
|
let server = response.headers().get_one("Server");
|
||||||
assert_eq!(server, Some("Rocket"));
|
assert_eq!(server, Some("Rocket"));
|
||||||
}
|
}
|
||||||
|
|
|
@ -43,16 +43,16 @@ fn number(params: Form<ThingForm>) -> DerivedResponder {
|
||||||
DerivedResponder { data: params.thing.to_string() }
|
DerivedResponder { data: params.thing.to_string() }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_derive_reexports() {
|
fn test_derive_reexports() {
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
let rocket = rocket::ignite().mount("/", routes![index, number]);
|
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;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "hello");
|
assert_eq!(response.into_string().unwrap(), "hello");
|
||||||
|
|
||||||
let response = client.get("/?thing=b").dispatch().await;
|
let response = client.get("/?thing=b").dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "b");
|
assert_eq!(response.into_string().unwrap(), "b");
|
||||||
}
|
}
|
||||||
|
|
|
@ -22,12 +22,12 @@ mod fairing_before_head_strip {
|
||||||
|
|
||||||
use rocket::fairing::AdHoc;
|
use rocket::fairing::AdHoc;
|
||||||
use rocket::http::Method;
|
use rocket::http::Method;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
use rocket::State;
|
use rocket::State;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn not_auto_handled() {
|
fn not_auto_handled() {
|
||||||
let rocket = rocket::ignite()
|
let rocket = rocket::ignite()
|
||||||
.mount("/", routes![head])
|
.mount("/", routes![head])
|
||||||
.attach(AdHoc::on_request("Check HEAD", |req, _| {
|
.attach(AdHoc::on_request("Check HEAD", |req, _| {
|
||||||
|
@ -42,14 +42,14 @@ mod fairing_before_head_strip {
|
||||||
})
|
})
|
||||||
}));
|
}));
|
||||||
|
|
||||||
let client = Client::new(rocket).await.unwrap();
|
let client = Client::new(rocket).unwrap();
|
||||||
let response = client.head("/").dispatch().await;
|
let response = client.head("/").dispatch();
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
assert!(response.body().is_none());
|
assert!(response.body().is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn auto_handled() {
|
fn auto_handled() {
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct Counter(AtomicUsize);
|
struct Counter(AtomicUsize);
|
||||||
|
|
||||||
|
@ -73,8 +73,8 @@ mod fairing_before_head_strip {
|
||||||
})
|
})
|
||||||
}));
|
}));
|
||||||
|
|
||||||
let client = Client::new(rocket).await.unwrap();
|
let client = Client::new(rocket).unwrap();
|
||||||
let response = client.head("/").dispatch().await;
|
let response = client.head("/").dispatch();
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
assert!(response.body().is_none());
|
assert!(response.body().is_none());
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,40 +23,40 @@ fn used(flash: Option<FlashMessage<'_, '_>>) -> Option<String> {
|
||||||
}
|
}
|
||||||
|
|
||||||
mod flash_lazy_remove_tests {
|
mod flash_lazy_remove_tests {
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test() {
|
fn test() {
|
||||||
use super::*;
|
use super::*;
|
||||||
let r = rocket::ignite().mount("/", routes![set, unused, used]);
|
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.
|
// 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);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
|
|
||||||
// Set the flash cookie.
|
// Set the flash cookie.
|
||||||
client.post("/").dispatch().await;
|
client.post("/").dispatch();
|
||||||
|
|
||||||
// Try once.
|
// Try once.
|
||||||
let response = client.get("/unused").dispatch().await;
|
let response = client.get("/unused").dispatch();
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
|
|
||||||
// Try again; should still be there.
|
// 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);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
|
|
||||||
// Now use it.
|
// Now use it.
|
||||||
let response = client.get("/use").dispatch().await;
|
let response = client.get("/use").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some(FLASH_MESSAGE.into()));
|
assert_eq!(response.into_string(), Some(FLASH_MESSAGE.into()));
|
||||||
|
|
||||||
// Now it should be gone.
|
// Now it should be gone.
|
||||||
let response = client.get("/unused").dispatch().await;
|
let response = client.get("/unused").dispatch();
|
||||||
assert_eq!(response.status(), Status::NotFound);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
|
|
||||||
// Still gone.
|
// Still gone.
|
||||||
let response = client.get("/use").dispatch().await;
|
let response = client.get("/use").dispatch();
|
||||||
assert_eq!(response.status(), Status::NotFound);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,27 +17,27 @@ fn bug(form_data: Form<FormData>) -> &'static str {
|
||||||
|
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{Status, ContentType};
|
use rocket::http::{Status, ContentType};
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn method_eval() {
|
fn method_eval() {
|
||||||
let client = Client::new(rocket::ignite().mount("/", routes![bug])).await.unwrap();
|
let client = Client::new(rocket::ignite().mount("/", routes![bug])).unwrap();
|
||||||
let response = client.post("/")
|
let response = client.post("/")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body("_method=patch&form_data=Form+data")
|
.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]
|
#[test]
|
||||||
async fn get_passes_through() {
|
fn get_passes_through() {
|
||||||
let client = Client::new(rocket::ignite().mount("/", routes![bug])).await.unwrap();
|
let client = Client::new(rocket::ignite().mount("/", routes![bug])).unwrap();
|
||||||
let response = client.get("/")
|
let response = client.get("/")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body("_method=patch&form_data=Form+data")
|
.body("_method=patch&form_data=Form+data")
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(response.status(), Status::NotFound);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,29 +16,29 @@ fn bug(form_data: Form<FormData>) -> String {
|
||||||
|
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::ContentType;
|
use rocket::http::ContentType;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
async fn check_decoding(raw: &str, decoded: &str) {
|
fn check_decoding(raw: &str, decoded: &str) {
|
||||||
let client = Client::new(rocket::ignite().mount("/", routes![bug])).await.unwrap();
|
let client = Client::new(rocket::ignite().mount("/", routes![bug])).unwrap();
|
||||||
let response = client.post("/")
|
let response = client.post("/")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body(format!("form_data={}", raw))
|
.body(format!("form_data={}", raw))
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(response.status(), Status::Ok);
|
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]
|
#[test]
|
||||||
async fn test_proper_decoding() {
|
fn test_proper_decoding() {
|
||||||
check_decoding("password", "password").await;
|
check_decoding("password", "password");
|
||||||
check_decoding("", "").await;
|
check_decoding("", "");
|
||||||
check_decoding("+", " ").await;
|
check_decoding("+", " ");
|
||||||
check_decoding("%2B", "+").await;
|
check_decoding("%2B", "+");
|
||||||
check_decoding("1+1", "1 1").await;
|
check_decoding("1+1", "1 1");
|
||||||
check_decoding("1%2B1", "1+1").await;
|
check_decoding("1%2B1", "1+1");
|
||||||
check_decoding("%3Fa%3D1%26b%3D2", "?a=1&b=2").await;
|
check_decoding("%3Fa%3D1%26b%3D2", "?a=1&b=2");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,38 +23,38 @@ mod head_handling_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
use rocket::Route;
|
use rocket::Route;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{Status, ContentType};
|
use rocket::http::{Status, ContentType};
|
||||||
|
|
||||||
fn routes() -> Vec<Route> {
|
fn routes() -> Vec<Route> {
|
||||||
routes![index, empty, other]
|
routes![index, empty, other]
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn auto_head() {
|
fn auto_head() {
|
||||||
let client = Client::new(rocket::ignite().mount("/", routes())).await.unwrap();
|
let client = Client::new(rocket::ignite().mount("/", routes())).unwrap();
|
||||||
let response = client.head("/").dispatch().await;
|
let response = client.head("/").dispatch();
|
||||||
|
|
||||||
let content_type: Vec<_> = response.headers().get("Content-Type").collect();
|
let content_type: Vec<_> = response.headers().get("Content-Type").collect();
|
||||||
assert_eq!(content_type, vec![ContentType::Plain.to_string()]);
|
assert_eq!(content_type, vec![ContentType::Plain.to_string()]);
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
assert_eq!(response.body().unwrap().known_size(), Some(13));
|
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_eq!(response.status(), Status::NoContent);
|
||||||
assert!(response.into_bytes().await.is_none());
|
assert!(response.into_bytes().is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn user_head() {
|
fn user_head() {
|
||||||
let client = Client::new(rocket::ignite().mount("/", routes())).await.unwrap();
|
let client = Client::new(rocket::ignite().mount("/", routes())).unwrap();
|
||||||
let response = client.head("/other").dispatch().await;
|
let response = client.head("/other").dispatch();
|
||||||
|
|
||||||
let content_type: Vec<_> = response.headers().get("Content-Type").collect();
|
let content_type: Vec<_> = response.headers().get("Content-Type").collect();
|
||||||
assert_eq!(content_type, vec![ContentType::JSON.to_string()]);
|
assert_eq!(content_type, vec![ContentType::JSON.to_string()]);
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
assert_eq!(response.body().unwrap().known_size(), Some(17));
|
assert_eq!(response.body().unwrap().known_size(), Some(17));
|
||||||
assert!(response.into_bytes().await.unwrap().is_empty());
|
assert!(response.into_bytes().unwrap().is_empty());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,7 +17,7 @@ fn index(form: Form<Simple>) -> String {
|
||||||
mod limits_tests {
|
mod limits_tests {
|
||||||
use rocket;
|
use rocket;
|
||||||
use rocket::config::{Environment, Config, Limits};
|
use rocket::config::{Environment, Config, Limits};
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{Status, ContentType};
|
use rocket::http::{Status, ContentType};
|
||||||
|
|
||||||
fn rocket_with_forms_limit(limit: u64) -> rocket::Rocket {
|
fn rocket_with_forms_limit(limit: u64) -> rocket::Rocket {
|
||||||
|
@ -28,47 +28,47 @@ mod limits_tests {
|
||||||
rocket::custom(config).mount("/", routes![super::index])
|
rocket::custom(config).mount("/", routes![super::index])
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn large_enough() {
|
fn large_enough() {
|
||||||
let client = Client::new(rocket_with_forms_limit(128)).await.unwrap();
|
let client = Client::new(rocket_with_forms_limit(128)).unwrap();
|
||||||
let response = client.post("/")
|
let response = client.post("/")
|
||||||
.body("value=Hello+world")
|
.body("value=Hello+world")
|
||||||
.header(ContentType::Form)
|
.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]
|
#[test]
|
||||||
async fn just_large_enough() {
|
fn just_large_enough() {
|
||||||
let client = Client::new(rocket_with_forms_limit(17)).await.unwrap();
|
let client = Client::new(rocket_with_forms_limit(17)).unwrap();
|
||||||
let response = client.post("/")
|
let response = client.post("/")
|
||||||
.body("value=Hello+world")
|
.body("value=Hello+world")
|
||||||
.header(ContentType::Form)
|
.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]
|
#[test]
|
||||||
async fn much_too_small() {
|
fn much_too_small() {
|
||||||
let client = Client::new(rocket_with_forms_limit(4)).await.unwrap();
|
let client = Client::new(rocket_with_forms_limit(4)).unwrap();
|
||||||
let response = client.post("/")
|
let response = client.post("/")
|
||||||
.body("value=Hello+world")
|
.body("value=Hello+world")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(response.status(), Status::UnprocessableEntity);
|
assert_eq!(response.status(), Status::UnprocessableEntity);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn contracted() {
|
fn contracted() {
|
||||||
let client = Client::new(rocket_with_forms_limit(10)).await.unwrap();
|
let client = Client::new(rocket_with_forms_limit(10)).unwrap();
|
||||||
let response = client.post("/")
|
let response = client.post("/")
|
||||||
.body("value=Hello+world")
|
.body("value=Hello+world")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(response.into_string().await, Some("Hell".into()));
|
assert_eq!(response.into_string(), Some("Hell".into()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -54,40 +54,40 @@ mod local_request_content_type_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
use rocket::Rocket;
|
use rocket::Rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::ContentType;
|
use rocket::http::ContentType;
|
||||||
|
|
||||||
fn rocket() -> Rocket {
|
fn rocket() -> Rocket {
|
||||||
rocket::ignite().mount("/", routes![rg_ct, data_has_ct, data_no_ct])
|
rocket::ignite().mount("/", routes![rg_ct, data_has_ct, data_no_ct])
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn has_no_ct() {
|
fn has_no_ct() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
|
|
||||||
let req = client.post("/");
|
let req = client.post("/");
|
||||||
assert_eq!(req.clone().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().await.into_string().await, Some("Absent".to_string()));
|
assert_eq!(req.clone().dispatch().into_string(), Some("Absent".to_string()));
|
||||||
assert_eq!(req.dispatch().await.into_string().await, Some("Absent".to_string()));
|
assert_eq!(req.dispatch().into_string(), Some("Absent".to_string()));
|
||||||
|
|
||||||
let req = client.post("/data");
|
let req = client.post("/data");
|
||||||
assert_eq!(req.clone().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().await.into_string().await, Some("Data Absent".to_string()));
|
assert_eq!(req.clone().dispatch().into_string(), Some("Data Absent".to_string()));
|
||||||
assert_eq!(req.dispatch().await.into_string().await, Some("Data Absent".to_string()));
|
assert_eq!(req.dispatch().into_string(), Some("Data Absent".to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn has_ct() {
|
fn has_ct() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
|
|
||||||
let req = client.post("/").header(ContentType::JSON);
|
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().into_string(), Some("Present".to_string()));
|
||||||
assert_eq!(req.clone().dispatch().await.into_string().await, Some("Present".to_string()));
|
assert_eq!(req.clone().dispatch().into_string(), Some("Present".to_string()));
|
||||||
assert_eq!(req.dispatch().await.into_string().await, Some("Present".to_string()));
|
assert_eq!(req.dispatch().into_string(), Some("Present".to_string()));
|
||||||
|
|
||||||
let req = client.post("/data").header(ContentType::JSON);
|
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().into_string(), Some("Data Present".to_string()));
|
||||||
assert_eq!(req.clone().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.dispatch().await.into_string().await, Some("Data Present".to_string()));
|
assert_eq!(req.dispatch().into_string(), Some("Data Present".to_string()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,29 +18,29 @@ mod private_cookie_test {
|
||||||
|
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Cookie;
|
use rocket::http::Cookie;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn private_cookie_is_returned() {
|
fn private_cookie_is_returned() {
|
||||||
let rocket = rocket::ignite().mount("/", routes![return_private_cookie]);
|
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 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.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]
|
#[test]
|
||||||
async fn regular_cookie_is_not_returned() {
|
fn regular_cookie_is_not_returned() {
|
||||||
let rocket = rocket::ignite().mount("/", routes![return_private_cookie]);
|
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 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);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
}
|
}
|
||||||
|
|
|
@ -44,20 +44,20 @@ fn rocket() -> rocket::Rocket {
|
||||||
|
|
||||||
mod nested_fairing_attaches_tests {
|
mod nested_fairing_attaches_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_counts() {
|
fn test_counts() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some("1, 1".into()));
|
assert_eq!(response.into_string(), Some("1, 1".into()));
|
||||||
|
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some("1, 2".into()));
|
assert_eq!(response.into_string(), Some("1, 2".into()));
|
||||||
|
|
||||||
client.get("/").dispatch().await;
|
client.get("/").dispatch();
|
||||||
client.get("/").dispatch().await;
|
client.get("/").dispatch();
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some("1, 5".into()));
|
assert_eq!(response.into_string(), Some("1, 5".into()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,7 +26,7 @@ mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
use rocket::Rocket;
|
use rocket::Rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{Status, ContentType};
|
use rocket::http::{Status, ContentType};
|
||||||
|
|
||||||
fn rocket() -> Rocket {
|
fn rocket() -> Rocket {
|
||||||
|
@ -37,16 +37,16 @@ mod tests {
|
||||||
|
|
||||||
macro_rules! check_dispatch {
|
macro_rules! check_dispatch {
|
||||||
($mount:expr, $ct:expr, $body:expr) => (
|
($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 mut req = client.post($mount);
|
||||||
let ct: Option<ContentType> = $ct;
|
let ct: Option<ContentType> = $ct;
|
||||||
if let Some(ct) = ct {
|
if let Some(ct) = ct {
|
||||||
req.add_header(ct);
|
req.add_header(ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
let response = req.dispatch().await;
|
let response = req.dispatch();
|
||||||
let status = response.status();
|
let status = response.status();
|
||||||
let body_str = response.into_string().await;
|
let body_str = response.into_string();
|
||||||
let body: Option<&'static str> = $body;
|
let body: Option<&'static str> = $body;
|
||||||
match body {
|
match body {
|
||||||
Some(string) => assert_eq!(body_str, Some(string.to_string())),
|
Some(string) => assert_eq!(body_str, Some(string.to_string())),
|
||||||
|
@ -55,15 +55,15 @@ mod tests {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn exact_match_or_forward() {
|
fn exact_match_or_forward() {
|
||||||
check_dispatch!("/first", Some(ContentType::JSON), Some("specified"));
|
check_dispatch!("/first", Some(ContentType::JSON), Some("specified"));
|
||||||
check_dispatch!("/first", None, Some("unspecified"));
|
check_dispatch!("/first", None, Some("unspecified"));
|
||||||
check_dispatch!("/first", Some(ContentType::HTML), Some("unspecified"));
|
check_dispatch!("/first", Some(ContentType::HTML), Some("unspecified"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn exact_match_or_none() {
|
fn exact_match_or_none() {
|
||||||
check_dispatch!("/second", Some(ContentType::JSON), Some("specified_json"));
|
check_dispatch!("/second", Some(ContentType::JSON), Some("specified_json"));
|
||||||
check_dispatch!("/second", Some(ContentType::HTML), Some("specified_html"));
|
check_dispatch!("/second", Some(ContentType::HTML), Some("specified_html"));
|
||||||
check_dispatch!("/second", Some(ContentType::CSV), None);
|
check_dispatch!("/second", Some(ContentType::CSV), None);
|
||||||
|
|
|
@ -11,13 +11,13 @@ fn not_found() -> Redirect {
|
||||||
|
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn error_catcher_redirect() {
|
fn error_catcher_redirect() {
|
||||||
let client = Client::new(rocket::ignite().register(catchers![not_found])).await.unwrap();
|
let client = Client::new(rocket::ignite().register(catchers![not_found])).unwrap();
|
||||||
let response = client.get("/unknown").dispatch().await;
|
let response = client.get("/unknown").dispatch();
|
||||||
println!("Response:\n{:?}", response);
|
println!("Response:\n{:?}", response);
|
||||||
|
|
||||||
let location: Vec<_> = response.headers().get("location").collect();
|
let location: Vec<_> = response.headers().get("location").collect();
|
||||||
|
|
|
@ -13,23 +13,23 @@ fn files(route: &Route, path: PathBuf) -> String {
|
||||||
|
|
||||||
mod route_guard_tests {
|
mod route_guard_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
async fn assert_path(client: &Client, path: &str) {
|
fn assert_path(client: &Client, path: &str) {
|
||||||
let res = client.get(path).dispatch().await;
|
let res = client.get(path).dispatch();
|
||||||
assert_eq!(res.into_string().await, Some(path.into()));
|
assert_eq!(res.into_string(), Some(path.into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn check_mount_path() {
|
fn check_mount_path() {
|
||||||
let rocket = rocket::ignite()
|
let rocket = rocket::ignite()
|
||||||
.mount("/first", routes![files])
|
.mount("/first", routes![files])
|
||||||
.mount("/second", routes![files]);
|
.mount("/second", routes![files]);
|
||||||
|
|
||||||
let client = Client::new(rocket).await.unwrap();
|
let client = Client::new(rocket).unwrap();
|
||||||
assert_path(&client, "/first/some/path").await;
|
assert_path(&client, "/first/some/path");
|
||||||
assert_path(&client, "/second/some/path").await;
|
assert_path(&client, "/second/some/path");
|
||||||
assert_path(&client, "/first/second/b/c").await;
|
assert_path(&client, "/first/second/b/c");
|
||||||
assert_path(&client, "/second/a/b/c").await;
|
assert_path(&client, "/second/a/b/c");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -31,14 +31,14 @@ fn dual(user: String, path: Segments<'_>) -> String {
|
||||||
|
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn segments_works() {
|
fn segments_works() {
|
||||||
let rocket = rocket::ignite()
|
let rocket = rocket::ignite()
|
||||||
.mount("/", routes![test, two, one_two, none, dual])
|
.mount("/", routes![test, two, one_two, none, dual])
|
||||||
.mount("/point", routes![test, two, one_two, 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
|
// We construct a path that matches each of the routes above. We ensure the
|
||||||
// prefix is stripped, confirming that dynamic segments are working.
|
// prefix is stripped, confirming that dynamic segments are working.
|
||||||
|
@ -47,8 +47,8 @@ mod tests {
|
||||||
"/static", "/point/static"]
|
"/static", "/point/static"]
|
||||||
{
|
{
|
||||||
let path = "this/is/the/path/we/want";
|
let path = "this/is/the/path/we/want";
|
||||||
let response = client.get(format!("{}/{}", prefix, path)).dispatch().await;
|
let response = client.get(format!("{}/{}", prefix, path)).dispatch();
|
||||||
assert_eq!(response.into_string().await, Some(path.into()));
|
assert_eq!(response.into_string(), Some(path.into()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -22,51 +22,51 @@ fn lenient<'r>(form: LenientForm<MyForm<'r>>) -> String {
|
||||||
|
|
||||||
mod strict_and_lenient_forms_tests {
|
mod strict_and_lenient_forms_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{Status, ContentType};
|
use rocket::http::{Status, ContentType};
|
||||||
|
|
||||||
const FIELD_VALUE: &str = "just_some_value";
|
const FIELD_VALUE: &str = "just_some_value";
|
||||||
|
|
||||||
async fn client() -> Client {
|
fn client() -> Client {
|
||||||
Client::new(rocket::ignite().mount("/", routes![strict, lenient])).await.unwrap()
|
Client::new(rocket::ignite().mount("/", routes![strict, lenient])).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_strict_form() {
|
fn test_strict_form() {
|
||||||
let client = client().await;
|
let client = client();
|
||||||
let response = client.post("/strict")
|
let response = client.post("/strict")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body(format!("field={}", FIELD_VALUE))
|
.body(format!("field={}", FIELD_VALUE))
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(response.status(), Status::Ok);
|
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")
|
let response = client.post("/strict")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body(format!("field={}&extra=whoops", FIELD_VALUE))
|
.body(format!("field={}&extra=whoops", FIELD_VALUE))
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(response.status(), Status::UnprocessableEntity);
|
assert_eq!(response.status(), Status::UnprocessableEntity);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_lenient_form() {
|
fn test_lenient_form() {
|
||||||
let client = client().await;
|
let client = client();
|
||||||
let response = client.post("/lenient")
|
let response = client.post("/lenient")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body(format!("field={}", FIELD_VALUE))
|
.body(format!("field={}", FIELD_VALUE))
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(response.status(), Status::Ok);
|
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")
|
let response = client.post("/lenient")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body(format!("field={}&extra=whoops", FIELD_VALUE))
|
.body(format!("field={}&extra=whoops", FIELD_VALUE))
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(response.status(), Status::Ok);
|
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()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,33 +1,33 @@
|
||||||
// use rocket::http::Header;
|
use rocket::http::Header;
|
||||||
// use rocket::local::Client;
|
use rocket::local::blocking::Client;
|
||||||
//
|
|
||||||
// #[test]
|
#[test]
|
||||||
// fn test_local_request_clone_soundness() {
|
fn test_local_request_clone_soundness() {
|
||||||
// let client = Client::new(rocket::ignite()).unwrap();
|
let client = Client::new(rocket::ignite()).unwrap();
|
||||||
//
|
|
||||||
// // creates two LocalRequest instances that shouldn't share the same req
|
// creates two LocalRequest instances that shouldn't share the same req
|
||||||
// let r1 = client.get("/").header(Header::new("key", "val1"));
|
let r1 = client.get("/").header(Header::new("key", "val1"));
|
||||||
// let mut r2 = r1.clone();
|
let mut r2 = r1.clone();
|
||||||
//
|
|
||||||
// // save the iterator, which internally holds a slice
|
// save the iterator, which internally holds a slice
|
||||||
// let mut iter = r1.inner().headers().get("key");
|
let mut iter = r1.inner().headers().get("key");
|
||||||
//
|
|
||||||
// // insert headers to force header map reallocation.
|
// insert headers to force header map reallocation.
|
||||||
// for i in 0..100 {
|
for i in 0..100 {
|
||||||
// r2.add_header(Header::new(i.to_string(), i.to_string()));
|
r2.add_header(Header::new(i.to_string(), i.to_string()));
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// // Replace the original key/val.
|
// Replace the original key/val.
|
||||||
// r2.add_header(Header::new("key", "val2"));
|
r2.add_header(Header::new("key", "val2"));
|
||||||
//
|
|
||||||
// // Heap massage: so we've got crud to print.
|
// Heap massage: so we've got crud to print.
|
||||||
// let _: Vec<usize> = vec![0, 0xcafebabe, 31337, 0];
|
let _: Vec<usize> = vec![0, 0xcafebabe, 31337, 0];
|
||||||
//
|
|
||||||
// // Ensure we're good.
|
// Ensure we're good.
|
||||||
// let s = iter.next().unwrap();
|
let s = iter.next().unwrap();
|
||||||
// println!("{}", s);
|
println!("{}", s);
|
||||||
//
|
|
||||||
// // And that we've got the right data.
|
// And that we've got the right data.
|
||||||
// assert_eq!(r1.inner().headers().get("key").collect::<Vec<_>>(), vec!["val1"]);
|
assert_eq!(r1.inner().headers().get("key").collect::<Vec<_>>(), vec!["val1"]);
|
||||||
// assert_eq!(r2.inner().headers().get("key").collect::<Vec<_>>(), vec!["val1", "val2"]);
|
assert_eq!(r2.inner().headers().get("key").collect::<Vec<_>>(), vec!["val1", "val2"]);
|
||||||
// }
|
}
|
||||||
|
|
|
@ -29,31 +29,31 @@ fn rocket() -> rocket::Rocket {
|
||||||
|
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{Status, uri::Uri};
|
use rocket::http::{Status, uri::Uri};
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn uri_percent_encoding_redirect() {
|
fn uri_percent_encoding_redirect() {
|
||||||
let expected_location = vec!["/hello/John%5B%5D%7C%5C%25@%5E"];
|
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();
|
let location: Vec<_> = response.headers().get("location").collect();
|
||||||
assert_eq!(response.status(), Status::SeeOther);
|
assert_eq!(response.status(), Status::SeeOther);
|
||||||
assert_eq!(&location, &expected_location);
|
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();
|
let location: Vec<_> = response.headers().get("location").collect();
|
||||||
assert_eq!(response.status(), Status::SeeOther);
|
assert_eq!(response.status(), Status::SeeOther);
|
||||||
assert_eq!(&location, &expected_location);
|
assert_eq!(&location, &expected_location);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn uri_percent_encoding_get() {
|
fn uri_percent_encoding_get() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let name = Uri::percent_encode(NAME);
|
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.status(), Status::Ok);
|
||||||
assert_eq!(response.into_string().await.unwrap(), format!("Hello, {}!", NAME));
|
assert_eq!(response.into_string().unwrap(), format!("Hello, {}!", NAME));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,7 +2,7 @@ use rocket::{self, State};
|
||||||
use rocket::fairing::AdHoc;
|
use rocket::fairing::AdHoc;
|
||||||
use rocket::config::{self, Config, Environment, LoggingLevel};
|
use rocket::config::{self, Config, Environment, LoggingLevel};
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
struct LocalConfig(Config);
|
struct LocalConfig(Config);
|
||||||
|
|
||||||
|
@ -62,9 +62,7 @@ pub fn test_config(environment: Environment) {
|
||||||
}))
|
}))
|
||||||
.mount("/", routes![check_config]);
|
.mount("/", routes![check_config]);
|
||||||
|
|
||||||
rocket::async_test(async move {
|
let client = Client::new(rocket).unwrap();
|
||||||
let client = Client::new(rocket).await.unwrap();
|
let response = client.get("/check_config").dispatch();
|
||||||
let response = client.get("/check_config").dispatch().await;
|
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,41 +1,41 @@
|
||||||
use super::Person;
|
use super::Person;
|
||||||
use rocket::http::{Accept, ContentType, Header, MediaType, Method, Status};
|
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>>
|
where H: Into<Header<'static>>
|
||||||
{
|
{
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
let response = client.req(method, uri).header(header).dispatch().await;
|
let response = client.req(method, uri).header(header).dispatch();
|
||||||
assert_eq!(response.status(), status);
|
assert_eq!(response.status(), status);
|
||||||
assert_eq!(response.into_string().await, Some(body));
|
assert_eq!(response.into_string(), Some(body));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_hello() {
|
fn test_hello() {
|
||||||
let person = Person { name: "Michael".to_string(), age: 80, };
|
let person = Person { name: "Michael".to_string(), age: 80, };
|
||||||
let body = serde_json::to_string(&person).unwrap();
|
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::JSON, Status::Ok, body.clone());
|
||||||
test(Method::Get, "/hello/Michael/80", Accept::Any, Status::Ok, body.clone()).await;
|
test(Method::Get, "/hello/Michael/80", Accept::Any, Status::Ok, body.clone());
|
||||||
|
|
||||||
// No `Accept` header is an implicit */*.
|
// 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 person = Person { name: "".to_string(), age: 99, };
|
||||||
let body = serde_json::to_string(&person).unwrap();
|
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]
|
#[test]
|
||||||
async fn test_hello_invalid_content_type() {
|
fn test_hello_invalid_content_type() {
|
||||||
let b = format!("<p>'{}' requests are not supported.</p>", MediaType::HTML);
|
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::Get, "/hello/Michael/80", Accept::HTML, Status::NotFound, b.clone());
|
||||||
test(Method::Post, "/hello/80", ContentType::HTML, Status::NotFound, b).await;
|
test(Method::Post, "/hello/80", ContentType::HTML, Status::NotFound, b);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_404() {
|
fn test_404() {
|
||||||
let body = "<p>Sorry, '/unknown' is an invalid path! Try \
|
let body = "<p>Sorry, '/unknown' is an invalid path! Try \
|
||||||
/hello/<name>/<age> instead.</p>";
|
/hello/<name>/<age> 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());
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,17 +1,17 @@
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use super::rocket;
|
use super::rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::*;
|
use rocket::http::*;
|
||||||
use rocket_contrib::templates::Template;
|
use rocket_contrib::templates::Template;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_submit() {
|
fn test_submit() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let response = client.post("/submit")
|
let response = client.post("/submit")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body("message=Hello from Rocket!")
|
.body("message=Hello from Rocket!")
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
let cookie_headers: Vec<_> = response.headers().get("Set-Cookie").collect();
|
let cookie_headers: Vec<_> = response.headers().get("Set-Cookie").collect();
|
||||||
let location_headers: Vec<_> = response.headers().get("Location").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()]);
|
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.
|
// 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 {
|
let response = match optional_cookie {
|
||||||
Some(cookie) => client.get("/").cookie(cookie).dispatch().await,
|
Some(cookie) => client.get("/").cookie(cookie).dispatch(),
|
||||||
None => client.get("/").dispatch().await,
|
None => client.get("/").dispatch(),
|
||||||
};
|
};
|
||||||
|
|
||||||
assert_eq!(response.status(), Status::Ok);
|
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]
|
#[test]
|
||||||
async fn test_index() {
|
fn test_index() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
|
|
||||||
// Render the template with an empty context.
|
// Render the template with an empty context.
|
||||||
let mut context: HashMap<&str, &str> = HashMap::new();
|
let mut context: HashMap<&str, &str> = HashMap::new();
|
||||||
let template = Template::show(client.cargo(), "index", &context).unwrap();
|
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.
|
// Render the template with a context that contains the message.
|
||||||
context.insert("message", "Hello from Rocket!");
|
context.insert("message", "Hello from Rocket!");
|
||||||
let template = Template::show(client.cargo(), "index", &context).unwrap();
|
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);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,31 +1,31 @@
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
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()
|
let rocket = rocket::ignite()
|
||||||
.mount("/", routes![super::hello])
|
.mount("/", routes![super::hello])
|
||||||
.register(catchers![super::not_found]);
|
.register(catchers![super::not_found]);
|
||||||
|
|
||||||
let client = Client::new(rocket).await.unwrap();
|
let client = Client::new(rocket).unwrap();
|
||||||
let response = client.get(uri).dispatch().await;
|
let response = client.get(uri).dispatch();
|
||||||
assert_eq!(response.status(), status);
|
assert_eq!(response.status(), status);
|
||||||
assert_eq!(response.into_string().await, Some(body));
|
assert_eq!(response.into_string(), Some(body));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_hello() {
|
fn test_hello() {
|
||||||
let (name, age) = ("Arthur", 42);
|
let (name, age) = ("Arthur", 42);
|
||||||
let uri = format!("/hello/{}/{}", name, age);
|
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]
|
#[test]
|
||||||
async fn test_hello_invalid_age() {
|
fn test_hello_invalid_age() {
|
||||||
for &(name, age) in &[("Ford", -129), ("Trillian", 128)] {
|
for &(name, age) in &[("Ford", -129), ("Trillian", 128)] {
|
||||||
let uri = format!("/hello/{}/{}", name, age);
|
let uri = format!("/hello/{}/{}", name, age);
|
||||||
let body = format!("<p>Sorry, but '{}' is not a valid path!</p>
|
let body = format!("<p>Sorry, but '{}' is not a valid path!</p>
|
||||||
<p>Try visiting /hello/<name>/<age> instead.</p>",
|
<p>Try visiting /hello/<name>/<age> instead.</p>",
|
||||||
uri);
|
uri);
|
||||||
test(&uri, Status::NotFound, body).await;
|
test(&uri, Status::NotFound, body);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,38 +1,38 @@
|
||||||
use super::rocket;
|
use super::rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn rewrite_get_put() {
|
fn rewrite_get_put() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some("Hello, fairings!".into()));
|
assert_eq!(response.into_string(), Some("Hello, fairings!".into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn counts() {
|
fn counts() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
|
|
||||||
// Issue 1 GET request.
|
// Issue 1 GET request.
|
||||||
client.get("/").dispatch().await;
|
client.get("/").dispatch();
|
||||||
|
|
||||||
// Check the GET count, taking into account _this_ GET request.
|
// Check the GET count, taking into account _this_ GET request.
|
||||||
let response = client.get("/counts").dispatch().await;
|
let response = client.get("/counts").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some("Get: 2\nPost: 0".into()));
|
assert_eq!(response.into_string(), Some("Get: 2\nPost: 0".into()));
|
||||||
|
|
||||||
// Issue 1 more GET request and a POST.
|
// Issue 1 more GET request and a POST.
|
||||||
client.get("/").dispatch().await;
|
client.get("/").dispatch();
|
||||||
client.post("/").dispatch().await;
|
client.post("/").dispatch();
|
||||||
|
|
||||||
// Check the counts.
|
// Check the counts.
|
||||||
let response = client.get("/counts").dispatch().await;
|
let response = client.get("/counts").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some("Get: 4\nPost: 1".into()));
|
assert_eq!(response.into_string(), Some("Get: 4\nPost: 1".into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn token() {
|
fn token() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
|
|
||||||
// Ensure the token is '123', which is what we have in `Rocket.toml`.
|
// Ensure the token is '123', which is what we have in `Rocket.toml`.
|
||||||
let res = client.get("/token").dispatch().await;
|
let res = client.get("/token").dispatch();
|
||||||
assert_eq!(res.into_string().await, Some("123".into()));
|
assert_eq!(res.into_string(), Some("123".into()));
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,24 +1,22 @@
|
||||||
use super::rocket;
|
use super::rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{ContentType, Status};
|
use rocket::http::{ContentType, Status};
|
||||||
|
|
||||||
fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T)
|
fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T)
|
||||||
where T: Into<Option<&'static str>> + Send
|
where T: Into<Option<&'static str>> + Send
|
||||||
{
|
{
|
||||||
rocket::async_test(async move {
|
let client = Client::new(rocket()).unwrap();
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
|
||||||
let query = format!("username={}&password={}&age={}", user, pass, age);
|
let query = format!("username={}&password={}&age={}", user, pass, age);
|
||||||
let response = client.post("/login")
|
let response = client.post("/login")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body(&query)
|
.body(&query)
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(response.status(), status);
|
assert_eq!(response.status(), status);
|
||||||
if let Some(expected_str) = body.into() {
|
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)));
|
assert!(body_str.map_or(false, |s| s.contains(expected_str)));
|
||||||
}
|
}
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -46,15 +44,13 @@ fn test_invalid_age() {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_bad_form(form_str: &str, status: Status) {
|
fn check_bad_form(form_str: &str, status: Status) {
|
||||||
rocket::async_test(async {
|
let client = Client::new(rocket()).unwrap();
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
|
||||||
let response = client.post("/login")
|
let response = client.post("/login")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body(form_str)
|
.body(form_str)
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(response.status(), status);
|
assert_eq!(response.status(), status);
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
@ -1,20 +1,20 @@
|
||||||
use super::{rocket, TemplateContext};
|
use super::{rocket, TemplateContext};
|
||||||
|
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Method::*;
|
use rocket::http::Method::*;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
use rocket_contrib::templates::Template;
|
use rocket_contrib::templates::Template;
|
||||||
|
|
||||||
macro_rules! dispatch {
|
macro_rules! dispatch {
|
||||||
($method:expr, $path:expr, |$client:ident, $response:ident| $body:expr) => ({
|
($method:expr, $path:expr, |$client:ident, $response:ident| $body:expr) => ({
|
||||||
let $client = Client::new(rocket()).await.unwrap();
|
let $client = Client::new(rocket()).unwrap();
|
||||||
let $response = $client.req($method, $path).dispatch().await;
|
let $response = $client.req($method, $path).dispatch();
|
||||||
$body
|
$body
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_root() {
|
fn test_root() {
|
||||||
// Check that the redirect works.
|
// Check that the redirect works.
|
||||||
for method in &[Get, Head] {
|
for method in &[Get, Head] {
|
||||||
dispatch!(*method, "/", |client, response| {
|
dispatch!(*method, "/", |client, response| {
|
||||||
|
@ -34,13 +34,13 @@ async fn test_root() {
|
||||||
let expected = Template::show(client.cargo(), "error/404", &map).unwrap();
|
let expected = Template::show(client.cargo(), "error/404", &map).unwrap();
|
||||||
|
|
||||||
assert_eq!(response.status(), Status::NotFound);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
assert_eq!(response.into_string().await, Some(expected));
|
assert_eq!(response.into_string(), Some(expected));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_name() {
|
fn test_name() {
|
||||||
// Check that the /hello/<name> route works.
|
// Check that the /hello/<name> route works.
|
||||||
dispatch!(Get, "/hello/Jack%20Daniels", |client, response| {
|
dispatch!(Get, "/hello/Jack%20Daniels", |client, response| {
|
||||||
let context = TemplateContext {
|
let context = TemplateContext {
|
||||||
|
@ -52,12 +52,12 @@ async fn test_name() {
|
||||||
|
|
||||||
let expected = Template::show(client.cargo(), "index", &context).unwrap();
|
let expected = Template::show(client.cargo(), "index", &context).unwrap();
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
assert_eq!(response.into_string().await, Some(expected));
|
assert_eq!(response.into_string(), Some(expected));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_404() {
|
fn test_404() {
|
||||||
// Check that the error catcher works.
|
// Check that the error catcher works.
|
||||||
dispatch!(Get, "/hello/", |client, response| {
|
dispatch!(Get, "/hello/", |client, response| {
|
||||||
let mut map = std::collections::HashMap::new();
|
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();
|
let expected = Template::show(client.cargo(), "error/404", &map).unwrap();
|
||||||
assert_eq!(response.status(), Status::NotFound);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
assert_eq!(response.into_string().await, Some(expected));
|
assert_eq!(response.into_string(), Some(expected));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
use rocket::{self, local::asynchronous::Client};
|
use rocket::{self, local::blocking::Client};
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn hello_world() {
|
fn hello_world() {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some("Hello, Rust 2018!".into()));
|
assert_eq!(response.into_string(), Some("Hello, Rust 2018!".into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tests unrelated to the example.
|
// Tests unrelated to the example.
|
||||||
|
@ -31,19 +31,19 @@ mod scoped_uri_tests {
|
||||||
.mount("/", rocket::routes![inner::hello])
|
.mount("/", rocket::routes![inner::hello])
|
||||||
}
|
}
|
||||||
|
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_inner_hello() {
|
fn test_inner_hello() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some("Hello! Try /Rust%202018.".into()));
|
assert_eq!(response.into_string(), Some("Hello! Try /Rust%202018.".into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_hello_name() {
|
fn test_hello_name() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let response = client.get("/Rust%202018").dispatch().await;
|
let response = client.get("/Rust%202018").dispatch();
|
||||||
assert_eq!(response.into_string().await.unwrap(), "Hello, Rust 2018! This is /Rust%202018.");
|
assert_eq!(response.into_string().unwrap(), "Hello, Rust 2018! This is /Rust%202018.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,34 +1,34 @@
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
async fn test(uri: String, expected: String) {
|
fn test(uri: String, expected: String) {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
assert_eq!(client.get(&uri).dispatch().await.into_string().await, Some(expected));
|
assert_eq!(client.get(&uri).dispatch().into_string(), Some(expected));
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn test_404(uri: &'static str) {
|
fn test_404(uri: &'static str) {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
assert_eq!(client.get(uri).dispatch().await.status(), Status::NotFound);
|
assert_eq!(client.get(uri).dispatch().status(), Status::NotFound);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_hello() {
|
fn test_hello() {
|
||||||
for &(name, age) in &[("Mike", 22), ("Michael", 80), ("A", 0), ("a", 127)] {
|
for &(name, age) in &[("Mike", 22), ("Michael", 80), ("A", 0), ("a", 127)] {
|
||||||
test(format!("/hello/{}/{}", name, age),
|
test(format!("/hello/{}/{}", name, age),
|
||||||
format!("Hello, {} year old named {}!", age, name)).await;
|
format!("Hello, {} year old named {}!", age, name));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_failing_hello() {
|
fn test_failing_hello() {
|
||||||
test_404("/hello/Mike/1000").await;
|
test_404("/hello/Mike/1000");
|
||||||
test_404("/hello/Mike/-129").await;
|
test_404("/hello/Mike/-129");
|
||||||
test_404("/hello/Mike/-1").await;
|
test_404("/hello/Mike/-1");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_hi() {
|
fn test_hi() {
|
||||||
for name in &["Mike", "A", "123", "hi", "c"] {
|
for name in &["Mike", "A", "123", "hi", "c"] {
|
||||||
test(format!("/hello/{}", name), name.to_string()).await;
|
test(format!("/hello/{}", name), name.to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn hello_world() {
|
fn hello_world() {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some("Hello, world!".into()));
|
assert_eq!(response.into_string(), Some("Hello, world!".into()));
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,71 +1,71 @@
|
||||||
use crate::rocket;
|
use crate::rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{Status, ContentType};
|
use rocket::http::{Status, ContentType};
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn bad_get_put() {
|
fn bad_get_put() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
|
|
||||||
// Try to get a message with an ID that doesn't exist.
|
// 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);
|
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("error"));
|
||||||
assert!(body.contains("Resource was not found."));
|
assert!(body.contains("Resource was not found."));
|
||||||
|
|
||||||
// Try to get a message with an invalid ID.
|
// 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_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.
|
// 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);
|
assert_eq!(res.status(), Status::BadRequest);
|
||||||
|
|
||||||
// Try to put a message for an ID that doesn't exist.
|
// Try to put a message for an ID that doesn't exist.
|
||||||
let res = client.put("/message/80")
|
let res = client.put("/message/80")
|
||||||
.header(ContentType::JSON)
|
.header(ContentType::JSON)
|
||||||
.body(r#"{ "contents": "Bye bye, world!" }"#)
|
.body(r#"{ "contents": "Bye bye, world!" }"#)
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(res.status(), Status::NotFound);
|
assert_eq!(res.status(), Status::NotFound);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn post_get_put_get() {
|
fn post_get_put_get() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
|
|
||||||
// Check that a message with ID 1 doesn't exist.
|
// 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);
|
assert_eq!(res.status(), Status::NotFound);
|
||||||
|
|
||||||
// Add a new message with ID 1.
|
// Add a new message with ID 1.
|
||||||
let res = client.post("/message/1")
|
let res = client.post("/message/1")
|
||||||
.header(ContentType::JSON)
|
.header(ContentType::JSON)
|
||||||
.body(r#"{ "contents": "Hello, world!" }"#)
|
.body(r#"{ "contents": "Hello, world!" }"#)
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(res.status(), Status::Ok);
|
assert_eq!(res.status(), Status::Ok);
|
||||||
|
|
||||||
// Check that the message exists with the correct contents.
|
// 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);
|
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("Hello, world!"));
|
||||||
|
|
||||||
// Change the message contents.
|
// Change the message contents.
|
||||||
let res = client.put("/message/1")
|
let res = client.put("/message/1")
|
||||||
.header(ContentType::JSON)
|
.header(ContentType::JSON)
|
||||||
.body(r#"{ "contents": "Bye bye, world!" }"#)
|
.body(r#"{ "contents": "Bye bye, world!" }"#)
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(res.status(), Status::Ok);
|
assert_eq!(res.status(), Status::Ok);
|
||||||
|
|
||||||
// Check that the message exists with the updated contents.
|
// 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);
|
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("Hello, world!"));
|
||||||
assert!(body.contains("Bye bye, world!"));
|
assert!(body.contains("Bye bye, world!"));
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,13 +1,13 @@
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_push_pop() {
|
fn test_push_pop() {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
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);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
|
|
||||||
let response = client.get("/pop").dispatch().await;
|
let response = client.get("/pop").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some("test1".to_string()));
|
assert_eq!(response.into_string(), Some("test1".to_string()));
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,14 +1,12 @@
|
||||||
use super::*;
|
use super::*;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{ContentType, Status};
|
use rocket::http::{ContentType, Status};
|
||||||
|
|
||||||
fn test(uri: &str, content_type: ContentType, status: Status, body: String) {
|
fn test(uri: &str, content_type: ContentType, status: Status, body: String) {
|
||||||
rocket::async_test(async move {
|
let client = Client::new(rocket()).unwrap();
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let response = client.get(uri).header(content_type).dispatch();
|
||||||
let response = client.get(uri).header(content_type).dispatch().await;
|
|
||||||
assert_eq!(response.status(), status);
|
assert_eq!(response.status(), status);
|
||||||
assert_eq!(response.into_string().await, Some(body));
|
assert_eq!(response.into_string(), Some(body));
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -30,9 +28,9 @@ fn test_echo() {
|
||||||
test(&uri, ContentType::Plain, Status::Ok, "echo this text".into());
|
test(&uri, ContentType::Plain, Status::Ok, "echo this text".into());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_upload() {
|
fn test_upload() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let expected_body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
|
let expected_body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
|
||||||
sed do eiusmod tempor incididunt ut labore et dolore \
|
sed do eiusmod tempor incididunt ut labore et dolore \
|
||||||
magna aliqua".to_string();
|
magna aliqua".to_string();
|
||||||
|
@ -41,14 +39,14 @@ async fn test_upload() {
|
||||||
let response = client.post("/upload")
|
let response = client.post("/upload")
|
||||||
.header(ContentType::Plain)
|
.header(ContentType::Plain)
|
||||||
.body(&expected_body)
|
.body(&expected_body)
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
|
|
||||||
// Ensure we get back the same body.
|
// 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.status(), Status::Ok);
|
||||||
assert_eq!(response.into_string().await, Some(expected_body));
|
assert_eq!(response.into_string(), Some(expected_body));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
use crate::rocket;
|
use crate::rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{Status, ContentType};
|
use rocket::http::{Status, ContentType};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
|
@ -8,27 +8,27 @@ struct Message {
|
||||||
contents: String
|
contents: String
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn msgpack_get() {
|
fn msgpack_get() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let res = client.get("/message/1").header(ContentType::MsgPack).dispatch().await;
|
let res = client.get("/message/1").header(ContentType::MsgPack).dispatch();
|
||||||
assert_eq!(res.status(), Status::Ok);
|
assert_eq!(res.status(), Status::Ok);
|
||||||
assert_eq!(res.content_type(), Some(ContentType::MsgPack));
|
assert_eq!(res.content_type(), Some(ContentType::MsgPack));
|
||||||
|
|
||||||
// Check that the message is `[1, "Hello, world!"]`
|
// 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]);
|
&[146, 1, 173, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn msgpack_post() {
|
fn msgpack_post() {
|
||||||
// Dispatch request with a message of `[2, "Goodbye, world!"]`.
|
// 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")
|
let res = client.post("/message")
|
||||||
.header(ContentType::MsgPack)
|
.header(ContentType::MsgPack)
|
||||||
.body(&[146, 2, 175, 71, 111, 111, 100, 98, 121, 101, 44, 32, 119, 111, 114, 108, 100, 33])
|
.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.status(), Status::Ok);
|
||||||
assert_eq!(res.into_string().await, Some("Goodbye, world!".into()));
|
assert_eq!(res.into_string(), Some("Goodbye, world!".into()));
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,30 +1,30 @@
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
async fn test_200(uri: &str, expected_body: &str) {
|
fn test_200(uri: &str, expected_body: &str) {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
let response = client.get(uri).dispatch().await;
|
let response = client.get(uri).dispatch();
|
||||||
assert_eq!(response.status(), Status::Ok);
|
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) {
|
fn test_303(uri: &str, expected_location: &str) {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
let response = client.get(uri).dispatch().await;
|
let response = client.get(uri).dispatch();
|
||||||
let location_headers: Vec<_> = response.headers().get("Location").collect();
|
let location_headers: Vec<_> = response.headers().get("Location").collect();
|
||||||
assert_eq!(response.status(), Status::SeeOther);
|
assert_eq!(response.status(), Status::SeeOther);
|
||||||
assert_eq!(location_headers, vec![expected_location]);
|
assert_eq!(location_headers, vec![expected_location]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test() {
|
fn test() {
|
||||||
test_200("/users/Sergio", "Hello, Sergio!").await;
|
test_200("/users/Sergio", "Hello, Sergio!");
|
||||||
test_200("/users/login",
|
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]
|
#[test]
|
||||||
async fn test_redirects() {
|
fn test_redirects() {
|
||||||
test_303("/", "/users/login").await;
|
test_303("/", "/users/login");
|
||||||
test_303("/users/unknown", "/users/login").await;
|
test_303("/users/unknown", "/users/login");
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,59 +1,59 @@
|
||||||
use super::{rocket, index};
|
use super::{rocket, index};
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{Status, ContentType};
|
use rocket::http::{Status, ContentType};
|
||||||
|
|
||||||
fn extract_id(from: &str) -> Option<String> {
|
fn extract_id(from: &str) -> Option<String> {
|
||||||
from.rfind('/').map(|i| &from[(i + 1)..]).map(|s| s.trim_end().to_string())
|
from.rfind('/').map(|i| &from[(i + 1)..]).map(|s| s.trim_end().to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn check_index() {
|
fn check_index() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
|
|
||||||
// Ensure the index returns what we expect.
|
// 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.status(), Status::Ok);
|
||||||
assert_eq!(response.content_type(), Some(ContentType::Plain));
|
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 {
|
fn upload_paste(client: &Client, body: &str) -> String {
|
||||||
let response = client.post("/").body(body).dispatch().await;
|
let response = client.post("/").body(body).dispatch();
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
assert_eq!(response.content_type(), Some(ContentType::Plain));
|
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 {
|
fn download_paste(client: &Client, id: &str) -> String {
|
||||||
let response = client.get(format!("/{}", id)).dispatch().await;
|
let response = client.get(format!("/{}", id)).dispatch();
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
response.into_string().await.unwrap()
|
response.into_string().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn pasting() {
|
fn pasting() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
|
|
||||||
// Do a trivial upload, just to make sure it works.
|
// Do a trivial upload, just to make sure it works.
|
||||||
let body_1 = "Hello, world!";
|
let body_1 = "Hello, world!";
|
||||||
let id_1 = upload_paste(&client, body_1).await;
|
let id_1 = upload_paste(&client, body_1);
|
||||||
assert_eq!(download_paste(&client, &id_1).await, body_1);
|
assert_eq!(download_paste(&client, &id_1), body_1);
|
||||||
|
|
||||||
// Make sure we can keep getting that paste.
|
// 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), 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).await, body_1);
|
assert_eq!(download_paste(&client, &id_1), body_1);
|
||||||
|
|
||||||
// Upload some unicode.
|
// Upload some unicode.
|
||||||
let body_2 = "こんにちは";
|
let body_2 = "こんにちは";
|
||||||
let id_2 = upload_paste(&client, body_2).await;
|
let id_2 = upload_paste(&client, body_2);
|
||||||
assert_eq!(download_paste(&client, &id_2).await, body_2);
|
assert_eq!(download_paste(&client, &id_2), body_2);
|
||||||
|
|
||||||
// Make sure we can get both pastes.
|
// Make sure we can get both pastes.
|
||||||
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_2).await, body_2);
|
assert_eq!(download_paste(&client, &id_2), body_2);
|
||||||
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_2).await, body_2);
|
assert_eq!(download_paste(&client, &id_2), body_2);
|
||||||
|
|
||||||
// Now a longer upload.
|
// Now a longer upload.
|
||||||
let body_3 = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
|
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.
|
in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
|
||||||
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
|
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
|
||||||
officia deserunt mollit anim id est laborum.";
|
officia deserunt mollit anim id est laborum.";
|
||||||
let id_3 = upload_paste(&client, body_3).await;
|
let id_3 = upload_paste(&client, body_3);
|
||||||
assert_eq!(download_paste(&client, &id_3).await, body_3);
|
assert_eq!(download_paste(&client, &id_3), body_3);
|
||||||
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_2).await, body_2);
|
assert_eq!(download_paste(&client, &id_2), body_2);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,77 +1,77 @@
|
||||||
use super::rocket;
|
use super::rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
macro_rules! run_test {
|
macro_rules! run_test {
|
||||||
($query:expr, |$response:ident| $body:expr) => ({
|
($query:expr, |$response:ident| $body:expr) => ({
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
#[allow(unused_mut)]
|
#[allow(unused_mut)]
|
||||||
let mut $response = client.get(format!("/hello{}", $query)).dispatch().await;
|
let mut $response = client.get(format!("/hello{}", $query)).dispatch();
|
||||||
$body
|
$body
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn age_and_name_params() {
|
fn age_and_name_params() {
|
||||||
run_test!("?age=10&first-name=john", |response| {
|
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()));
|
Some("Hello, 10 year old named john!".into()));
|
||||||
});
|
});
|
||||||
|
|
||||||
run_test!("?age=20&first-name=john", |response| {
|
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()));
|
Some("20 years old? Hi, john!".into()));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn age_param_only() {
|
fn age_param_only() {
|
||||||
run_test!("?age=10", |response| {
|
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()));
|
Some("We're gonna need a name, and only a name.".into()));
|
||||||
});
|
});
|
||||||
|
|
||||||
run_test!("?age=20", |response| {
|
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()));
|
Some("We're gonna need a name, and only a name.".into()));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn name_param_only() {
|
fn name_param_only() {
|
||||||
run_test!("?first-name=John", |response| {
|
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]
|
#[test]
|
||||||
async fn no_params() {
|
fn no_params() {
|
||||||
run_test!("", |response| {
|
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()));
|
Some("We're gonna need a name, and only a name.".into()));
|
||||||
});
|
});
|
||||||
|
|
||||||
run_test!("?", |response| {
|
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()));
|
Some("We're gonna need a name, and only a name.".into()));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn extra_params() {
|
fn extra_params() {
|
||||||
run_test!("?age=20&first-name=Bob&extra", |response| {
|
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()));
|
Some("20 years old? Hi, Bob!".into()));
|
||||||
});
|
});
|
||||||
|
|
||||||
run_test!("?age=30&first-name=Bob&extra", |response| {
|
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()));
|
Some("We're gonna need a name, and only a name.".into()));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn wrong_path() {
|
fn wrong_path() {
|
||||||
run_test!("/other?age=20&first-name=Bob", |response| {
|
run_test!("/other?age=20&first-name=Bob", |response| {
|
||||||
assert_eq!(response.status(), Status::NotFound);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
});
|
});
|
||||||
|
|
|
@ -1,30 +1,30 @@
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
async fn test(uri: String, expected: String) {
|
fn test(uri: String, expected: String) {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
let response = client.get(&uri).dispatch().await;
|
let response = client.get(&uri).dispatch();
|
||||||
assert_eq!(response.into_string().await, Some(expected));
|
assert_eq!(response.into_string(), Some(expected));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_hello() {
|
fn test_hello() {
|
||||||
for &(name, age) in &[("Mike", 22), ("Michael", 80), ("A", 0), ("a", 127)] {
|
for &(name, age) in &[("Mike", 22), ("Michael", 80), ("A", 0), ("a", 127)] {
|
||||||
test(format!("/hello/{}/{}", name, age),
|
test(format!("/hello/{}/{}", name, age),
|
||||||
format!("Hello, {} year old named {}!", age, name)).await;
|
format!("Hello, {} year old named {}!", age, name));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_failing_hello_hi() {
|
fn test_failing_hello_hi() {
|
||||||
// Invalid integers.
|
// Invalid integers.
|
||||||
for &(name, age) in &[("Mike", 1000), ("Michael", 128), ("A", -800), ("a", -200)] {
|
for &(name, age) in &[("Mike", 1000), ("Michael", 128), ("A", -800), ("a", -200)] {
|
||||||
test(format!("/hello/{}/{}", name, age),
|
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.
|
// Non-integers.
|
||||||
for &(name, age) in &[("Mike", "!"), ("Michael", "hi"), ("A", "blah"), ("a", "0-1")] {
|
for &(name, age) in &[("Mike", "!"), ("Michael", "hi"), ("A", "blah"), ("a", "0-1")] {
|
||||||
test(format!("/hello/{}/{}", name, age),
|
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));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
use super::rocket;
|
use super::rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn hello() {
|
fn hello() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some("Rocketeer".into()));
|
assert_eq!(response.into_string(), Some("Rocketeer".into()));
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{Status, ContentType};
|
use rocket::http::{Status, ContentType};
|
||||||
|
|
||||||
use std::env;
|
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!";
|
const UPLOAD_CONTENTS: &str = "Hey! I'm going to be uploaded. :D Yay!";
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_index() {
|
fn test_index() {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
let res = client.get("/").dispatch().await;
|
let res = client.get("/").dispatch();
|
||||||
assert_eq!(res.into_string().await, Some(super::index().to_string()));
|
assert_eq!(res.into_string(), Some(super::index().to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_raw_upload() {
|
fn test_raw_upload() {
|
||||||
// Delete the upload file before we begin.
|
// Delete the upload file before we begin.
|
||||||
let upload_file = env::temp_dir().join("upload.txt");
|
let upload_file = env::temp_dir().join("upload.txt");
|
||||||
let _ = fs::remove_file(&upload_file);
|
let _ = fs::remove_file(&upload_file);
|
||||||
|
|
||||||
// Do the upload. Make sure we get the expected results.
|
// 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")
|
let res = client.post("/upload")
|
||||||
.header(ContentType::Plain)
|
.header(ContentType::Plain)
|
||||||
.body(UPLOAD_CONTENTS)
|
.body(UPLOAD_CONTENTS)
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
assert_eq!(res.status(), Status::Ok);
|
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.
|
// Ensure we find the body in the /tmp/upload.txt file.
|
||||||
let mut file_contents = String::new();
|
let mut file_contents = String::new();
|
||||||
|
|
|
@ -1,15 +1,15 @@
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
async fn client() -> Client {
|
fn client() -> Client {
|
||||||
let rocket = rocket::ignite().mount("/", routes![super::root, super::login]);
|
let rocket = rocket::ignite().mount("/", routes![super::root, super::login]);
|
||||||
Client::new(rocket).await.unwrap()
|
Client::new(rocket).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_root() {
|
fn test_root() {
|
||||||
let client = client().await;
|
let client = client();
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
|
|
||||||
assert!(response.body().is_none());
|
assert!(response.body().is_none());
|
||||||
assert_eq!(response.status(), Status::SeeOther);
|
assert_eq!(response.status(), Status::SeeOther);
|
||||||
|
@ -22,9 +22,9 @@ async fn test_root() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_login() {
|
fn test_login() {
|
||||||
let client = client().await;
|
let client = client();
|
||||||
let r = client.get("/login").dispatch().await;
|
let r = client.get("/login").dispatch();
|
||||||
assert_eq!(r.into_string().await, Some("Hi! Please log in before continuing.".into()));
|
assert_eq!(r.into_string(), Some("Hi! Please log in before continuing.".into()));
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,29 +29,29 @@ fn rocket() -> rocket::Rocket {
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Header;
|
use rocket::http::Header;
|
||||||
|
|
||||||
async fn test_header_count<'h>(headers: Vec<Header<'static>>) {
|
fn test_header_count<'h>(headers: Vec<Header<'static>>) {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
let mut req = client.get("/");
|
let mut req = client.get("/");
|
||||||
for header in headers.iter().cloned() {
|
for header in headers.iter().cloned() {
|
||||||
req.add_header(header);
|
req.add_header(header);
|
||||||
}
|
}
|
||||||
|
|
||||||
let response = req.dispatch().await;
|
let response = req.dispatch();
|
||||||
let expect = format!("Your request contained {} headers!", headers.len());
|
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]
|
#[test]
|
||||||
async fn test_n_headers() {
|
fn test_n_headers() {
|
||||||
for i in 0..50 {
|
for i in 0..50 {
|
||||||
let headers = (0..i)
|
let headers = (0..i)
|
||||||
.map(|n| Header::new(n.to_string(), n.to_string()))
|
.map(|n| Header::new(n.to_string(), n.to_string()))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
test_header_count(headers).await;
|
test_header_count(headers);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,18 +1,18 @@
|
||||||
use std::sync::atomic::Ordering;
|
use std::sync::atomic::Ordering;
|
||||||
|
|
||||||
use super::{rocket, Atomics};
|
use super::{rocket, Atomics};
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test() {
|
fn test() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
client.get("/sync").dispatch().await;
|
client.get("/sync").dispatch();
|
||||||
|
|
||||||
let atomics = client.cargo().state::<Atomics>().unwrap();
|
let atomics = client.cargo().state::<Atomics>().unwrap();
|
||||||
assert_eq!(atomics.uncached.load(Ordering::Relaxed), 2);
|
assert_eq!(atomics.uncached.load(Ordering::Relaxed), 2);
|
||||||
assert_eq!(atomics.cached.load(Ordering::Relaxed), 1);
|
assert_eq!(atomics.cached.load(Ordering::Relaxed), 1);
|
||||||
|
|
||||||
client.get("/async").dispatch().await;
|
client.get("/async").dispatch();
|
||||||
|
|
||||||
let atomics = client.cargo().state::<Atomics>().unwrap();
|
let atomics = client.cargo().state::<Atomics>().unwrap();
|
||||||
assert_eq!(atomics.uncached.load(Ordering::Relaxed), 4);
|
assert_eq!(atomics.uncached.load(Ordering::Relaxed), 4);
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
use super::rocket;
|
use super::rocket;
|
||||||
use rocket::local::asynchronous::{Client, LocalResponse};
|
use rocket::local::blocking::{Client, LocalResponse};
|
||||||
use rocket::http::{Status, Cookie, ContentType};
|
use rocket::http::{Status, Cookie, ContentType};
|
||||||
|
|
||||||
fn user_id_cookie(response: &LocalResponse<'_>) -> Option<Cookie<'static>> {
|
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())
|
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")
|
let response = client.post("/login")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body(format!("username={}&password={}", user, pass))
|
.body(format!("username={}&password={}", user, pass))
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
user_id_cookie(&response)
|
user_id_cookie(&response)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn redirect_on_index() {
|
fn redirect_on_index() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.status(), Status::SeeOther);
|
assert_eq!(response.status(), Status::SeeOther);
|
||||||
assert_eq!(response.headers().get_one("Location"), Some("/login"));
|
assert_eq!(response.headers().get_one("Location"), Some("/login"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn can_login() {
|
fn can_login() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
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);
|
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."));
|
assert!(body.contains("Please login to continue."));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn login_fails() {
|
fn login_fails() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
assert!(login(&client, "Seergio", "password").await.is_none());
|
assert!(login(&client, "Seergio", "password").is_none());
|
||||||
assert!(login(&client, "Sergio", "idontknow").await.is_none());
|
assert!(login(&client, "Sergio", "idontknow").is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn login_logout_succeeds() {
|
fn login_logout_succeeds() {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let login_cookie = login(&client, "Sergio", "password").await.expect("logged in");
|
let login_cookie = login(&client, "Sergio", "password").expect("logged in");
|
||||||
|
|
||||||
// Ensure we're 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);
|
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"));
|
assert!(body.contains("Logged in with user ID 1"));
|
||||||
|
|
||||||
// One more.
|
// 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.status(), Status::SeeOther);
|
||||||
assert_eq!(response.headers().get_one("Location"), Some("/"));
|
assert_eq!(response.headers().get_one("Location"), Some("/"));
|
||||||
|
|
||||||
// Logout.
|
// 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");
|
let cookie = user_id_cookie(&response).expect("logout cookie");
|
||||||
assert!(cookie.value().is_empty());
|
assert!(cookie.value().is_empty());
|
||||||
|
|
||||||
|
@ -72,9 +72,9 @@ async fn login_logout_succeeds() {
|
||||||
assert_eq!(response.headers().get_one("Location"), Some("/login"));
|
assert_eq!(response.headers().get_one("Location"), Some("/login"));
|
||||||
|
|
||||||
// The page should show the success message, and no errors.
|
// 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);
|
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("Successfully logged out."));
|
||||||
assert!(!body.contains("Error"));
|
assert!(!body.contains("Error"));
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,28 +1,28 @@
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
async fn register_hit(client: &Client) {
|
fn register_hit(client: &Client) {
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_count(client: &Client) -> usize {
|
fn get_count(client: &Client) -> usize {
|
||||||
let response = client.get("/count").dispatch().await;
|
let response = client.get("/count").dispatch();
|
||||||
response.into_string().await.and_then(|s| s.parse().ok()).unwrap()
|
response.into_string().and_then(|s| s.parse().ok()).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_count() {
|
fn test_count() {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
|
|
||||||
// Count should start at 0.
|
// 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; }
|
for _ in 0..99 { register_hit(&client); }
|
||||||
assert_eq!(get_count(&client).await, 99);
|
assert_eq!(get_count(&client), 99);
|
||||||
|
|
||||||
register_hit(&client).await;
|
register_hit(&client);
|
||||||
assert_eq!(get_count(&client).await, 100);
|
assert_eq!(get_count(&client), 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[rocket::async_test]
|
||||||
|
|
|
@ -1,19 +1,19 @@
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
|
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
use super::rocket;
|
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>>
|
where T: Into<Option<&'static str>>
|
||||||
{
|
{
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let response = client.get(path).dispatch().await;
|
let response = client.get(path).dispatch();
|
||||||
assert_eq!(response.status(), status);
|
assert_eq!(response.status(), status);
|
||||||
|
|
||||||
let body_data = response.into_bytes().await;
|
let body_data = response.into_bytes();
|
||||||
if let Some(filename) = file.into() {
|
if let Some(filename) = file.into() {
|
||||||
let expected_data = read_file_content(filename);
|
let expected_data = read_file_content(filename);
|
||||||
assert!(body_data.map_or(false, |s| s == expected_data));
|
assert!(body_data.map_or(false, |s| s == expected_data));
|
||||||
|
@ -28,29 +28,29 @@ fn read_file_content(path: &str) -> Vec<u8> {
|
||||||
file_content
|
file_content
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_index_html() {
|
fn test_index_html() {
|
||||||
test_query_file("/", "static/index.html", Status::Ok).await;
|
test_query_file("/", "static/index.html", Status::Ok);
|
||||||
test_query_file("/?v=1", "static/index.html", Status::Ok).await;
|
test_query_file("/?v=1", "static/index.html", Status::Ok);
|
||||||
test_query_file("/?this=should&be=ignored", "static/index.html", Status::Ok).await;
|
test_query_file("/?this=should&be=ignored", "static/index.html", Status::Ok);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_hidden_file() {
|
fn test_hidden_file() {
|
||||||
test_query_file("/hidden/hi.txt", "static/hidden/hi.txt", Status::Ok).await;
|
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).await;
|
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).await;
|
test_query_file("/hidden/hi.txt?v=1&a=b", "static/hidden/hi.txt", Status::Ok);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_icon_file() {
|
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);
|
||||||
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_invalid_path() {
|
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);
|
||||||
test_query_file("/thou/shalt/not/exist", None, Status::NotFound).await;
|
test_query_file("/thou/shalt/not/exist", None, Status::NotFound);
|
||||||
test_query_file("/thou/shalt/not/exist?a=b&c=d", None, Status::NotFound).await;
|
test_query_file("/thou/shalt/not/exist?a=b&c=d", None, Status::NotFound);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,32 +1,32 @@
|
||||||
use std::fs::{self, File};
|
use std::fs::{self, File};
|
||||||
use std::io::prelude::*;
|
use std::io::prelude::*;
|
||||||
|
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_root() {
|
fn test_root() {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
let res = client.get("/").dispatch().await;
|
let res = client.get("/").dispatch();
|
||||||
|
|
||||||
// Check that we have exactly 25,000 'a'.
|
// 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);
|
assert_eq!(res_str.len(), 25000);
|
||||||
for byte in res_str.as_bytes() {
|
for byte in res_str.as_bytes() {
|
||||||
assert_eq!(*byte, b'a');
|
assert_eq!(*byte, b'a');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_file() {
|
fn test_file() {
|
||||||
// Create the 'big_file'
|
// Create the 'big_file'
|
||||||
const CONTENTS: &str = "big_file contents...not so big here";
|
const CONTENTS: &str = "big_file contents...not so big here";
|
||||||
let mut file = File::create(super::FILENAME).expect("create big_file");
|
let mut file = File::create(super::FILENAME).expect("create big_file");
|
||||||
file.write_all(CONTENTS.as_bytes()).expect("write to big_file");
|
file.write_all(CONTENTS.as_bytes()).expect("write to big_file");
|
||||||
|
|
||||||
// Get the big file contents, hopefully.
|
// Get the big file contents, hopefully.
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
let res = client.get("/big_file").dispatch().await;
|
let res = client.get("/big_file").dispatch();
|
||||||
assert_eq!(res.into_string().await, Some(CONTENTS.into()));
|
assert_eq!(res.into_string(), Some(CONTENTS.into()));
|
||||||
|
|
||||||
// Delete the 'big_file'.
|
// Delete the 'big_file'.
|
||||||
fs::remove_file(super::FILENAME).expect("remove big_file");
|
fs::remove_file(super::FILENAME).expect("remove big_file");
|
||||||
|
|
|
@ -1,19 +1,19 @@
|
||||||
use super::rocket;
|
use super::rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Method::*;
|
use rocket::http::Method::*;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
use rocket_contrib::templates::Template;
|
use rocket_contrib::templates::Template;
|
||||||
|
|
||||||
macro_rules! dispatch {
|
macro_rules! dispatch {
|
||||||
($method:expr, $path:expr, |$client:ident, $response:ident| $body:expr) => ({
|
($method:expr, $path:expr, |$client:ident, $response:ident| $body:expr) => ({
|
||||||
let $client = Client::new(rocket()).await.unwrap();
|
let $client = Client::new(rocket()).unwrap();
|
||||||
let $response = $client.req($method, $path).dispatch().await;
|
let $response = $client.req($method, $path).dispatch();
|
||||||
$body
|
$body
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_root() {
|
fn test_root() {
|
||||||
// Check that the redirect works.
|
// Check that the redirect works.
|
||||||
for method in &[Get, Head] {
|
for method in &[Get, Head] {
|
||||||
dispatch!(*method, "/", |client, response| {
|
dispatch!(*method, "/", |client, response| {
|
||||||
|
@ -33,13 +33,13 @@ async fn test_root() {
|
||||||
let expected = Template::show(client.cargo(), "error/404", &map).unwrap();
|
let expected = Template::show(client.cargo(), "error/404", &map).unwrap();
|
||||||
|
|
||||||
assert_eq!(response.status(), Status::NotFound);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
assert_eq!(response.into_string().await, Some(expected));
|
assert_eq!(response.into_string(), Some(expected));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_name() {
|
fn test_name() {
|
||||||
// Check that the /hello/<name> route works.
|
// Check that the /hello/<name> route works.
|
||||||
dispatch!(Get, "/hello/Jack", |client, response| {
|
dispatch!(Get, "/hello/Jack", |client, response| {
|
||||||
let context = super::TemplateContext {
|
let context = super::TemplateContext {
|
||||||
|
@ -49,12 +49,12 @@ async fn test_name() {
|
||||||
|
|
||||||
let expected = Template::show(client.cargo(), "index", &context).unwrap();
|
let expected = Template::show(client.cargo(), "index", &context).unwrap();
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
assert_eq!(response.into_string().await, Some(expected));
|
assert_eq!(response.into_string(), Some(expected));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_404() {
|
fn test_404() {
|
||||||
// Check that the error catcher works.
|
// Check that the error catcher works.
|
||||||
dispatch!(Get, "/hello/", |client, response| {
|
dispatch!(Get, "/hello/", |client, response| {
|
||||||
let mut map = std::collections::HashMap::new();
|
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();
|
let expected = Template::show(client.cargo(), "error/404", &map).unwrap();
|
||||||
assert_eq!(response.status(), Status::NotFound);
|
assert_eq!(response.status(), Status::NotFound);
|
||||||
assert_eq!(response.into_string().await, Some(expected));
|
assert_eq!(response.into_string(), Some(expected));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,14 +15,25 @@ fn rocket() -> rocket::Rocket {
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use super::rocket;
|
use super::rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[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 client = Client::new(rocket()).await.unwrap();
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch().await;
|
||||||
assert_eq!(response.status(), Status::Ok);
|
assert_eq!(response.status(), Status::Ok);
|
||||||
assert_eq!(response.into_string().await, Some("Hello, world!".into()));
|
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()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn hello_world() {
|
fn hello_world() {
|
||||||
let client = Client::new(super::rocket()).await.unwrap();
|
let client = Client::new(super::rocket()).unwrap();
|
||||||
let response = client.get("/").dispatch().await;
|
let response = client.get("/").dispatch();
|
||||||
assert_eq!(response.into_string().await, Some("Hello, world!".into()));
|
assert_eq!(response.into_string(), Some("Hello, world!".into()));
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,7 +3,7 @@ use super::task::Task;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use rand::{Rng, thread_rng, distributions::Alphanumeric};
|
use rand::{Rng, thread_rng, distributions::Alphanumeric};
|
||||||
|
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::{Status, ContentType};
|
use rocket::http::{Status, ContentType};
|
||||||
|
|
||||||
// We use a lock to synchronize between tests so DB operations don't collide.
|
// 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) => ({
|
(|$client:ident, $conn:ident| $block:expr) => ({
|
||||||
let _lock = DB_LOCK.lock();
|
let _lock = DB_LOCK.lock();
|
||||||
|
|
||||||
rocket::async_test(async move {
|
let rocket = super::rocket();
|
||||||
let mut rocket = super::rocket();
|
let $client = Client::new(rocket).expect("Rocket client");
|
||||||
let db = super::DbConn::get_one(rocket.inspect().await);
|
let db = super::DbConn::get_one($client.cargo());
|
||||||
let $client = Client::new(rocket).await.expect("Rocket client");
|
|
||||||
let $conn = db.expect("failed to get database connection for testing");
|
let $conn = db.expect("failed to get database connection for testing");
|
||||||
Task::delete_all(&$conn).expect("failed to delete all tasks for testing");
|
Task::delete_all(&$conn).expect("failed to delete all tasks for testing");
|
||||||
|
|
||||||
$block
|
$block
|
||||||
})
|
})
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -37,7 +35,7 @@ fn test_insertion_deletion() {
|
||||||
client.post("/todo")
|
client.post("/todo")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body("description=My+first+task")
|
.body("description=My+first+task")
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
// Ensure we have one more task in the database.
|
// Ensure we have one more task in the database.
|
||||||
let new_tasks = Task::all(&conn).unwrap();
|
let new_tasks = Task::all(&conn).unwrap();
|
||||||
|
@ -49,7 +47,7 @@ fn test_insertion_deletion() {
|
||||||
|
|
||||||
// Issue a request to delete the task.
|
// Issue a request to delete the task.
|
||||||
let id = new_tasks[0].id.unwrap();
|
let id = new_tasks[0].id.unwrap();
|
||||||
client.delete(format!("/todo/{}", id)).dispatch().await;
|
client.delete(format!("/todo/{}", id)).dispatch();
|
||||||
|
|
||||||
// Ensure it's gone.
|
// Ensure it's gone.
|
||||||
let final_tasks = Task::all(&conn).unwrap();
|
let final_tasks = Task::all(&conn).unwrap();
|
||||||
|
@ -67,17 +65,17 @@ fn test_toggle() {
|
||||||
client.post("/todo")
|
client.post("/todo")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body("description=test_for_completion")
|
.body("description=test_for_completion")
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
let task = Task::all(&conn).unwrap()[0].clone();
|
let task = Task::all(&conn).unwrap()[0].clone();
|
||||||
assert_eq!(task.completed, false);
|
assert_eq!(task.completed, false);
|
||||||
|
|
||||||
// Issue a request to toggle the task; ensure it is completed.
|
// 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);
|
assert_eq!(Task::all(&conn).unwrap()[0].completed, true);
|
||||||
|
|
||||||
// Issue a request to toggle the task; ensure it's not completed again.
|
// 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);
|
assert_eq!(Task::all(&conn).unwrap()[0].completed, false);
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -97,7 +95,7 @@ fn test_many_insertions() {
|
||||||
client.post("/todo")
|
client.post("/todo")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body(format!("description={}", desc))
|
.body(format!("description={}", desc))
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
// Record the description we choose for this iteration.
|
// Record the description we choose for this iteration.
|
||||||
descs.insert(0, desc);
|
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.
|
// Submit an empty form. We should get a 422 but no flash error.
|
||||||
let res = client.post("/todo")
|
let res = client.post("/todo")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
let mut cookies = res.headers().get("Set-Cookie");
|
let mut cookies = res.headers().get("Set-Cookie");
|
||||||
assert_eq!(res.status(), Status::UnprocessableEntity);
|
assert_eq!(res.status(), Status::UnprocessableEntity);
|
||||||
|
@ -130,7 +128,7 @@ fn test_bad_form_submissions() {
|
||||||
let res = client.post("/todo")
|
let res = client.post("/todo")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body("description=")
|
.body("description=")
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
let mut cookies = res.headers().get("Set-Cookie");
|
let mut cookies = res.headers().get("Set-Cookie");
|
||||||
assert!(cookies.any(|value| value.contains("error")));
|
assert!(cookies.any(|value| value.contains("error")));
|
||||||
|
@ -139,7 +137,7 @@ fn test_bad_form_submissions() {
|
||||||
let res = client.post("/todo")
|
let res = client.post("/todo")
|
||||||
.header(ContentType::Form)
|
.header(ContentType::Form)
|
||||||
.body("evil=smile")
|
.body("evil=smile")
|
||||||
.dispatch().await;
|
.dispatch();
|
||||||
|
|
||||||
let mut cookies = res.headers().get("Set-Cookie");
|
let mut cookies = res.headers().get("Set-Cookie");
|
||||||
assert_eq!(res.status(), Status::UnprocessableEntity);
|
assert_eq!(res.status(), Status::UnprocessableEntity);
|
||||||
|
|
|
@ -1,25 +1,25 @@
|
||||||
use super::rocket;
|
use super::rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
async fn test(uri: &str, expected: &str) {
|
fn test(uri: &str, expected: &str) {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let res = client.get(uri).dispatch().await;
|
let res = client.get(uri).dispatch();
|
||||||
assert_eq!(res.into_string().await, Some(expected.into()));
|
assert_eq!(res.into_string(), Some(expected.into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn test_404(uri: &str) {
|
fn test_404(uri: &str) {
|
||||||
let client = Client::new(rocket()).await.unwrap();
|
let client = Client::new(rocket()).unwrap();
|
||||||
let res = client.get(uri).dispatch().await;
|
let res = client.get(uri).dispatch();
|
||||||
assert_eq!(res.status(), Status::NotFound);
|
assert_eq!(res.status(), Status::NotFound);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[rocket::async_test]
|
#[test]
|
||||||
async fn test_people() {
|
fn test_people() {
|
||||||
test("/people/7f205202-7ba1-4c39-b2fc-3e630722bf9f", "We found: Lacy").await;
|
test("/people/7f205202-7ba1-4c39-b2fc-3e630722bf9f", "We found: Lacy");
|
||||||
test("/people/4da34121-bc7d-4fc1-aee6-bf8de0795333", "We found: Bob").await;
|
test("/people/4da34121-bc7d-4fc1-aee6-bf8de0795333", "We found: Bob");
|
||||||
test("/people/ad962969-4e3d-4de7-ac4a-2d86d6d10839", "We found: George").await;
|
test("/people/ad962969-4e3d-4de7-ac4a-2d86d6d10839", "We found: George");
|
||||||
test("/people/e18b3a5c-488f-4159-a240-2101e0da19fd",
|
test("/people/e18b3a5c-488f-4159-a240-2101e0da19fd",
|
||||||
"Person not found for UUID: e18b3a5c-488f-4159-a240-2101e0da19fd").await;
|
"Person not found for UUID: e18b3a5c-488f-4159-a240-2101e0da19fd");
|
||||||
test_404("/people/invalid_uuid").await;
|
test_404("/people/invalid_uuid");
|
||||||
}
|
}
|
||||||
|
|
|
@ -103,7 +103,7 @@ use rocket::http::{ContentType, Status};
|
||||||
|
|
||||||
let rocket = rocket::ignite().mount("/", routes![hello]);
|
let rocket = rocket::ignite().mount("/", routes![hello]);
|
||||||
let client = Client::new(rocket).expect("valid rocket instance");
|
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.status(), Status::Ok);
|
||||||
assert_eq!(response.content_type(), Some(ContentType::Plain));
|
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)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use super::rocket;
|
use super::rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -167,12 +167,6 @@ You can also move the body of the `test` module into its own file, say
|
||||||
|
|
||||||
### Testing
|
### 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
|
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
|
`Rocket` instance. It's okay to use methods like `expect` and `unwrap` during
|
||||||
testing: we _want_ our tests to panic when something goes wrong.
|
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();
|
# let mut response = client.get("/").dispatch();
|
||||||
|
|
||||||
assert_eq!(response.status(), Status::Ok);
|
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:
|
That's it! Altogether, this looks like:
|
||||||
|
@ -240,7 +234,7 @@ fn rocket() -> rocket::Rocket {
|
||||||
# */
|
# */
|
||||||
mod test {
|
mod test {
|
||||||
use super::rocket;
|
use super::rocket;
|
||||||
use rocket::local::asynchronous::Client;
|
use rocket::local::blocking::Client;
|
||||||
use rocket::http::Status;
|
use rocket::http::Status;
|
||||||
|
|
||||||
# /*
|
# /*
|
||||||
|
@ -248,9 +242,9 @@ mod test {
|
||||||
# */ pub
|
# */ pub
|
||||||
fn hello_world() {
|
fn hello_world() {
|
||||||
let client = Client::new(rocket()).expect("valid rocket instance");
|
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.status(), Status::Ok);
|
||||||
assert_eq!(response.into_string().await, Some("Hello, world!".into()));
|
assert_eq!(response.into_string(), Some("Hello, world!".into()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue