1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-24 00:21:08 +01:00

update tests to async handlers

This commit is contained in:
Nikolay Kim 2019-11-22 11:49:35 +06:00
parent e668acc596
commit 57981ca04a
9 changed files with 111 additions and 79 deletions

View File

@ -11,7 +11,7 @@
//! use actix_cors::Cors; //! use actix_cors::Cors;
//! use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer}; //! use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer};
//! //!
//! fn index(req: HttpRequest) -> &'static str { //! async fn index(req: HttpRequest) -> &'static str {
//! "Hello world" //! "Hello world"
//! } //! }
//! //!

View File

@ -1176,9 +1176,11 @@ mod tests {
let mut srv = let mut srv =
test::init_service(App::new().wrap(Compress::default()).service( test::init_service(App::new().wrap(Compress::default()).service(
web::resource("/").to(|| { web::resource("/").to(|| {
NamedFile::open("Cargo.toml") async {
.unwrap() NamedFile::open("Cargo.toml")
.set_content_encoding(header::ContentEncoding::Identity) .unwrap()
.set_content_encoding(header::ContentEncoding::Identity)
}
}), }),
)) ))
.await; .await;
@ -1199,9 +1201,11 @@ mod tests {
let mut srv = let mut srv =
test::init_service(App::new().wrap(Compress::default()).service( test::init_service(App::new().wrap(Compress::default()).service(
web::resource("/").to(|| { web::resource("/").to(|| {
NamedFile::open("Cargo.toml") async {
.unwrap() NamedFile::open("Cargo.toml")
.set_content_encoding(header::ContentEncoding::Gzip) .unwrap()
.set_content_encoding(header::ContentEncoding::Gzip)
}
}), }),
)) ))
.await; .await;

View File

@ -388,6 +388,12 @@ impl BoxedResponseHead {
pub fn new(status: StatusCode) -> Self { pub fn new(status: StatusCode) -> Self {
RESPONSE_POOL.with(|p| p.get_message(status)) RESPONSE_POOL.with(|p| p.get_message(status))
} }
pub(crate) fn take(&mut self) -> Self {
BoxedResponseHead {
head: self.head.take(),
}
}
} }
impl std::ops::Deref for BoxedResponseHead { impl std::ops::Deref for BoxedResponseHead {
@ -406,7 +412,9 @@ impl std::ops::DerefMut for BoxedResponseHead {
impl Drop for BoxedResponseHead { impl Drop for BoxedResponseHead {
fn drop(&mut self) { fn drop(&mut self) {
RESPONSE_POOL.with(|p| p.release(self.head.take().unwrap())) if let Some(head) = self.head.take() {
RESPONSE_POOL.with(move |p| p.release(head))
}
} }
} }

View File

@ -288,10 +288,7 @@ impl Future for Response {
fn poll(mut self: Pin<&mut Self>, _: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, _: &mut Context) -> Poll<Self::Output> {
Poll::Ready(Ok(Response { Poll::Ready(Ok(Response {
head: std::mem::replace( head: self.head.take(),
&mut self.head,
BoxedResponseHead::new(StatusCode::OK),
),
body: self.body.take_body(), body: self.body.take_body(),
error: self.error.take(), error: self.error.take(),
})) }))

View File

@ -16,7 +16,7 @@
//! use actix_web::*; //! use actix_web::*;
//! use actix_identity::{Identity, CookieIdentityPolicy, IdentityService}; //! use actix_identity::{Identity, CookieIdentityPolicy, IdentityService};
//! //!
//! fn index(id: Identity) -> String { //! async fn index(id: Identity) -> String {
//! // access request identity //! // access request identity
//! if let Some(id) = id.identity() { //! if let Some(id) = id.identity() {
//! format!("Welcome! {}", id) //! format!("Welcome! {}", id)
@ -25,12 +25,12 @@
//! } //! }
//! } //! }
//! //!
//! fn login(id: Identity) -> HttpResponse { //! async fn login(id: Identity) -> HttpResponse {
//! id.remember("User1".to_owned()); // <- remember identity //! id.remember("User1".to_owned()); // <- remember identity
//! HttpResponse::Ok().finish() //! HttpResponse::Ok().finish()
//! } //! }
//! //!
//! fn logout(id: Identity) -> HttpResponse { //! async fn logout(id: Identity) -> HttpResponse {
//! id.forget(); // <- remove identity //! id.forget(); // <- remove identity
//! HttpResponse::Ok().finish() //! HttpResponse::Ok().finish()
//! } //! }
@ -764,11 +764,13 @@ mod tests {
.secure(false) .secure(false)
.name(COOKIE_NAME)))) .name(COOKIE_NAME))))
.service(web::resource("/").to(|id: Identity| { .service(web::resource("/").to(|id: Identity| {
let identity = id.identity(); async move {
if identity.is_none() { let identity = id.identity();
id.remember(COOKIE_LOGIN.to_string()) if identity.is_none() {
id.remember(COOKIE_LOGIN.to_string())
}
web::Json(identity)
} }
web::Json(identity)
})), })),
) )
.await .await

