add compat test

This commit is contained in:
Rob Ede 2022-02-08 07:11:16 +00:00
parent b530dc7010
commit 072205606f
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
2 changed files with 37 additions and 23 deletions

View File

@ -2,7 +2,7 @@
## Unreleased - 2021-xx-xx ## Unreleased - 2021-xx-xx
### Changed ### Changed
- `middleware::Condition` gained a broader compatiblity; It no longer requires `Compat`. [#2635] - `middleware::Condition` gained a broader compatibility; `Compat` is needed in fewer cases. [#2635]
### Added ### Added
- Implement `Responder` for `Vec<u8>`. [#2625] - Implement `Responder` for `Vec<u8>`. [#2625]

View File

@ -6,12 +6,14 @@ use std::{
task::{Context, Poll}, task::{Context, Poll},
}; };
use actix_service::{Service, Transform};
use futures_core::{future::LocalBoxFuture, ready}; use futures_core::{future::LocalBoxFuture, ready};
use futures_util::future::FutureExt as _; use futures_util::future::FutureExt as _;
use pin_project_lite::pin_project; use pin_project_lite::pin_project;
use crate::{body::EitherBody, dev::ServiceResponse}; use crate::{
body::EitherBody,
dev::{Service, ServiceResponse, Transform},
};
/// Middleware for conditionally enabling other middleware. /// Middleware for conditionally enabling other middleware.
/// ///
@ -89,10 +91,10 @@ where
fn call(&self, req: Req) -> Self::Future { fn call(&self, req: Req) -> Self::Future {
match self { match self {
ConditionMiddleware::Enable(service) => ConditionMiddlewareFuture::Left { ConditionMiddleware::Enable(service) => ConditionMiddlewareFuture::Enabled {
fut: service.call(req), fut: service.call(req),
}, },
ConditionMiddleware::Disable(service) => ConditionMiddlewareFuture::Right { ConditionMiddleware::Disable(service) => ConditionMiddlewareFuture::Disabled {
fut: service.call(req), fut: service.call(req),
}, },
} }
@ -100,25 +102,26 @@ where
} }
pin_project! { pin_project! {
#[project = EitherProj] #[doc(hidden)]
pub enum ConditionMiddlewareFuture<L, R> { #[project = ConditionProj]
Left { #[pin] fut: L, }, pub enum ConditionMiddlewareFuture<E, D> {
Right { #[pin] fut: R, }, Enabled { #[pin] fut: E, },
Disabled { #[pin] fut: D, },
} }
} }
impl<L, R, BL, BR, Err> Future for ConditionMiddlewareFuture<L, R> impl<E, D, BE, BD, Err> Future for ConditionMiddlewareFuture<E, D>
where where
L: Future<Output = Result<ServiceResponse<BL>, Err>>, E: Future<Output = Result<ServiceResponse<BE>, Err>>,
R: Future<Output = Result<ServiceResponse<BR>, Err>>, D: Future<Output = Result<ServiceResponse<BD>, Err>>,
{ {
type Output = Result<ServiceResponse<EitherBody<BL, BR>>, Err>; type Output = Result<ServiceResponse<EitherBody<BE, BD>>, Err>;
#[inline] #[inline]
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let res = match self.project() { let res = match self.project() {
EitherProj::Left { fut } => ready!(fut.poll(cx))?.map_into_left_body(), ConditionProj::Enabled { fut } => ready!(fut.poll(cx))?.map_into_left_body(),
EitherProj::Right { fut } => ready!(fut.poll(cx))?.map_into_right_body(), ConditionProj::Disabled { fut } => ready!(fut.poll(cx))?.map_into_right_body(),
}; };
Poll::Ready(Ok(res)) Poll::Ready(Ok(res))
@ -127,23 +130,23 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use actix_service::IntoService; use actix_service::IntoService as _;
use super::*; use super::*;
use crate::{ use crate::{
body::BoxBody,
dev::{ServiceRequest, ServiceResponse}, dev::{ServiceRequest, ServiceResponse},
error::Result, error::Result,
http::{ http::{
header::{HeaderValue, CONTENT_TYPE}, header::{HeaderValue, CONTENT_TYPE},
StatusCode, StatusCode,
}, },
middleware::err_handlers::*, middleware::{self, ErrorHandlerResponse, ErrorHandlers},
test::{self, TestRequest}, test::{self, TestRequest},
web::Bytes,
HttpResponse, HttpResponse,
}; };
fn assert_type<T>(_: &T) {}
#[allow(clippy::unnecessary_wraps)] #[allow(clippy::unnecessary_wraps)]
fn render_500<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { fn render_500<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
res.response_mut() res.response_mut()
@ -153,6 +156,17 @@ mod tests {
Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) Ok(ErrorHandlerResponse::Response(res.map_into_left_body()))
} }
#[test]
fn compat_with_builtin_middleware() {
let _ = Condition::new(true, middleware::Compat::noop());
let _ = Condition::new(true, middleware::Logger::default());
let _ = Condition::new(true, middleware::Compress::default());
let _ = Condition::new(true, middleware::NormalizePath::trim());
let _ = Condition::new(true, middleware::DefaultHeaders::new());
let _ = Condition::new(true, middleware::ErrorHandlers::<BoxBody>::new());
let _ = Condition::new(true, middleware::ErrorHandlers::<Bytes>::new());
}
#[actix_rt::test] #[actix_rt::test]
async fn test_handler_enabled() { async fn test_handler_enabled() {
let srv = |req: ServiceRequest| async move { let srv = |req: ServiceRequest| async move {
@ -167,8 +181,8 @@ mod tests {
.await .await
.unwrap(); .unwrap();
let resp = test::call_service(&mw, TestRequest::default().to_srv_request()).await; let resp: ServiceResponse<EitherBody<EitherBody<_, _>, String>> =
assert_type::<ServiceResponse<EitherBody<EitherBody<_, _>, String>>>(&resp); test::call_service(&mw, TestRequest::default().to_srv_request()).await;
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
} }
@ -186,8 +200,8 @@ mod tests {
.await .await
.unwrap(); .unwrap();
let resp = test::call_service(&mw, TestRequest::default().to_srv_request()).await; let resp: ServiceResponse<EitherBody<EitherBody<_, _>, String>> =
assert_type::<ServiceResponse<EitherBody<EitherBody<_, _>, String>>>(&resp); test::call_service(&mw, TestRequest::default().to_srv_request()).await;
assert_eq!(resp.headers().get(CONTENT_TYPE), None); assert_eq!(resp.headers().get(CONTENT_TYPE), None);
} }
} }