Skip to content

Commit

Permalink
feature: learn how to test middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
tyrchen committed Apr 29, 2024
1 parent 3e50a99 commit a87eab4
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions chat_server/src/middlewares/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,54 @@ pub async fn verify_token(State(state): State<AppState>, req: Request, next: Nex

next.run(req).await
}

#[cfg(test)]
mod tests {
use crate::{AppConfig, User};

use super::*;
use anyhow::Result;
use axum::{body::Body, middleware::from_fn_with_state, routing::get, Router};
use tower::ServiceExt;

async fn handler(_req: Request) -> impl IntoResponse {
(StatusCode::OK, "ok")
}

#[tokio::test]
async fn verify_token_middleware_should_work() -> Result<()> {
let config = AppConfig::load()?;
let (_tdb, state) = AppState::new_for_test(config).await?;

let user = User::new(1, "Tyr Chen", "[email protected]");
let token = state.ek.sign(user)?;

let app = Router::new()
.route("/", get(handler))
.layer(from_fn_with_state(state.clone(), verify_token))
.with_state(state);

// good token
let req = Request::builder()
.uri("/")
.header("Authorization", format!("Bearer {}", token))
.body(Body::empty())?;
let res = app.clone().oneshot(req).await?;
assert_eq!(res.status(), StatusCode::OK);

// no token
let req = Request::builder().uri("/").body(Body::empty())?;
let res = app.clone().oneshot(req).await?;
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);

// bad token
let req = Request::builder()
.uri("/")
.header("Authorization", "Bearer bad-token")
.body(Body::empty())?;
let res = app.oneshot(req).await?;
assert_eq!(res.status(), StatusCode::FORBIDDEN);

Ok(())
}
}

0 comments on commit a87eab4

Please sign in to comment.