unfinished revive tests

This commit is contained in:
Rob Ede 2021-01-15 06:50:09 +00:00
parent 0a506bf2e9
commit d7cef210b3
No known key found for this signature in database
GPG Key ID: C2A3B36E841A91E6
4 changed files with 210 additions and 183 deletions

View File

@ -1,3 +1,13 @@
use std::{convert::Infallible, str::FromStr};
use http::header::InvalidHeaderValue;
use crate::{
error::ParseError,
header::{self, from_one_raw_str, Header, HeaderName, HeaderValue, IntoHeaderValue},
HttpMessage,
};
/// Represents a supported content encoding. /// Represents a supported content encoding.
#[derive(Copy, Clone, PartialEq, Debug)] #[derive(Copy, Clone, PartialEq, Debug)]
pub enum ContentEncoding { pub enum ContentEncoding {
@ -47,6 +57,20 @@ impl ContentEncoding {
} }
} }
impl Default for ContentEncoding {
fn default() -> Self {
Self::Identity
}
}
impl FromStr for ContentEncoding {
type Err = Infallible;
fn from_str(val: &str) -> Result<Self, Self::Err> {
Ok(Self::from(val))
}
}
impl From<&str> for ContentEncoding { impl From<&str> for ContentEncoding {
fn from(val: &str) -> ContentEncoding { fn from(val: &str) -> ContentEncoding {
let val = val.trim(); let val = val.trim();
@ -58,7 +82,25 @@ impl From<&str> for ContentEncoding {
} else if val.eq_ignore_ascii_case("deflate") { } else if val.eq_ignore_ascii_case("deflate") {
ContentEncoding::Deflate ContentEncoding::Deflate
} else { } else {
ContentEncoding::Identity ContentEncoding::default()
} }
} }
} }
impl IntoHeaderValue for ContentEncoding {
type Error = InvalidHeaderValue;
fn try_into_value(self) -> Result<http::HeaderValue, Self::Error> {
Ok(HeaderValue::from_static(self.as_str()))
}
}
impl Header for ContentEncoding {
fn name() -> HeaderName {
header::CONTENT_ENCODING
}
fn parse<T: HttpMessage>(msg: &T) -> Result<Self, ParseError> {
from_one_raw_str(msg.headers().get(Self::name()))
}
}

View File

