Rocket/core/codegen/tests/route-data.rs
Sergio Benitez 03127f4dae Add blocking variant of 'local'.
This commit adds the 'local::blocking' module and moves the existing
asynchronous testing to 'local::asynchronous'. It also includes several
changes to improve the local API, bringing it to parity (and beyond)
with master. These changes are:

  * 'LocalRequest' implements 'Clone'.
  * 'LocalResponse' doesn't implement 'DerefMut<Target=Response>'.
    Instead, direct methods on the type, such as 'into_string()', can
    be used to read the 'Response'.
  * 'Response::body()' returns an '&ResponseBody' as opposed to '&mut
    ResponseBody', which is returned by a new 'Response::body_mut()'.
  * '&ResponseBody' implements 'known_size()` to retrieve a body's size,
    if it is known.

Co-authored-by: Jeb Rosen <jeb@jebrosen.com>
2020-07-11 09:24:30 -07:00

62 lines
1.8 KiB
Rust

#![feature(proc_macro_hygiene)]
#[macro_use] extern crate rocket;
use rocket::{Request, Data, Outcome::*};
use rocket::local::asynchronous::Client;
use rocket::request::Form;
use rocket::data::{self, FromDataSimple};
use rocket::http::{RawStr, ContentType, Status};
// Test that the data parameters works as expected.
#[derive(FromForm)]
struct Inner<'r> {
field: &'r RawStr
}
struct Simple(String);
impl FromDataSimple for Simple {
type Error = ();
fn from_data(_: &Request<'_>, data: Data) -> data::FromDataFuture<'static, Self, ()> {
Box::pin(async {
use tokio::io::AsyncReadExt;
let mut string = String::new();
let mut stream = data.open().take(64);
if let Err(_) = stream.read_to_string(&mut string).await {
return Failure((Status::InternalServerError, ()));
}
Success(Simple(string))
})
}
}
#[post("/f", data = "<form>")]
fn form(form: Form<Inner<'_>>) -> String { form.field.url_decode_lossy() }
#[post("/s", data = "<simple>")]
fn simple(simple: Simple) -> String { simple.0 }
#[rocket::async_test]
async fn test_data() {
let rocket = rocket::ignite().mount("/", routes![form, simple]);
let client = Client::new(rocket).await.unwrap();
let response = client.post("/f")
.header(ContentType::Form)
.body("field=this%20is%20here")
.dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "this is here");
let response = client.post("/s").body("this is here").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "this is here");
let response = client.post("/s").body("this%20is%20here").dispatch().await;
assert_eq!(response.into_string().await.unwrap(), "this%20is%20here");
}