#How can I test a route using a session cookie?

1 messages · Page 1 of 1 (latest)

eternal wharf
#

Hello, I am very new to Rust and Actix. Sorry if this is obvious.

I have a route that increments a counter every time a user accesses it:

#[get("/session")]
async fn session(session: Session) -> impl Responder {
    let counter = match session.get::<i32>("counter") {
        Ok(counter) => match counter {
            Some(counter) => counter + 1,
            _ => 1,
        },
        _ => 1,
    };

    match session.insert("counter", counter) {
        _ => format!("You have visited {} times", counter),
    }
}

and I have a test associated with it:

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::{test, App};

    #[actix_web::test]
    async fn test_get_session() {
        let app = test::init_service(App::new().service(session)).await;

        let req = test::TestRequest::get().uri("/session").to_request();
        let resp = test::call_and_read_body(&app, req).await;
        assert_eq!(resp, "You have visited 1 times");
    }
}

My problem is that this only tests the trivial case (when the user doesn't have a session cookie). How can I create a TestRequest that has a session cookie associated with it?

eternal wharf
#

Here is my full main.rs for reference:

use actix_session::Session;
use actix_session::{storage::CookieSessionStore, SessionMiddleware};
use actix_web::{get, Responder};
use actix_web::{App, HttpServer};

#[get("/session")]
async fn session(session: Session) -> impl Responder {
    let counter = match session.get::<i32>("counter") {
        Ok(counter) => match counter {
            Some(counter) => counter + 1,
            _ => 1,
        },
        _ => 1,
    };

    match session.insert("counter", counter) {
        _ => format!("You have visited {} times", counter),
    }
}

static SESSION_SIGNING_KEY: &[u8] = &[0; 64]; // Just an example

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let key = actix_web::cookie::Key::from(SESSION_SIGNING_KEY);

    let host = "0.0.0.0";
    let port = 8080;
    HttpServer::new(move || {
        App::new()
            .wrap(
                SessionMiddleware::builder(CookieSessionStore::default(), key.clone())
                    .cookie_secure(false)
                    .build(),
            )
            .service(session)
    })
    .bind((host, port))?
    .run()
    .await
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::{test, App};

    #[actix_web::test]
    async fn test_get_session() {
        let app = test::init_service(App::new().service(session)).await;

        let req = test::TestRequest::get().uri("/session").to_request();
        let resp = test::call_and_read_body(&app, req).await;
        assert_eq!(resp, "You have visited 1 times");
    }
}
torpid plover