@ -9,17 +9,20 @@ use bytes::Bytes;
use flate2::read::GzDecoder; use flate2::read::GzDecoder;
use flate2::write::GzEncoder; use flate2::write::GzEncoder;
use flate2::Compression; use flate2::Compression;
use futures_util::future::ok; use futures_util::{future::ok, stream};
use rand::Rng; use rand::Rng;
use actix_http::HttpService; use actix_http::{
http::{self, StatusCode},
HttpService,
};
use actix_http_test::test_server; use actix_http_test::test_server;
use actix_service::{map_config, pipeline_factory}; use actix_service::{map_config, pipeline_factory};
use actix_web::dev::{AppConfig, BodyEncoding};
use actix_web::http::Cookie;
use actix_web::middleware::Compress;
use actix_web::{ use actix_web::{
http::header, test, web, App, Error, HttpMessage, HttpRequest, HttpResponse, dev::{AppConfig, BodyEncoding},
http::{header, Cookie},
middleware::Compress,
test, web, App, Error, HttpMessage, HttpRequest, HttpResponse,
}; };
use awc::error::SendRequestError; use awc::error::SendRequestError;
@ -557,117 +560,100 @@ async fn test_client_brotli_encoding_large_random() {
assert_eq!(bytes, Bytes::from(data)); assert_eq!(bytes, Bytes::from(data));
} }
// TODO: why is test ignored #[actix_rt::test]
// #[actix_rt::test] async fn test_client_deflate_encoding() {
// async fn test_client_deflate_encoding() { let srv = test::start(|| {
// let srv = test::TestServer::start(|app| { App::new().default_service(web::to(|body: Bytes| async move {
// app.handler(|req: &HttpRequest| { HttpResponse::Ok()
// req.body() .encoding(http::ContentEncoding::Br)
// .and_then(|bytes: Bytes| { .body(body)
// Ok(HttpResponse::Ok() }))
// .content_encoding(http::ContentEncoding::Br) });
// .body(bytes))
// })
// .responder()
// })
// });
// // client request let req = srv
// let request = srv .post("/")
// .post() .insert_header(header::ContentEncoding::Deflate)
// .content_encoding(http::ContentEncoding::Deflate) .send_body(STR);
// .body(STR)
// .unwrap();
// let response = srv.execute(request.send()).unwrap();
// assert!(response.status().is_success());
// // read response let mut res = req.await.unwrap();
// let bytes = srv.execute(response.body()).unwrap(); assert_eq!(res.status(), StatusCode::OK);
// assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
// }
// TODO: why is test ignored let bytes = res.body().await.unwrap();
// #[actix_rt::test] assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
// async fn test_client_deflate_encoding_large_random() { }
// let data = rand::thread_rng()
// .sample_iter(&rand::distributions::Alphanumeric)
// .take(70_000)
// .collect::<String>();
// let srv = test::TestServer::start(|app| { #[actix_rt::test]
// app.handler(|req: &HttpRequest| { async fn test_client_deflate_encoding_large_random() {
// req.body() let data = rand::thread_rng()
// .and_then(|bytes: Bytes| { .sample_iter(rand::distributions::Alphanumeric)
// Ok(HttpResponse::Ok() .map(char::from)
// .content_encoding(http::ContentEncoding::Br) .take(70_000)
// .body(bytes)) .collect::<String>();
// })
// .responder()
// })
// });
// // client request let srv = test::start(|| {
// let request = srv App::new().default_service(web::to(|body: Bytes| async move {
// .post() HttpResponse::Ok()
// .content_encoding(http::ContentEncoding::Deflate) .encoding(http::ContentEncoding::Br)
// .body(data.clone()) .body(body)
// .unwrap(); }))
// let response = srv.execute(request.send()).unwrap(); });
// assert!(response.status().is_success());
// // read response let req = srv
// let bytes = srv.execute(response.body()).unwrap(); .post("/")
// assert_eq!(bytes, Bytes::from(data)); .insert_header(header::ContentEncoding::Deflate)
// } .send_body(data.clone());
// TODO: why is test ignored let mut res = req.await.unwrap();
// #[actix_rt::test] assert_eq!(res.status(), StatusCode::OK);
// async fn test_client_streaming_explicit() {
// let srv = test::TestServer::start(|app| {
// app.handler(|req: &HttpRequest| {
// req.body()
// .map_err(Error::from)
// .and_then(|body| {
// Ok(HttpResponse::Ok()
// .chunked()
// .content_encoding(http::ContentEncoding::Identity)
// .body(body))
// })
// .responder()
// })
// });
// let body = once(Ok(Bytes::from_static(STR.as_ref()))); let bytes = res.body().await.unwrap();
assert_eq!(bytes, Bytes::from(data));
}
// let request = srv.get("/").body(Body::Streaming(Box::new(body))).unwrap(); #[actix_rt::test]
// let response = srv.execute(request.send()).unwrap(); async fn test_client_streaming_explicit() {
// assert!(response.status().is_success()); let srv = test::start(|| {
App::new().default_service(web::to(|body: web::Payload| async move {
HttpResponse::Ok()
.encoding(http::ContentEncoding::Identity)
.streaming(body)
}))
});
// // read response let body = stream::once(async {
// let bytes = srv.execute(response.body()).unwrap(); Ok::<_, actix_http::Error>(Bytes::from_static(STR.as_bytes()))
// assert_eq!(bytes, Bytes::from_static(STR.as_ref())); });
// } let req = srv.post("/").send_stream(Box::pin(body));
// TODO: why is test ignored let mut res = req.await.unwrap();
// #[actix_rt::test] assert!(res.status().is_success());
// async fn test_body_streaming_implicit() {
// let srv = test::TestServer::start(|app| {
// app.handler(|_| {
// let body = once(Ok(Bytes::from_static(STR.as_ref())));
// HttpResponse::Ok()
// .content_encoding(http::ContentEncoding::Gzip)
// .body(Body::Streaming(Box::new(body)))
// })
// });
// let request = srv.get("/").finish().unwrap(); let bytes = res.body().await.unwrap();
// let response = srv.execute(request.send()).unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
// assert!(response.status().is_success()); }
// // read response #[actix_rt::test]
// let bytes = srv.execute(response.body()).unwrap(); async fn test_body_streaming_implicit() {
// assert_eq!(bytes, Bytes::from_static(STR.as_ref())); let srv = test::start(|| {
// } App::new().default_service(web::to(|| {
let body = stream::once(async {
Ok::<_, actix_http::Error>(Bytes::from_static(STR.as_bytes()))
});
HttpResponse::Ok()
.encoding(http::ContentEncoding::Gzip)
.streaming(Box::pin(body))
}))
});
let req = srv.get("/").send();
let mut res = req.await.unwrap();
assert!(res.status().is_success());
let bytes = res.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
}
#[actix_rt::test] #[actix_rt::test]
async fn test_client_cookie_handling() { async fn test_client_cookie_handling() {
@ -738,36 +724,35 @@ async fn test_client_cookie_handling() {
assert_eq!(c2, cookie2); assert_eq!(c2, cookie2);
} }
// TODO: why is test ignored #[actix_rt::test]
// #[actix_rt::test] async fn client_unread_response() {
// fn client_read_until_eof() { let addr = test::unused_addr();
// let addr = test::TestServer::unused_addr();
// thread::spawn(move || { std::thread::spawn(move || {
// let lst = net::TcpListener::bind(addr).unwrap(); let lst = std::net::TcpListener::bind(addr).unwrap();
// for stream in lst.incoming() { for stream in lst.incoming() {
// let mut stream = stream.unwrap(); let mut stream = stream.unwrap();
// let mut b = [0; 1000]; let mut b = [0; 1000];
// let _ = stream.read(&mut b).unwrap(); let _ = stream.read(&mut b).unwrap();
// let _ = stream let _ = stream.write_all(
// .write_all(b"HTTP/1.1 200 OK\r\nconnection: close\r\n\r\nwelcome!"); b"HTTP/1.1 200 OK\r\n\
// } connection: close\r\n\
// }); \r\n\
welcome!",
);
}
});
// let mut sys = actix::System::new("test"); // client request
let req = awc::Client::new().get(format!("http://{}/", addr).as_str());
let mut res = req.send().await.unwrap();
assert!(res.status().is_success());
// // client request // awc does not read all bytes unless content-length is specified
// let req = client::ClientRequest::get(format!("http://{}/", addr).as_str()) let bytes = res.body().await.unwrap();
// .finish() assert_eq!(bytes, Bytes::from_static(b""));
// .unwrap(); }
// let response = req.send().await.unwrap();
// assert!(response.status().is_success());
// // read response
// let bytes = response.body().await.unwrap();
// assert_eq!(bytes, Bytes::from_static(b"welcome!"));
// }
#[actix_rt::test] #[actix_rt::test]
async fn client_basic_auth() { async fn client_basic_auth() {

View File

@ -16,6 +16,7 @@ use actix_http::{
Error, Error,
}; };
use actix_service::{Service, Transform}; use actix_service::{Service, Transform};
use futures_core::ready;
use futures_util::future::{ok, Ready}; use futures_util::future::{ok, Ready};
use pin_project::pin_project; use pin_project::pin_project;
@ -131,7 +132,7 @@ where
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 this = self.project(); let this = self.project();
match futures_util::ready!(this.fut.poll(cx)) { match ready!(this.fut.poll(cx)) {
Ok(resp) => { Ok(resp) => {
let enc = if let Some(enc) = resp.response().get_encoding() { let enc = if let Some(enc) = resp.response().get_encoding() {
enc enc

View File

@ -800,62 +800,61 @@ async fn test_reading_deflate_encoding_large_random_rustls() {
assert_eq!(bytes, Bytes::from(data)); assert_eq!(bytes, Bytes::from(data));
} }
// TODO: why is test ignored #[actix_rt::test]
// #[test] async fn test_server_cookies() {
// fn test_server_cookies() { use actix_web::http;
// use actix_web::http;
// let srv = test::TestServer::with_factory(|| { let srv = test::TestServer::with_factory(|| {
// App::new().resource("/", |r| { App::new().resource("/", |r| {
// r.f(|_| { r.f(|_| {
// HttpResponse::Ok() HttpResponse::Ok()
// .cookie( .cookie(
// http::CookieBuilder::new("first", "first_value") http::CookieBuilder::new("first", "first_value")
// .http_only(true) .http_only(true)
// .finish(), .finish(),
// ) )
// .cookie(http::Cookie::new("second", "first_value")) .cookie(http::Cookie::new("second", "first_value"))
// .cookie(http::Cookie::new("second", "second_value")) .cookie(http::Cookie::new("second", "second_value"))
// .finish() .finish()
// }) })
// }) })
// }); });
// let first_cookie = http::CookieBuilder::new("first", "first_value") let first_cookie = http::CookieBuilder::new("first", "first_value")
// .http_only(true) .http_only(true)
// .finish(); .finish();
// let second_cookie = http::Cookie::new("second", "second_value"); let second_cookie = http::Cookie::new("second", "second_value");
// let request = srv.get("/").finish().unwrap(); let request = srv.get("/").finish().unwrap();
// let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
// assert!(response.status().is_success()); assert!(response.status().is_success());
// let cookies = response.cookies().expect("To have cookies"); let cookies = response.cookies().expect("To have cookies");
// assert_eq!(cookies.len(), 2); assert_eq!(cookies.len(), 2);
// if cookies[0] == first_cookie { if cookies[0] == first_cookie {
// assert_eq!(cookies[1], second_cookie); assert_eq!(cookies[1], second_cookie);
// } else { } else {
// assert_eq!(cookies[0], second_cookie); assert_eq!(cookies[0], second_cookie);
// assert_eq!(cookies[1], first_cookie); assert_eq!(cookies[1], first_cookie);
// } }
// let first_cookie = first_cookie.to_string(); let first_cookie = first_cookie.to_string();
// let second_cookie = second_cookie.to_string(); let second_cookie = second_cookie.to_string();
// //Check that we have exactly two instances of raw cookie headers //Check that we have exactly two instances of raw cookie headers
// let cookies = response let cookies = response
// .headers() .headers()
// .get_all(http::header::SET_COOKIE) .get_all(http::header::SET_COOKIE)
// .iter() .iter()
// .map(|header| header.to_str().expect("To str").to_string()) .map(|header| header.to_str().expect("To str").to_string())
// .collect::<Vec<_>>(); .collect::<Vec<_>>();
// assert_eq!(cookies.len(), 2); assert_eq!(cookies.len(), 2);
// if cookies[0] == first_cookie { if cookies[0] == first_cookie {
// assert_eq!(cookies[1], second_cookie); assert_eq!(cookies[1], second_cookie);
// } else { } else {
// assert_eq!(cookies[0], second_cookie); assert_eq!(cookies[0], second_cookie);
// assert_eq!(cookies[1], first_cookie); assert_eq!(cookies[1], first_cookie);
// } }
// } }
#[actix_rt::test] #[actix_rt::test]
async fn test_slow_request() { async fn test_slow_request() {