Rocket/lib/tests/strict_and_lenient_forms.rs
Sergio Benitez a3ea9d0f9a Add support for lenient forms via 'LenientForm'.
This commit changes the 'FromForm' trait in two ways:

  1. The singular method is now named 'from_form'.
  2. The method takes a second parameter: 'strict: bool'.

The 'strict' parameter is used to specify whether form parsing should
be strict or not (i.e. lenient). When parsing is lenient, extra form
fields do not result in an error. This lenient behavior is used by a
new 'LenientForm' data guard type to request lenient form parsing. The
behavior for 'Form' remains unchanged.

Resolves #242.
2017-06-18 01:59:22 -07:00

74 lines
2.0 KiB
Rust

#![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
use rocket::request::{Form, LenientForm};
use rocket::http::RawStr;
#[derive(FromForm)]
struct MyForm<'r> {
field: &'r RawStr,
}
#[post("/strict", data = "<form>")]
fn strict<'r>(form: Form<'r, MyForm<'r>>) -> String {
form.get().field.as_str().into()
}
#[post("/lenient", data = "<form>")]
fn lenient<'r>(form: LenientForm<'r, MyForm<'r>>) -> String {
form.get().field.as_str().into()
}
mod strict_and_lenient_forms_tests {
use super::*;
use rocket::local::Client;
use rocket::http::{Status, ContentType};
const FIELD_VALUE: &str = "just_some_value";
fn client() -> Client {
Client::new(rocket::ignite().mount("/", routes![strict, lenient])).unwrap()
}
#[test]
fn test_strict_form() {
let client = client();
let mut response = client.post("/strict")
.header(ContentType::Form)
.body(format!("field={}", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
let response = client.post("/strict")
.header(ContentType::Form)
.body(format!("field={}&extra=whoops", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::UnprocessableEntity);
}
#[test]
fn test_lenient_form() {
let client = client();
let mut response = client.post("/lenient")
.header(ContentType::Form)
.body(format!("field={}", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
let mut response = client.post("/lenient")
.header(ContentType::Form)
.body(format!("field={}&extra=whoops", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
}
}