Rocket/core/lib/tests/catcher-cookies-1213.rs
Sergio Benitez 52320020bc Use thread-safe 'CookieJar's.
The user-facing changes effected by this commit are:

  * The 'http::Cookies<'_>' guard is now '&http::CookieJar<'_>'.
  * The "one-at-a-time" jar restriction is no longer imposed.
  * 'CookieJar' retrieval methods return 'http::CookieCrumb'.
  * The 'private-cookies' feature is now called 'secrets'.
  * Docs flag private cookie methods with feature cfg.
  * Local, async request dispatching is never serialized.
  * 'Client::cookies()' returns the tracked 'CookieJar'.
  * 'LocalResponse::cookies()' returns a 'CookieJar'.
  * 'Response::cookies()' returns an 'impl Iterator'.
  * A path of '/' is set by default on all cookies.
  * 'SameSite=strict' is set by default on all cookies.
  * 'LocalRequest::cookies()' accepts any 'Cookie' iterator.
  * The 'Debug' impl for 'Request' prints the cookie jar.

Resolves #1332.
2020-08-16 02:19:45 -07:00

48 lines
1.5 KiB
Rust

#[macro_use] extern crate rocket;
use rocket::request::Request;
use rocket::http::{Cookie, CookieJar};
#[catch(404)]
fn not_found(request: &Request) -> &'static str {
request.cookies().add(Cookie::new("not_found", "404"));
"404 - Not Found"
}
#[get("/")]
fn index(cookies: &CookieJar<'_>) -> &'static str {
cookies.add(Cookie::new("index", "hi"));
"Hello, world!"
}
mod tests {
use super::*;
use rocket::local::blocking::Client;
use rocket::fairing::AdHoc;
#[test]
fn error_catcher_sets_cookies() {
let rocket = rocket::ignite()
.mount("/", routes![index])
.register(catchers![not_found])
.attach(AdHoc::on_request("Add Fairing Cookie", |req, _| Box::pin(async move {
req.cookies().add(Cookie::new("fairing", "woo"));
})));
let client = Client::new(rocket).unwrap();
// Check that the index returns the `index` and `fairing` cookie.
let response = client.get("/").dispatch();
let cookies = response.cookies();
assert_eq!(cookies.iter().count(), 2);
assert_eq!(cookies.get("index").unwrap().value(), "hi");
assert_eq!(cookies.get("fairing").unwrap().value(), "woo");
// Check that the catcher returns only the `not_found` cookie.
let response = client.get("/not-existent").dispatch();
let cookies = response.cookies();
assert_eq!(cookies.iter().count(), 1);
assert_eq!(cookies.get("not_found").unwrap().value(), "404");
}
}