View File

@ -371,8 +371,10 @@ mod tests {
App::new() App::new()
.wrap(CookieSession::signed(&[0; 32]).secure(false)) .wrap(CookieSession::signed(&[0; 32]).secure(false))
.service(web::resource("/").to(|ses: Session| { .service(web::resource("/").to(|ses: Session| {
let _ = ses.set("counter", 100); async move {
"test" let _ = ses.set("counter", 100);
"test"
}
})), })),
) )
.await; .await;
@ -394,8 +396,10 @@ mod tests {
App::new() App::new()
.wrap(CookieSession::private(&[0; 32]).secure(false)) .wrap(CookieSession::private(&[0; 32]).secure(false))
.service(web::resource("/").to(|ses: Session| { .service(web::resource("/").to(|ses: Session| {
let _ = ses.set("counter", 100); async move {
"test" let _ = ses.set("counter", 100);
"test"
}
})), })),
) )
.await; .await;
@ -417,8 +421,10 @@ mod tests {
App::new() App::new()
.wrap(CookieSession::signed(&[0; 32]).secure(false)) .wrap(CookieSession::signed(&[0; 32]).secure(false))
.service(web::resource("/").to(|ses: Session| { .service(web::resource("/").to(|ses: Session| {
let _ = ses.set("counter", 100); async move {
"test" let _ = ses.set("counter", 100);
"test"
}
})), })),
) )
.await; .await;
@ -448,12 +454,16 @@ mod tests {
.max_age(100), .max_age(100),
) )
.service(web::resource("/").to(|ses: Session| { .service(web::resource("/").to(|ses: Session| {
let _ = ses.set("counter", 100); async move {
"test" let _ = ses.set("counter", 100);
"test"
}
})) }))
.service(web::resource("/test/").to(|ses: Session| { .service(web::resource("/test/").to(|ses: Session| {
let val: usize = ses.get("counter").unwrap().unwrap(); async move {
format!("counter: {}", val) let val: usize = ses.get("counter").unwrap().unwrap();
format!("counter: {}", val)
}
})), })),
) )
.await; .await;

View File

@ -5,42 +5,42 @@ use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, t
use futures::{future, Future}; use futures::{future, Future};
#[get("/test")] #[get("/test")]
fn test() -> impl Responder { async fn test() -> impl Responder {
HttpResponse::Ok() HttpResponse::Ok()
} }
#[put("/test")] #[put("/test")]
fn put_test() -> impl Responder { async fn put_test() -> impl Responder {
HttpResponse::Created() HttpResponse::Created()
} }
#[patch("/test")] #[patch("/test")]
fn patch_test() -> impl Responder { async fn patch_test() -> impl Responder {
HttpResponse::Ok() HttpResponse::Ok()
} }
#[post("/test")] #[post("/test")]
fn post_test() -> impl Responder { async fn post_test() -> impl Responder {
HttpResponse::NoContent() HttpResponse::NoContent()
} }
#[head("/test")] #[head("/test")]
fn head_test() -> impl Responder { async fn head_test() -> impl Responder {
HttpResponse::Ok() HttpResponse::Ok()
} }
#[connect("/test")] #[connect("/test")]
fn connect_test() -> impl Responder { async fn connect_test() -> impl Responder {
HttpResponse::Ok() HttpResponse::Ok()
} }
#[options("/test")] #[options("/test")]
fn options_test() -> impl Responder { async fn options_test() -> impl Responder {
HttpResponse::Ok() HttpResponse::Ok()
} }
#[trace("/test")] #[trace("/test")]
fn trace_test() -> impl Responder { async fn trace_test() -> impl Responder {
HttpResponse::Ok() HttpResponse::Ok()
} }
@ -55,17 +55,17 @@ fn auto_sync() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> {
} }
#[put("/test/{param}")] #[put("/test/{param}")]
fn put_param_test(_: Path<String>) -> impl Responder { async fn put_param_test(_: Path<String>) -> impl Responder {
HttpResponse::Created() HttpResponse::Created()
} }
#[delete("/test/{param}")] #[delete("/test/{param}")]
fn delete_param_test(_: Path<String>) -> impl Responder { async fn delete_param_test(_: Path<String>) -> impl Responder {
HttpResponse::NoContent() HttpResponse::NoContent()
} }
#[get("/test/{param}")] #[get("/test/{param}")]
fn get_param_test(_: Path<String>) -> impl Responder { async fn get_param_test(_: Path<String>) -> impl Responder {
HttpResponse::Ok() HttpResponse::Ok()
} }

