1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-30 10:32:55 +01:00

add test for middleware usage in app and scope (#215)

This commit is contained in:
simon-an 2022-03-01 05:18:46 +01:00 committed by GitHub
parent fd272f817c
commit ce92f0036f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -240,10 +240,13 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::extractors::basic::BasicAuth;
use crate::extractors::bearer::BearerAuth; use crate::extractors::bearer::BearerAuth;
use actix_service::{into_service, Service}; use actix_service::{into_service, Service};
use actix_web::error::ErrorForbidden;
use actix_web::http::StatusCode;
use actix_web::test::TestRequest; use actix_web::test::TestRequest;
use actix_web::{error, HttpResponse}; use actix_web::{error, web, App, HttpResponse};
/// This is a test for https://github.com/actix/actix-extras/issues/10 /// This is a test for https://github.com/actix/actix-extras/issues/10
#[actix_web::test] #[actix_web::test]
@ -354,4 +357,56 @@ mod tests {
assert!(f.is_ok()); assert!(f.is_ok());
} }
#[actix_rt::test]
async fn test_middleware_works_with_app() {
async fn validator(
_req: ServiceRequest,
_credentials: BasicAuth,
) -> Result<ServiceRequest, actix_web::Error> {
Err(ErrorForbidden("You are not welcome!"))
}
let middleware = HttpAuthentication::basic(validator);
let srv = actix_web::test::init_service(
App::new()
.wrap(middleware)
.route("/", web::get().to(|| web::HttpResponse::Ok())),
)
.await;
let req = actix_web::test::TestRequest::with_uri("/")
.append_header(("Authorization", "Basic DontCare"))
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[actix_rt::test]
async fn test_middleware_works_with_scope() {
async fn validator(
_req: ServiceRequest,
_credentials: BasicAuth,
) -> Result<ServiceRequest, actix_web::Error> {
Err(ErrorForbidden("You are not welcome!"))
}
let middleware = actix_web::middleware::Compat::new(HttpAuthentication::basic(validator));
let srv = actix_web::test::init_service(
App::new().service(
web::scope("/")
.wrap(middleware)
.route("/", web::get().to(|| web::HttpResponse::Ok())),
),
)
.await;
let req = actix_web::test::TestRequest::with_uri("/")
.append_header(("Authorization", "Basic DontCare"))
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
} }