Rocket - Multi-counter using cookies (in the client)



examples/rocket/multi-counter-using-cookies/src/main.rs
#[macro_use]
extern crate rocket;

use rocket::http::CookieJar;

#[get("/")]
fn index(cookies: &CookieJar<'_>) -> String {
    let counter: u32 = match cookies.get("counter") {
        Some(cookie) => match cookie.value().parse() {
            Ok(val) => val,
            Err(_) => {
                eprintln!(
                    "Invalid value '{}' for the 'counter' cookie.",
                    cookie.value()
                );
                0
            }
        },
        None => 0,
    };
    let counter = counter + 1;
    cookies.add(("counter", counter.to_string()));

    format!("Counter: {}", counter)
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index])
}

#[cfg(test)]
mod tests;

examples/rocket/multi-counter-using-cookies/src/tests.rs
use rocket::http::Status;
use rocket::local::blocking::Client;

#[test]
fn test_without_cookie() {
    let client = Client::tracked(super::rocket()).unwrap();
    let response = client.get("/").dispatch();

    assert_eq!(response.status(), Status::Ok);
    assert_eq!(
        response.headers().get_one("set-cookie").unwrap(),
        "counter=1; SameSite=Strict; Path=/"
    );

    assert_eq!(response.into_string(), Some("Counter: 1".into()));
}

#[test]
fn test_with_cookie() {
    let client = Client::tracked(super::rocket()).unwrap();
    let response = client.get("/").cookie(("counter", "41")).dispatch();

    assert_eq!(response.status(), Status::Ok);
    assert_eq!(
        response.headers().get_one("set-cookie").unwrap(),
        "counter=42; SameSite=Strict; Path=/"
    );

    assert_eq!(response.into_string(), Some("Counter: 42".into()));
}

#[test]
fn test_with_bad_cookie() {
    let client = Client::tracked(super::rocket()).unwrap();
    let response = client.get("/").cookie(("counter", "bla")).dispatch();

    assert_eq!(response.status(), Status::Ok);
    assert_eq!(
        response.headers().get_one("set-cookie").unwrap(),
        "counter=1; SameSite=Strict; Path=/"
    );

    assert_eq!(response.into_string(), Some("Counter: 1".into()));
}