View File

@ -115,14 +115,14 @@ fn test_form() {
fn test_timeout() { fn test_timeout() {
block_on(async { block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route( HttpService::new(App::new().service(web::resource("/").route(web::to(
web::to_async(|| { || {
async { async {
tokio_timer::delay_for(Duration::from_millis(200)).await; tokio_timer::delay_for(Duration::from_millis(200)).await;
Ok::<_, Error>(HttpResponse::Ok().body(STR)) Ok::<_, Error>(HttpResponse::Ok().body(STR))
} }
}), },
))) ))))
}); });
let connector = awc::Connector::new() let connector = awc::Connector::new()
@ -149,14 +149,14 @@ fn test_timeout() {
fn test_timeout_override() { fn test_timeout_override() {
block_on(async { block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route( HttpService::new(App::new().service(web::resource("/").route(web::to(
web::to_async(|| { || {
async { async {
tokio_timer::delay_for(Duration::from_millis(200)).await; tokio_timer::delay_for(Duration::from_millis(200)).await;
Ok::<_, Error>(HttpResponse::Ok().body(STR)) Ok::<_, Error>(HttpResponse::Ok().body(STR))
} }
}), },
))) ))))
}); });
let client = awc::Client::build() let client = awc::Client::build()
@ -693,12 +693,9 @@ fn test_client_brotli_encoding() {
#[test] #[test]
fn test_client_cookie_handling() { fn test_client_cookie_handling() {
use std::io::{Error as IoError, ErrorKind};
block_on(async { block_on(async {
fn err() -> Error {
use std::io::{Error as IoError, ErrorKind};
// stub some generic error
Error::from(IoError::from(ErrorKind::NotFound))
}
let cookie1 = Cookie::build("cookie1", "value1").finish(); let cookie1 = Cookie::build("cookie1", "value1").finish();
let cookie2 = Cookie::build("cookie2", "value2") let cookie2 = Cookie::build("cookie2", "value2")
.domain("www.example.org") .domain("www.example.org")
@ -717,31 +714,45 @@ fn test_client_cookie_handling() {
HttpService::new(App::new().route( HttpService::new(App::new().route(
"/", "/",
web::to(move |req: HttpRequest| { web::to(move |req: HttpRequest| {
// Check cookies were sent correctly let cookie1 = cookie1.clone();
req.cookie("cookie1") let cookie2 = cookie2.clone();
.ok_or_else(err)
.and_then(|c1| { async move {
if c1.value() == "value1" { // Check cookies were sent correctly
Ok(()) let res: Result<(), Error> = req
} else { .cookie("cookie1")
Err(err()) .ok_or(())
} .and_then(|c1| {
}) if c1.value() == "value1" {
.and_then(|()| req.cookie("cookie2").ok_or_else(err)) Ok(())
.and_then(|c2| { } else {
if c2.value() == "value2" { Err(())
Ok(()) }
} else { })
Err(err()) .and_then(|()| req.cookie("cookie2").ok_or(()))
} .and_then(|c2| {
}) if c2.value() == "value2" {
// Send some cookies back Ok(())
.map(|_| { } else {
HttpResponse::Ok() Err(())
.cookie(cookie1.clone()) }
.cookie(cookie2.clone()) })
.finish() .map_err(|_| {
}) Error::from(IoError::from(ErrorKind::NotFound))
});
if let Err(e) = res {
Err(e)
} else {
// Send some cookies back
Ok::<_, Error>(
HttpResponse::Ok()
.cookie(cookie1)
.cookie(cookie2)
.finish(),
)
}
}
}), }),
)) ))
}); });

View File

@ -35,7 +35,7 @@ pub use actix_testing::*;
/// let mut srv = TestServer::start( /// let mut srv = TestServer::start(
/// || HttpService::new( /// || HttpService::new(
/// App::new().service( /// App::new().service(
/// web::resource("/").to_async(my_handler)) /// web::resource("/").to(my_handler))
/// ) /// )
/// ); /// );
/// ///