1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-01 16:55:08 +02:00

response header rework (#1869)

This commit is contained in:
Rob Ede
2021-01-15 02:11:10 +00:00
committed by GitHub
parent 4edeb5ce47
commit b1dd8d28bc
76 changed files with 1568 additions and 1347 deletions

View File

@ -347,25 +347,21 @@ mod tests {
#[actix_rt::test]
async fn test_option() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.data(FormConfig::default().limit(4096))
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
.data(FormConfig::default().limit(4096))
.to_http_parts();
let r = Option::<Form<Info>>::from_request(&req, &mut pl)
.await
.unwrap();
assert_eq!(r, None);
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header(header::CONTENT_LENGTH, "9")
.set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((header::CONTENT_LENGTH, "9"))
.set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts();
let r = Option::<Form<Info>>::from_request(&req, &mut pl)
.await
@ -377,13 +373,11 @@ mod tests {
}))
);
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header(header::CONTENT_LENGTH, "9")
.set_payload(Bytes::from_static(b"bye=world"))
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((header::CONTENT_LENGTH, "9"))
.set_payload(Bytes::from_static(b"bye=world"))
.to_http_parts();
let r = Option::<Form<Info>>::from_request(&req, &mut pl)
.await
@ -393,13 +387,11 @@ mod tests {
#[actix_rt::test]
async fn test_result() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header(header::CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((header::CONTENT_LENGTH, "11"))
.set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts();
let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl)
.await
@ -412,13 +404,11 @@ mod tests {
})
);
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header(header::CONTENT_LENGTH, "9")
.set_payload(Bytes::from_static(b"bye=world"))
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((header::CONTENT_LENGTH, 9))
.set_payload(Bytes::from_static(b"bye=world"))
.to_http_parts();
let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl)
.await

View File

