From 60a386b270c864a9db47b8b281352e0d12f07be8 Mon Sep 17 00:00:00 2001 From: Markus Kohlhase Date: Tue, 13 Jun 2017 17:40:04 +0200 Subject: [PATCH] add login and logout tests to session example --- examples/session/src/main.rs | 3 ++ examples/session/src/tests.rs | 87 +++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 examples/session/src/tests.rs diff --git a/examples/session/src/main.rs b/examples/session/src/main.rs index 454119a8..9df39b87 100644 --- a/examples/session/src/main.rs +++ b/examples/session/src/main.rs @@ -4,6 +4,9 @@ extern crate rocket_contrib; extern crate rocket; +#[cfg(test)] +mod tests; + use std::collections::HashMap; use rocket::Outcome; diff --git a/examples/session/src/tests.rs b/examples/session/src/tests.rs new file mode 100644 index 00000000..e4209001 --- /dev/null +++ b/examples/session/src/tests.rs @@ -0,0 +1,87 @@ +use rocket::local::Client; +use rocket::http::*; + +fn setup() -> Client { + use super::*; + let server = rocket::ignite().mount("/", routes![ + index, + user_index, + login, + logout, + login_user, + login_page]); + Client::new(server).unwrap() +} + +#[test] +fn test_login() { + let client = setup(); + let response = client + .post("/login") + .header(ContentType::Form) + .body("username=Sergio&password=password") + .dispatch(); + let cookie: Cookie = response + .headers() + .iter() + .filter(|h| h.name == "Set-Cookie") + .filter(|h| h.value.contains("user_id")) + .map(|h| h.value) + .nth(0) + .unwrap() + .parse() + .unwrap(); + + assert_eq!(response.status(), Status::SeeOther); + assert_eq!(cookie.name(), "user_id"); + assert_eq!(cookie.path().unwrap(), "/"); + assert!(cookie.value().len() > 25); + assert!(cookie.http_only()); + assert_eq!(cookie.same_site().unwrap().to_string(), "Strict"); +} + +#[test] +fn test_logout() { + let client = setup(); + + let response = client + .post("/login") + .header(ContentType::Form) + .body("username=Sergio&password=password") + .dispatch(); + + let user_id: String = response + .headers() + .iter() + .filter(|h| h.name == "Set-Cookie") + .filter(|h| h.value.contains("user_id")) + .map(|h| h.value) + .nth(0) + .unwrap() + .parse::() + .unwrap() + .value() + .into(); + + let response = client + .post("/logout") + .header(ContentType::Form) + .cookie(Cookie::new("user_id", user_id)) + .dispatch(); + + let cookie: Cookie = response + .headers() + .iter() + .filter(|h| h.name == "Set-Cookie") + .filter(|h| h.value.contains("user_id")) + .map(|h| h.value) + .nth(0) + .unwrap() + .parse() + .unwrap(); + + assert_eq!(response.status(), Status::SeeOther); + assert_eq!(cookie.name(), "user_id"); + assert_eq!(cookie.value(), ""); + assert_eq!(cookie.max_age().unwrap().num_seconds(), 0); +}