Add test for middleware that return early (#409)

* Add test for middleware that return early

Turns out #408 fixed #380.

* changelog
This commit is contained in:
David Pedersen 2021-10-25 21:46:49 +02:00 committed by GitHub
parent 85f5511313
commit baf7cabfe1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 64 additions and 2 deletions

View file

@ -123,6 +123,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Use `Router::fallback` for adding fallback routes ([#408])
- **added:** `Router::fallback` for adding handlers for request that didn't
match any routes ([#408])
- **fixed:** Middleware that return early (such as `tower_http::auth::RequireAuthorization`)
now no longer catch requests that would otherwise be 404s. They also work
correctly with `Router::merge` (previously called `or`) ([#408])
[#339]: https://github.com/tokio-rs/axum/pull/339
[#286]: https://github.com/tokio-rs/axum/pull/286

View file

@ -373,3 +373,33 @@ async fn nesting_and_seeing_the_right_uri_ors_with_multi_segment_uris() {
})
);
}
#[tokio::test]
async fn middleware_that_return_early() {
let private = Router::new()
.route("/", get(|| async {}))
.layer(RequireAuthorizationLayer::bearer("password"));
let public = Router::new().route("/public", get(|| async {}));
let client = TestClient::new(private.merge(public));
assert_eq!(
client.get("/").send().await.status(),
StatusCode::UNAUTHORIZED
);
assert_eq!(
client
.get("/")
.header("authorization", "Bearer password")
.send()
.await
.status(),
StatusCode::OK
);
assert_eq!(
client.get("/doesnt-exist").send().await.status(),
StatusCode::NOT_FOUND
);
assert_eq!(client.get("/public").send().await.status(), StatusCode::OK);
}

View file

@ -25,8 +25,8 @@ use std::{
task::{Context, Poll},
time::Duration,
};
use tower::timeout::TimeoutLayer;
use tower::{service_fn, ServiceBuilder};
use tower::{service_fn, timeout::TimeoutLayer, ServiceBuilder};
use tower_http::auth::RequireAuthorizationLayer;
use tower_service::Service;
pub(crate) use helpers::*;
@ -550,6 +550,35 @@ async fn middleware_applies_to_routes_above() {
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test]
async fn middleware_that_return_early() {
let app = Router::new()
.route("/", get(|| async {}))
.layer(RequireAuthorizationLayer::bearer("password"))
.route("/public", get(|| async {}));
let client = TestClient::new(app);
assert_eq!(
client.get("/").send().await.status(),
StatusCode::UNAUTHORIZED
);
assert_eq!(
client
.get("/")
.header("authorization", "Bearer password")
.send()
.await
.status(),
StatusCode::OK
);
assert_eq!(
client.get("/doesnt-exist").send().await.status(),
StatusCode::NOT_FOUND
);
assert_eq!(client.get("/public").send().await.status(), StatusCode::OK);
}
pub(crate) fn assert_send<T: Send>() {}
pub(crate) fn assert_sync<T: Sync>() {}
pub(crate) fn assert_unpin<T: Unpin>() {}