Skip to content

Commit

Permalink
Fix tests now that tower-http handles Content-Length
Browse files Browse the repository at this point in the history
  • Loading branch information
davidpdrsn committed Jun 8, 2022
1 parent 58f9e06 commit 3c3f1ce
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 5 deletions.
47 changes: 42 additions & 5 deletions axum/src/routing/tests/mod.rs
Expand Up @@ -8,7 +8,7 @@ use crate::{
test_helpers::*,
BoxError, Json, Router,
};
use http::{Method, Request, Response, StatusCode, Uri};
use http::{header::CONTENT_LENGTH, HeaderMap, Method, Request, Response, StatusCode, Uri};
use hyper::Body;
use serde::Deserialize;
use serde_json::{json, Value};
Expand All @@ -20,7 +20,7 @@ use std::{
time::Duration,
};
use tower::{service_fn, timeout::TimeoutLayer, ServiceBuilder, ServiceExt};
use tower_http::auth::RequireAuthorizationLayer;
use tower_http::{auth::RequireAuthorizationLayer, limit::RequestBodyLimitLayer};
use tower_service::Service;

mod fallback;
Expand Down Expand Up @@ -701,12 +701,17 @@ async fn routes_must_start_with_slash() {
}

#[tokio::test]
async fn limited_body() {
async fn limited_body_with_content_length() {
const LIMIT: usize = 3;

let app = Router::new()
.route("/", post(|_: Bytes| async {}))
.layer(tower_http::limit::RequestBodyLimitLayer::new(LIMIT));
.route(
"/",
post(|headers: HeaderMap, _body: Bytes| async move {
assert!(headers.get(CONTENT_LENGTH).is_some());
}),
)
.layer(RequestBodyLimitLayer::new(LIMIT));

let client = TestClient::new(app);

Expand All @@ -716,3 +721,35 @@ async fn limited_body() {
let res = client.post("/").body("a".repeat(LIMIT * 2)).send().await;
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
}

#[tokio::test]
async fn limited_body_with_streaming_body() {
const LIMIT: usize = 3;

let app = Router::new()
.route(
"/",
post(|headers: HeaderMap, _body: Bytes| async move {
assert!(headers.get(CONTENT_LENGTH).is_none());
}),
)
.layer(RequestBodyLimitLayer::new(LIMIT));

let client = TestClient::new(app);

let stream = futures_util::stream::iter(vec![Ok::<_, hyper::Error>("a".repeat(LIMIT))]);
let res = client
.post("/")
.body(Body::wrap_stream(stream))
.send()
.await;
assert_eq!(res.status(), StatusCode::OK);

let stream = futures_util::stream::iter(vec![Ok::<_, hyper::Error>("a".repeat(LIMIT * 2))]);
let res = client
.post("/")
.body(Body::wrap_stream(stream))
.send()
.await;
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
}
1 change: 1 addition & 0 deletions axum/src/test_helpers/test_client.rs
Expand Up @@ -118,6 +118,7 @@ impl RequestBuilder {
}
}

#[derive(Debug)]
pub(crate) struct TestResponse {
response: reqwest::Response,
}
Expand Down

0 comments on commit 3c3f1ce

Please sign in to comment.