-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feature: learn how to test middleware
- Loading branch information
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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(()) | ||
} | ||
} |