@ -330,7 +330,8 @@ mod tests {
#[test]
fn test_header() {
let req = TestRequest::with_header(header::TRANSFER_ENCODING, "chunked")
let req = TestRequest::default()
.insert_header((header::TRANSFER_ENCODING, "chunked"))
.to_http_request();
let pred = Header("transfer-encoding", "chunked");
@ -346,10 +347,10 @@ mod tests {
#[test]
fn test_host() {
let req = TestRequest::default()
.header(
.insert_header((
header::HOST,
header::HeaderValue::from_static("www.rust-lang.org"),
)
))
.to_http_request();
let pred = Host("www.rust-lang.org");
@ -374,10 +375,10 @@ mod tests {
#[test]
fn test_host_scheme() {
let req = TestRequest::default()
.header(
.insert_header((
header::HOST,
header::HeaderValue::from_static("https://www.rust-lang.org"),
)
))
.to_http_request();
let pred = Host("www.rust-lang.org").scheme("https");

View File

@ -200,10 +200,10 @@ mod tests {
assert_eq!(info.host(), "localhost:8080");
let req = TestRequest::default()
.header(
.insert_header((
header::FORWARDED,
"for=192.0.2.60; proto=https; by=203.0.113.43; host=rust-lang.org",
)
))
.to_http_request();
let info = req.connection_info();
@ -212,7 +212,7 @@ mod tests {
assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
let req = TestRequest::default()
.header(header::HOST, "rust-lang.org")
.insert_header((header::HOST, "rust-lang.org"))
.to_http_request();
let info = req.connection_info();
@ -221,20 +221,20 @@ mod tests {
assert_eq!(info.realip_remote_addr(), None);
let req = TestRequest::default()
.header(X_FORWARDED_FOR, "192.0.2.60")
.insert_header((X_FORWARDED_FOR, "192.0.2.60"))
.to_http_request();
let info = req.connection_info();
assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
let req = TestRequest::default()
.header(X_FORWARDED_HOST, "192.0.2.60")
.insert_header((X_FORWARDED_HOST, "192.0.2.60"))
.to_http_request();
let info = req.connection_info();
assert_eq!(info.host(), "192.0.2.60");
assert_eq!(info.realip_remote_addr(), None);
let req = TestRequest::default()
.header(X_FORWARDED_PROTO, "https")
.insert_header((X_FORWARDED_PROTO, "https"))
.to_http_request();
let info = req.connection_info();
assert_eq!(info.scheme(), "https");

View File

@ -211,7 +211,7 @@ pub mod client {
//!
//! // Create request builder and send request
//! let response = client.get("http://www.rust-lang.org")
//! .header("User-Agent", "actix-web/3.0")
//! .insert_header(("User-Agent", "actix-web/3.0"))
//! .send() // <- Send request
//! .await; // <- Wait for response
//!

View File

@ -212,8 +212,11 @@ mod tests {
let req = TestRequest::default().to_srv_request();
let srv = |req: ServiceRequest| {
ok(req
.into_response(HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish()))
ok(req.into_response(
HttpResponse::Ok()
.insert_header((CONTENT_TYPE, "0002"))
.finish(),
))
};
let mut mw = DefaultHeaders::new()
.header(CONTENT_TYPE, "0001")

View File

@ -603,7 +603,7 @@ mod tests {
let srv = |req: ServiceRequest| {
ok(req.into_response(
HttpResponse::build(StatusCode::OK)
.header("X-Test", "ttt")
.insert_header(("X-Test", "ttt"))
.finish(),
))
};
@ -611,11 +611,12 @@ mod tests {
let mut srv = logger.new_transform(srv.into_service()).await.unwrap();
let req = TestRequest::with_header(
header::USER_AGENT,
header::HeaderValue::from_static("ACTIX-WEB"),
)
.to_srv_request();
let req = TestRequest::default()
.insert_header((
header::USER_AGENT,
header::HeaderValue::from_static("ACTIX-WEB"),
))
.to_srv_request();
let _res = srv.call(req).await;
}
@ -624,7 +625,7 @@ mod tests {
let srv = |req: ServiceRequest| {
ok(req.into_response(
HttpResponse::build(StatusCode::OK)
.header("X-Test", "ttt")
.insert_header(("X-Test", "ttt"))
.finish(),
))
};
@ -633,23 +634,25 @@ mod tests {
let mut srv = logger.new_transform(srv.into_service()).await.unwrap();
let req = TestRequest::with_header(
header::USER_AGENT,
header::HeaderValue::from_static("ACTIX-WEB"),
)
.to_srv_request();
let req = TestRequest::default()
.insert_header((
header::USER_AGENT,
header::HeaderValue::from_static("ACTIX-WEB"),
))
.to_srv_request();
let _res = srv.call(req).await.unwrap();
}
#[actix_rt::test]
async fn test_url_path() {
let mut format = Format::new("%T %U");
let req = TestRequest::with_header(
header::USER_AGENT,
header::HeaderValue::from_static("ACTIX-WEB"),
)
.uri("/test/route/yeah")
.to_srv_request();
let req = TestRequest::default()
.insert_header((
header::USER_AGENT,
header::HeaderValue::from_static("ACTIX-WEB"),
))
.uri("/test/route/yeah")
.to_srv_request();
let now = OffsetDateTime::now_utc();
for unit in &mut format.0 {
@ -676,12 +679,13 @@ mod tests {
async fn test_default_format() {
let mut format = Format::default();
let req = TestRequest::with_header(
header::USER_AGENT,
header::HeaderValue::from_static("ACTIX-WEB"),
)
.peer_addr("127.0.0.1:8081".parse().unwrap())
.to_srv_request();
let req = TestRequest::default()
.insert_header((
header::USER_AGENT,
header::HeaderValue::from_static("ACTIX-WEB"),
))
.peer_addr("127.0.0.1:8081".parse().unwrap())
.to_srv_request();
let now = OffsetDateTime::now_utc();
for unit in &mut format.0 {
@ -736,13 +740,14 @@ mod tests {
async fn test_remote_addr_format() {
let mut format = Format::new("%{r}a");
let req = TestRequest::with_header(
header::FORWARDED,
header::HeaderValue::from_static(
"for=192.0.2.60;proto=http;by=203.0.113.43",
),
)
.to_srv_request();
let req = TestRequest::default()
.insert_header((
header::FORWARDED,
header::HeaderValue::from_static(
"for=192.0.2.60;proto=http;by=203.0.113.43",
),
))
.to_srv_request();
let now = OffsetDateTime::now_utc();
for unit in &mut format.0 {

View File

@ -423,8 +423,9 @@ mod tests {
#[test]
fn test_debug() {
let req =
TestRequest::with_header("content-type", "text/plain").to_http_request();
let req = TestRequest::default()
.insert_header(("content-type", "text/plain"))
.to_http_request();
let dbg = format!("{:?}", req);
assert!(dbg.contains("HttpRequest"));
}
@ -438,8 +439,8 @@ mod tests {
#[test]
fn test_request_cookies() {
let req = TestRequest::default()
.header(header::COOKIE, "cookie1=value1")
.header(header::COOKIE, "cookie2=value2")
.append_header((header::COOKIE, "cookie1=value1"))
.append_header((header::COOKIE, "cookie2=value2"))
.to_http_request();
{
let cookies = req.cookies().unwrap();
@ -476,7 +477,8 @@ mod tests {
assert!(rmap.has_resource("/user/test.html"));
assert!(!rmap.has_resource("/test/unknown"));
let req = TestRequest::with_header(header::HOST, "www.rust-lang.org")
let req = TestRequest::default()
.insert_header((header::HOST, "www.rust-lang.org"))
.rmap(rmap)
.to_http_request();
@ -506,7 +508,7 @@ mod tests {
assert!(rmap.has_resource("/index.html"));
let req = TestRequest::with_uri("/test")
.header(header::HOST, "www.rust-lang.org")
.insert_header((header::HOST, "www.rust-lang.org"))
.rmap(rmap)
.to_http_request();
let url = req.url_for_static("index");
@ -557,7 +559,7 @@ mod tests {
let mut srv = init_service(App::new().service(web::resource("/").to(
|req: HttpRequest| {
HttpResponse::Ok()
.set_header("pool_cap", req.app_state().pool().cap)
.insert_header(("pool_cap", req.app_state().pool().cap))
.finish()
},
)))

View File

@ -1,17 +1,17 @@
use std::convert::TryFrom;
use std::fmt;
use actix_http::error::InternalError;
use actix_http::http::{
header::IntoHeaderValue, Error as HttpError, HeaderMap, HeaderName, StatusCode,
use actix_http::{
error::InternalError,
http::{header::IntoHeaderPair, Error as HttpError, HeaderMap, StatusCode},
ResponseBuilder,
};
use actix_http::ResponseBuilder;
use bytes::{Bytes, BytesMut};
use crate::{Error, HttpRequest, HttpResponse};
/// Trait implemented by types that can be converted to a http response.
/// Trait implemented by types that can be converted to an HTTP response.
///
/// Types that implement this trait can be used as the return type of a handler.
/// Any types that implement this trait can be used in the return type of a handler.
pub trait Responder {
/// Convert self to `HttpResponse`.
fn respond_to(self, req: &HttpRequest) -> HttpResponse;
@ -19,12 +19,11 @@ pub trait Responder {
/// Override a status code for a Responder.
///
/// ```rust
/// use actix_web::{HttpRequest, Responder, http::StatusCode};
/// use actix_web::{http::StatusCode, HttpRequest, Responder};
///
/// fn index(req: HttpRequest) -> impl Responder {
/// "Welcome!".with_status(StatusCode::OK)
/// }
/// # fn main() {}
/// ```
fn with_status(self, status: StatusCode) -> CustomResponder<Self>
where
@ -33,7 +32,9 @@ pub trait Responder {
CustomResponder::new(self).with_status(status)
}
/// Add header to the Responder's response.
/// Insert header to the final response.
///
/// Overrides other headers with the same name.
///
/// ```rust
/// use actix_web::{web, HttpRequest, Responder};
@ -45,21 +46,16 @@ pub trait Responder {
/// }
///
/// fn index(req: HttpRequest) -> impl Responder {
/// web::Json(
/// MyObj{name: "Name".to_string()}
/// )
/// .with_header("x-version", "1.2.3")
/// web::Json(MyObj { name: "Name".to_owned() })
/// .with_header(("x-version", "1.2.3"))
/// }
/// # fn main() {}
/// ```
fn with_header<K, V>(self, key: K, value: V) -> CustomResponder<Self>
fn with_header<H>(self, header: H) -> CustomResponder<Self>
where
Self: Sized,
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
V: IntoHeaderValue,
H: IntoHeaderPair,
{
CustomResponder::new(self).with_header(key, value)
CustomResponder::new(self).with_header(header)
}
}
@ -155,7 +151,7 @@ impl Responder for BytesMut {
}
}
/// Allows to override status code and headers for a responder.
/// Allows overriding status code and headers for a responder.
pub struct CustomResponder<T> {
responder: T,
status: Option<StatusCode>,
@ -181,14 +177,15 @@ impl<T: Responder> CustomResponder<T> {
/// fn index(req: HttpRequest) -> impl Responder {
/// "Welcome!".with_status(StatusCode::OK)
/// }
/// # fn main() {}
/// ```
pub fn with_status(mut self, status: StatusCode) -> Self {
self.status = Some(status);
self
}
/// Add header to the Responder's response.
/// Insert header to the final response.
///
/// Overrides other headers with the same name.
///
/// ```rust
/// use actix_web::{web, HttpRequest, Responder};
@ -200,32 +197,24 @@ impl<T: Responder> CustomResponder<T> {
/// }
///
/// fn index(req: HttpRequest) -> impl Responder {
/// web::Json(
/// MyObj{name: "Name".to_string()}
/// )
/// .with_header("x-version", "1.2.3")
/// web::Json(MyObj { name: "Name".to_string() })
/// .with_header(("x-version", "1.2.3"))
/// .with_header(("x-version", "1.2.3"))
/// }
/// # fn main() {}
/// ```
pub fn with_header<K, V>(mut self, key: K, value: V) -> Self
pub fn with_header<H>(mut self, header: H) -> Self
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
V: IntoHeaderValue,
H: IntoHeaderPair,
{
if self.headers.is_none() {
self.headers = Some(HeaderMap::new());
}
match HeaderName::try_from(key) {
Ok(key) => match value.try_into() {
Ok(value) => {
self.headers.as_mut().unwrap().append(key, value);
}
Err(e) => self.error = Some(e.into()),
},
match header.try_into_header_pair() {
Ok((key, value)) => self.headers.as_mut().unwrap().append(key, value),
Err(e) => self.error = Some(e.into()),
};
self
}
}
@ -240,6 +229,7 @@ impl<T: Responder> Responder for CustomResponder<T> {
if let Some(ref headers) = self.headers {
for (k, v) in headers {
// TODO: before v4, decide if this should be append instead
res.headers_mut().insert(k.clone(), v.clone());
}
}
@ -250,7 +240,7 @@ impl<T: Responder> Responder for CustomResponder<T> {
impl<T> Responder for InternalError<T>
where
T: std::fmt::Debug + std::fmt::Display + 'static,
T: fmt::Debug + fmt::Display + 'static,
{
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::from_error(self.into())
@ -412,7 +402,7 @@ pub(crate) mod tests {
let res = "test"
.to_string()
.with_header("content-type", "json")
.with_header(("content-type", "json"))
.respond_to(&req);
assert_eq!(res.status(), StatusCode::OK);
@ -432,13 +422,13 @@ pub(crate) mod tests {
let req = TestRequest::default().to_http_request();
let res = ("test".to_string(), StatusCode::OK)
.with_header("content-type", "json")
.with_header((CONTENT_TYPE, mime::APPLICATION_JSON))
.respond_to(&req);
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.body().bin_ref(), b"test");
assert_eq!(
res.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("json")
HeaderValue::from_static("application/json")
);
}
}

View File

@ -588,14 +588,14 @@ mod tests {
fn test_fmt_debug() {
let req = TestRequest::get()
.uri("/index.html?test=1")
.header("x-test", "111")
.insert_header(("x-test", "111"))
.to_srv_request();
let s = format!("{:?}", req);
assert!(s.contains("ServiceRequest"));
assert!(s.contains("test=1"));
assert!(s.contains("x-test"));
let res = HttpResponse::Ok().header("x-test", "111").finish();
let res = HttpResponse::Ok().insert_header(("x-test", "111")).finish();
let res = TestRequest::post()
.uri("/index.html?test=1")
.to_srv_response(res);

View File

@ -1,13 +1,13 @@
//! Various helpers for Actix applications to use during testing.
use std::convert::TryFrom;
use std::net::SocketAddr;
use std::rc::Rc;
use std::sync::mpsc;
use std::{fmt, net, thread, time};
use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_http::http::header::{ContentType, Header, HeaderName, IntoHeaderValue};
use actix_http::http::{Error as HttpError, Method, StatusCode, Uri, Version};
use actix_http::http::header::{ContentType, IntoHeaderPair};
use actix_http::http::{Method, StatusCode, Uri, Version};
use actix_http::test::TestRequest as HttpTestRequest;
use actix_http::{cookie::Cookie, ws, Extensions, HttpService, Request};
use actix_router::{Path, ResourceDef, Url};
@ -349,7 +349,7 @@ where
///
/// #[test]
/// fn test_index() {
/// let req = test::TestRequest::with_header("content-type", "text/plain")
/// let req = test::TestRequest::default().insert_header("content-type", "text/plain")
/// .to_http_request();
///
/// let resp = index(req).await.unwrap();
@ -389,21 +389,6 @@ impl TestRequest {
TestRequest::default().uri(path)
}
/// Create TestRequest and set header
pub fn with_hdr<H: Header>(hdr: H) -> TestRequest {
TestRequest::default().set(hdr)
}
/// Create TestRequest and set header
pub fn with_header<K, V>(key: K, value: V) -> TestRequest
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
V: IntoHeaderValue,
{
TestRequest::default().header(key, value)
}
/// Create TestRequest and set method to `Method::GET`
pub fn get() -> TestRequest {
TestRequest::default().method(Method::GET)
@ -447,24 +432,25 @@ impl TestRequest {
self
}
/// Set a header
pub fn set<H: Header>(mut self, hdr: H) -> Self {
self.req.set(hdr);
self
}
/// Set a header
pub fn header<K, V>(mut self, key: K, value: V) -> Self
/// Insert a header, replacing any that were set with an equivalent field name.
pub fn insert_header<H>(mut self, header: H) -> Self
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
V: IntoHeaderValue,
H: IntoHeaderPair,
{
self.req.header(key, value);
self.req.insert_header(header);
self
}
/// Set cookie for this request
/// Append a header, keeping any that were set with an equivalent field name.
pub fn append_header<H>(mut self, header: H) -> Self
where
H: IntoHeaderPair,
{
self.req.append_header(header);
self
}
/// Set cookie for this request.
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
self.req.cookie(cookie);
self
@ -494,7 +480,7 @@ impl TestRequest {
let bytes = serde_urlencoded::to_string(data)
.expect("Failed to serialize test data as a urlencoded form");
self.req.set_payload(bytes);
self.req.set(ContentType::form_url_encoded());
self.req.insert_header(ContentType::form_url_encoded());
self
}
@ -504,7 +490,7 @@ impl TestRequest {
let bytes =
serde_json::to_string(data).expect("Failed to serialize test data to json");
self.req.set_payload(bytes);
self.req.set(ContentType::json());
self.req.insert_header(ContentType::json());
self
}
@ -1029,9 +1015,10 @@ mod tests {
#[actix_rt::test]
async fn test_basics() {
let req = TestRequest::with_hdr(header::ContentType::json())
let req = TestRequest::default()
.version(Version::HTTP_2)
.set(header::Date(SystemTime::now().into()))
.insert_header(header::ContentType::json())
.insert_header(header::Date(SystemTime::now().into()))
.param("test", "123")
.data(10u32)
.app_data(20u64)
@ -1068,7 +1055,7 @@ mod tests {
let put_req = TestRequest::put()
.uri("/index.html")
.header(header::CONTENT_TYPE, "application/json")
.insert_header((header::CONTENT_TYPE, "application/json"))
.to_request();
let result = read_response(&mut app, put_req).await;
@ -1076,7 +1063,7 @@ mod tests {
let patch_req = TestRequest::patch()
.uri("/index.html")
.header(header::CONTENT_TYPE, "application/json")
.insert_header((header::CONTENT_TYPE, "application/json"))
.to_request();
let result = read_response(&mut app, patch_req).await;
@ -1099,7 +1086,7 @@ mod tests {
let req = TestRequest::post()
.uri("/index.html")
.header(header::CONTENT_TYPE, "application/json")
.insert_header((header::CONTENT_TYPE, "application/json"))
.to_request();
let result = read_response(&mut app, req).await;
@ -1144,7 +1131,7 @@ mod tests {
let req = TestRequest::post()
.uri("/people")
.header(header::CONTENT_TYPE, "application/json")
.insert_header((header::CONTENT_TYPE, "application/json"))
.set_payload(payload)
.to_request();
@ -1165,7 +1152,7 @@ mod tests {
let resp = TestRequest::post()
.uri("/people")
.header(header::CONTENT_TYPE, "application/json")
.insert_header((header::CONTENT_TYPE, "application/json"))
.set_payload(payload)
.send_request(&mut app)
.await;

View File

@ -381,11 +381,11 @@ mod tests {
#[actix_rt::test]
async fn test_form() {
let (req, mut pl) =
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((CONTENT_LENGTH, 11))
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts();
let Form(s) = Form::<Info>::from_request(&req, &mut pl).await.unwrap();
assert_eq!(
@ -414,25 +414,26 @@ mod tests {
#[actix_rt::test]
async fn test_urlencoded_error() {
let (req, mut pl) =
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(CONTENT_LENGTH, "xxxx")
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((CONTENT_LENGTH, "xxxx"))
.to_http_parts();
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
assert!(eq(info.err().unwrap(), UrlencodedError::UnknownLength));
let (req, mut pl) =
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(CONTENT_LENGTH, "1000000")
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((CONTENT_LENGTH, "1000000"))
.to_http_parts();
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
assert!(eq(
info.err().unwrap(),
UrlencodedError::Overflow { size: 0, limit: 0 }
));
let (req, mut pl) = TestRequest::with_header(CONTENT_TYPE, "text/plain")
.header(CONTENT_LENGTH, "10")
let (req, mut pl) = TestRequest::default()
.insert_header((CONTENT_TYPE, "text/plain"))
.insert_header((CONTENT_LENGTH, 10))
.to_http_parts();
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
assert!(eq(info.err().unwrap(), UrlencodedError::ContentType));
@ -440,11 +441,11 @@ mod tests {
#[actix_rt::test]
async fn test_urlencoded() {
let (req, mut pl) =
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((CONTENT_LENGTH, 11))
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts();
let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
assert_eq!(
@ -455,13 +456,14 @@ mod tests {
}
);
let (req, mut pl) = TestRequest::with_header(
CONTENT_TYPE,
"application/x-www-form-urlencoded; charset=utf-8",
)
.header(CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((
CONTENT_TYPE,
"application/x-www-form-urlencoded; charset=utf-8",
))
.insert_header((CONTENT_LENGTH, 11))
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts();
let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
assert_eq!(
@ -497,8 +499,8 @@ mod tests {
let ctype = HeaderValue::from_static("application/x-www-form-urlencoded");
let (req, mut pl) = TestRequest::default()
.header(CONTENT_TYPE, ctype)
.header(CONTENT_LENGTH, HeaderValue::from_static("20"))
.insert_header((CONTENT_TYPE, ctype))
.insert_header((CONTENT_LENGTH, HeaderValue::from_static("20")))
.set_payload(Bytes::from_static(b"hello=test&counter=4"))
.app_data(web::Data::new(FormConfig::default().limit(10)))
.to_http_parts();

View File

@ -427,7 +427,7 @@ mod tests {
use crate::{
error::InternalError,
http::{
header::{self, HeaderValue, CONTENT_LENGTH, CONTENT_TYPE},
header::{self, CONTENT_LENGTH, CONTENT_TYPE},
StatusCode,
},
test::{load_stream, TestRequest},
@ -469,14 +469,14 @@ mod tests {
#[actix_rt::test]
async fn test_custom_error_responder() {
let (req, mut pl) = TestRequest::default()
.header(
.insert_header((
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
)
.header(
))
.insert_header((
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
))
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.app_data(JsonConfig::default().limit(10).error_handler(|err, _| {
let msg = MyObject {
@ -500,14 +500,14 @@ mod tests {
#[actix_rt::test]
async fn test_extract() {
let (req, mut pl) = TestRequest::default()
.header(
.insert_header((
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
)
.header(
))
.insert_header((
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
))
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.to_http_parts();
@ -521,14 +521,14 @@ mod tests {
);
let (req, mut pl) = TestRequest::default()
.header(
.insert_header((
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
)
.header(
))
.insert_header((
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
))
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.app_data(JsonConfig::default().limit(10))
.to_http_parts();
@ -538,14 +538,14 @@ mod tests {
.contains("Json payload size is bigger than allowed"));
let (req, mut pl) = TestRequest::default()
.header(
.insert_header((
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
)
.header(
))
.insert_header((
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
))
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.app_data(
JsonConfig::default()
@ -564,23 +564,23 @@ mod tests {
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
let (req, mut pl) = TestRequest::default()
.header(
.insert_header((
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/text"),
)
))
.to_http_parts();
let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
let (req, mut pl) = TestRequest::default()
.header(
.insert_header((
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
)
.header(
))
.insert_header((
header::CONTENT_LENGTH,
header::HeaderValue::from_static("10000"),
)
))
.to_http_parts();
let json = JsonBody::<MyObject>::new(&req, &mut pl, None)
@ -589,14 +589,14 @@ mod tests {
assert!(json_eq(json.err().unwrap(), JsonPayloadError::Overflow));
let (req, mut pl) = TestRequest::default()
.header(
.insert_header((
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
)
.header(
))
.insert_header((
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
))
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.to_http_parts();
@ -611,17 +611,18 @@ mod tests {
#[actix_rt::test]
async fn test_with_json_and_bad_content_type() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain"),
)
.header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.app_data(JsonConfig::default().limit(4096))
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain"),
))
.insert_header((
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
))
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.app_data(JsonConfig::default().limit(4096))
.to_http_parts();
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
assert!(s.is_err())
@ -629,19 +630,20 @@ mod tests {
#[actix_rt::test]
async fn test_with_json_and_good_custom_content_type() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain"),
)
.header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
}))
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain"),
))
.insert_header((
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
))
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
}))
.to_http_parts();
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
assert!(s.is_ok())
@ -649,19 +651,20 @@ mod tests {
#[actix_rt::test]
async fn test_with_json_and_bad_custom_content_type() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/html"),
)
.header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
}))
.to_http_parts();
let (req, mut pl) = TestRequest::default()
.insert_header((
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/html"),
))
.insert_header((
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
))
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
}))
.to_http_parts();
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
assert!(s.is_err())
@ -670,8 +673,8 @@ mod tests {
#[actix_rt::test]
async fn test_with_config_in_data_wrapper() {
let (req, mut pl) = TestRequest::default()
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
.header(CONTENT_LENGTH, HeaderValue::from_static("16"))
.insert_header((CONTENT_TYPE, mime::APPLICATION_JSON))
.insert_header((CONTENT_LENGTH, 16))
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.app_data(web::Data::new(JsonConfig::default().limit(10)))
.to_http_parts();

View File

@ -364,14 +364,13 @@ mod tests {
let cfg = PayloadConfig::default().mimetype(mime::APPLICATION_JSON);
assert!(cfg.check_mimetype(&req).is_err());
let req = TestRequest::with_header(
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.to_http_request();
let req = TestRequest::default()
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
.to_http_request();
assert!(cfg.check_mimetype(&req).is_err());
let req = TestRequest::with_header(header::CONTENT_TYPE, "application/json")
let req = TestRequest::default()
.insert_header((header::CONTENT_TYPE, "application/json"))
.to_http_request();
assert!(cfg.check_mimetype(&req).is_ok());
}
@ -432,25 +431,25 @@ mod tests {
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let req = TestRequest::with_uri("/bytes-app-data")
.header(header::CONTENT_TYPE, mime::APPLICATION_JSON)
.insert_header(header::ContentType(mime::APPLICATION_JSON))
.to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/bytes-data")
.header(header::CONTENT_TYPE, mime::APPLICATION_JSON)
.insert_header(header::ContentType(mime::APPLICATION_JSON))
.to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/string-app-data")
.header(header::CONTENT_TYPE, mime::APPLICATION_JSON)
.insert_header(header::ContentType(mime::APPLICATION_JSON))
.to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/string-data")
.header(header::CONTENT_TYPE, mime::APPLICATION_JSON)
.insert_header(header::ContentType(mime::APPLICATION_JSON))
.to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
@ -458,7 +457,8 @@ mod tests {
#[actix_rt::test]
async fn test_bytes() {
let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_LENGTH, "11"))
.set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts();
@ -468,7 +468,8 @@ mod tests {
#[actix_rt::test]
async fn test_string() {
let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_LENGTH, "11"))
.set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts();
@ -478,7 +479,8 @@ mod tests {
#[actix_rt::test]
async fn test_message_body() {
let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "xxxx")
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_LENGTH, "xxxx"))
.to_srv_request()
.into_parts();
let res = HttpMessageBody::new(&req, &mut pl).await;
@ -487,7 +489,8 @@ mod tests {
_ => unreachable!("error"),
}
let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "1000000")
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_LENGTH, "1000000"))
.to_srv_request()
.into_parts();
let res = HttpMessageBody::new(&req, &mut pl).await;