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

use actix_rt::test for test setup

This commit is contained in:
Nikolay Kim 2019-11-26 11:25:50 +06:00
parent c1c44a7dd6
commit 4dc31aac93
80 changed files with 6502 additions and 7237 deletions

View File

@ -36,9 +36,12 @@ before_script:
script: script:
- cargo update - cargo update
- cargo check --all --no-default-features - cargo check --all --no-default-features
- cargo test --all-features --all -- --nocapture - |
# - cd actix-http; cargo test --no-default-features --features="rustls" -- --nocapture; cd .. if [[ "$TRAVIS_RUST_VERSION" == "stable" || "$TRAVIS_RUST_VERSION" == "beta" ]]; then
# - cd awc; cargo test --no-default-features --features="rustls" -- --nocapture; cd .. cargo test --all-features --all -- --nocapture
cd actix-http; cargo test --no-default-features --features="rustls" -- --nocapture; cd ..
cd awc; cargo test --no-default-features --features="rustls" -- --nocapture; cd ..
fi
# Upload docs # Upload docs
after_success: after_success:

View File

@ -66,7 +66,7 @@ fail = ["actix-http/fail"]
openssl = ["open-ssl", "actix-server/openssl", "awc/openssl"] openssl = ["open-ssl", "actix-server/openssl", "awc/openssl"]
# rustls # rustls
# rustls = ["rust-tls", "actix-server/rustls", "awc/rustls"] rustls = ["rust-tls", "actix-server/rustls", "awc/rustls"]
[dependencies] [dependencies]
actix-codec = "0.2.0-alpha.1" actix-codec = "0.2.0-alpha.1"
@ -110,7 +110,6 @@ actix-http-test = "0.3.0-alpha.1"
rand = "0.7" rand = "0.7"
env_logger = "0.6" env_logger = "0.6"
serde_derive = "1.0" serde_derive = "1.0"
tokio-timer = "0.3.0-alpha.6"
brotli2 = "0.3.2" brotli2 = "0.3.2"
flate2 = "1.0.2" flate2 = "1.0.2"
@ -135,19 +134,9 @@ awc = { path = "awc" }
actix-codec = { git = "https://github.com/actix/actix-net.git" } actix-codec = { git = "https://github.com/actix/actix-net.git" }
actix-connect = { git = "https://github.com/actix/actix-net.git" } actix-connect = { git = "https://github.com/actix/actix-net.git" }
actix-rt = { git = "https://github.com/actix/actix-net.git" } actix-rt = { git = "https://github.com/actix/actix-net.git" }
actix-macros = { git = "https://github.com/actix/actix-net.git" }
actix-server = { git = "https://github.com/actix/actix-net.git" } actix-server = { git = "https://github.com/actix/actix-net.git" }
actix-server-config = { git = "https://github.com/actix/actix-net.git" } actix-server-config = { git = "https://github.com/actix/actix-net.git" }
actix-service = { git = "https://github.com/actix/actix-net.git" } actix-service = { git = "https://github.com/actix/actix-net.git" }
actix-testing = { git = "https://github.com/actix/actix-net.git" } actix-testing = { git = "https://github.com/actix/actix-net.git" }
actix-threadpool = { git = "https://github.com/actix/actix-net.git" }
actix-utils = { git = "https://github.com/actix/actix-net.git" } actix-utils = { git = "https://github.com/actix/actix-net.git" }
# actix-codec = { path = "../actix-net/actix-codec" }
# actix-connect = { path = "../actix-net/actix-connect" }
# actix-rt = { path = "../actix-net/actix-rt" }
# actix-server = { path = "../actix-net/actix-server" }
# actix-server-config = { path = "../actix-net/actix-server-config" }
# actix-service = { path = "../actix-net/actix-service" }
# actix-testing = { path = "../actix-net/actix-testing" }
# actix-threadpool = { path = "../actix-net/actix-threadpool" }
# actix-utils = { path = "../actix-net/actix-utils" }

View File

@ -21,3 +21,6 @@ actix-web = "2.0.0-alpha.1"
actix-service = "1.0.0-alpha.1" actix-service = "1.0.0-alpha.1"
derive_more = "0.99.2" derive_more = "0.99.2"
futures = "0.3.1" futures = "0.3.1"
[dev-dependencies]
actix-rt = "1.0.0-alpha.1"

View File

@ -814,19 +814,18 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use actix_service::{service_fn2, Transform}; use actix_service::{service_fn2, Transform};
use actix_web::test::{self, block_on, TestRequest}; use actix_web::test::{self, TestRequest};
use super::*; use super::*;
#[test] #[actix_rt::test]
#[should_panic(expected = "Credentials are allowed, but the Origin is set to")] #[should_panic(expected = "Credentials are allowed, but the Origin is set to")]
fn cors_validates_illegal_allow_credentials() { async fn cors_validates_illegal_allow_credentials() {
let _cors = Cors::new().supports_credentials().send_wildcard().finish(); let _cors = Cors::new().supports_credentials().send_wildcard().finish();
} }
#[test] #[actix_rt::test]
fn validate_origin_allows_all_origins() { async fn validate_origin_allows_all_origins() {
block_on(async {
let mut cors = Cors::new() let mut cors = Cors::new()
.finish() .finish()
.new_transform(test::ok_service()) .new_transform(test::ok_service())
@ -837,12 +836,10 @@ mod tests {
let resp = test::call_service(&mut cors, req).await; let resp = test::call_service(&mut cors, req).await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn default() { async fn default() {
block_on(async {
let mut cors = Cors::default() let mut cors = Cors::default()
.new_transform(test::ok_service()) .new_transform(test::ok_service())
.await .await
@ -852,12 +849,10 @@ mod tests {
let resp = test::call_service(&mut cors, req).await; let resp = test::call_service(&mut cors, req).await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_preflight() { async fn test_preflight() {
block_on(async {
let mut cors = Cors::new() let mut cors = Cors::new()
.send_wildcard() .send_wildcard()
.max_age(3600) .max_age(3600)
@ -944,12 +939,11 @@ mod tests {
let resp = test::call_service(&mut cors, req).await; let resp = test::call_service(&mut cors, req).await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
// #[test] // #[actix_rt::test]
// #[should_panic(expected = "MissingOrigin")] // #[should_panic(expected = "MissingOrigin")]
// fn test_validate_missing_origin() { // async fn test_validate_missing_origin() {
// let cors = Cors::build() // let cors = Cors::build()
// .allowed_origin("https://www.example.com") // .allowed_origin("https://www.example.com")
// .finish(); // .finish();
@ -957,10 +951,9 @@ mod tests {
// cors.start(&req).unwrap(); // cors.start(&req).unwrap();
// } // }
#[test] #[actix_rt::test]
#[should_panic(expected = "OriginNotAllowed")] #[should_panic(expected = "OriginNotAllowed")]
fn test_validate_not_allowed_origin() { async fn test_validate_not_allowed_origin() {
block_on(async {
let cors = Cors::new() let cors = Cors::new()
.allowed_origin("https://www.example.com") .allowed_origin("https://www.example.com")
.finish() .finish()
@ -974,12 +967,10 @@ mod tests {
cors.inner.validate_origin(req.head()).unwrap(); cors.inner.validate_origin(req.head()).unwrap();
cors.inner.validate_allowed_method(req.head()).unwrap(); cors.inner.validate_allowed_method(req.head()).unwrap();
cors.inner.validate_allowed_headers(req.head()).unwrap(); cors.inner.validate_allowed_headers(req.head()).unwrap();
})
} }
#[test] #[actix_rt::test]
fn test_validate_origin() { async fn test_validate_origin() {
block_on(async {
let mut cors = Cors::new() let mut cors = Cors::new()
.allowed_origin("https://www.example.com") .allowed_origin("https://www.example.com")
.finish() .finish()
@ -993,12 +984,10 @@ mod tests {
let resp = test::call_service(&mut cors, req).await; let resp = test::call_service(&mut cors, req).await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_no_origin_response() { async fn test_no_origin_response() {
block_on(async {
let mut cors = Cors::new() let mut cors = Cors::new()
.disable_preflight() .disable_preflight()
.finish() .finish()
@ -1024,12 +1013,10 @@ mod tests {
.unwrap() .unwrap()
.as_bytes() .as_bytes()
); );
})
} }
#[test] #[actix_rt::test]
fn test_response() { async fn test_response() {
block_on(async {
let exposed_headers = vec![header::AUTHORIZATION, header::ACCEPT]; let exposed_headers = vec![header::AUTHORIZATION, header::ACCEPT];
let mut cors = Cors::new() let mut cors = Cors::new()
.send_wildcard() .send_wildcard()
@ -1126,12 +1113,10 @@ mod tests {
.unwrap(); .unwrap();
assert_eq!("https://www.example.com", origins_str); assert_eq!("https://www.example.com", origins_str);
})
} }
#[test] #[actix_rt::test]
fn test_multiple_origins() { async fn test_multiple_origins() {
block_on(async {
let mut cors = Cors::new() let mut cors = Cors::new()
.allowed_origin("https://example.com") .allowed_origin("https://example.com")
.allowed_origin("https://example.org") .allowed_origin("https://example.org")
@ -1166,12 +1151,10 @@ mod tests {
.unwrap() .unwrap()
.as_bytes() .as_bytes()
); );
})
} }
#[test] #[actix_rt::test]
fn test_multiple_origins_preflight() { async fn test_multiple_origins_preflight() {
block_on(async {
let mut cors = Cors::new() let mut cors = Cors::new()
.allowed_origin("https://example.com") .allowed_origin("https://example.com")
.allowed_origin("https://example.org") .allowed_origin("https://example.org")
@ -1208,6 +1191,5 @@ mod tests {
.unwrap() .unwrap()
.as_bytes() .as_bytes()
); );
})
} }
} }

View File

@ -32,4 +32,5 @@ percent-encoding = "2.1"
v_htmlescape = "0.4" v_htmlescape = "0.4"
[dev-dependencies] [dev-dependencies]
actix-rt = "1.0.0-alpha.1"
actix-web = { version = "2.0.0-alpha.1", features=["openssl"] } actix-web = { version = "2.0.0-alpha.1", features=["openssl"] }

View File

@ -12,7 +12,7 @@ use std::rc::Rc;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use std::{cmp, io}; use std::{cmp, io};
use actix_service::boxed::{self, BoxedNewService, BoxedService}; use actix_service::boxed::{self, BoxService, BoxServiceFactory};
use actix_service::{IntoServiceFactory, Service, ServiceFactory}; use actix_service::{IntoServiceFactory, Service, ServiceFactory};
use actix_web::dev::{ use actix_web::dev::{
AppService, HttpServiceFactory, Payload, ResourceDef, ServiceRequest, AppService, HttpServiceFactory, Payload, ResourceDef, ServiceRequest,
@ -39,8 +39,8 @@ use self::error::{FilesError, UriSegmentError};
pub use crate::named::NamedFile; pub use crate::named::NamedFile;
pub use crate::range::HttpRange; pub use crate::range::HttpRange;
type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>; type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
/// Return the MIME type associated with a filename extension (case-insensitive). /// Return the MIME type associated with a filename extension (case-insensitive).
/// If `ext` is empty or no associated type for the extension was found, returns /// If `ext` is empty or no associated type for the extension was found, returns
@ -644,11 +644,11 @@ mod tests {
}; };
use actix_web::http::{Method, StatusCode}; use actix_web::http::{Method, StatusCode};
use actix_web::middleware::Compress; use actix_web::middleware::Compress;
use actix_web::test::{self, block_on, TestRequest}; use actix_web::test::{self, TestRequest};
use actix_web::{App, Responder}; use actix_web::{App, Responder};
#[test] #[actix_rt::test]
fn test_file_extension_to_mime() { async fn test_file_extension_to_mime() {
let m = file_extension_to_mime("jpg"); let m = file_extension_to_mime("jpg");
assert_eq!(m, mime::IMAGE_JPEG); assert_eq!(m, mime::IMAGE_JPEG);
@ -659,9 +659,8 @@ mod tests {
assert_eq!(m, mime::APPLICATION_OCTET_STREAM); assert_eq!(m, mime::APPLICATION_OCTET_STREAM);
} }
#[test] #[actix_rt::test]
fn test_if_modified_since_without_if_none_match() { async fn test_if_modified_since_without_if_none_match() {
block_on(async {
let file = NamedFile::open("Cargo.toml").unwrap(); let file = NamedFile::open("Cargo.toml").unwrap();
let since = let since =
header::HttpDate::from(SystemTime::now().add(Duration::from_secs(60))); header::HttpDate::from(SystemTime::now().add(Duration::from_secs(60)));
@ -671,12 +670,10 @@ mod tests {
.to_http_request(); .to_http_request();
let resp = file.respond_to(&req).await.unwrap(); let resp = file.respond_to(&req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_MODIFIED); assert_eq!(resp.status(), StatusCode::NOT_MODIFIED);
})
} }
#[test] #[actix_rt::test]
fn test_if_modified_since_with_if_none_match() { async fn test_if_modified_since_with_if_none_match() {
block_on(async {
let file = NamedFile::open("Cargo.toml").unwrap(); let file = NamedFile::open("Cargo.toml").unwrap();
let since = let since =
header::HttpDate::from(SystemTime::now().add(Duration::from_secs(60))); header::HttpDate::from(SystemTime::now().add(Duration::from_secs(60)));
@ -687,12 +684,10 @@ mod tests {
.to_http_request(); .to_http_request();
let resp = file.respond_to(&req).await.unwrap(); let resp = file.respond_to(&req).await.unwrap();
assert_ne!(resp.status(), StatusCode::NOT_MODIFIED); assert_ne!(resp.status(), StatusCode::NOT_MODIFIED);
})
} }
#[test] #[actix_rt::test]
fn test_named_file_text() { async fn test_named_file_text() {
block_on(async {
assert!(NamedFile::open("test--").is_err()); assert!(NamedFile::open("test--").is_err());
let mut file = NamedFile::open("Cargo.toml").unwrap(); let mut file = NamedFile::open("Cargo.toml").unwrap();
{ {
@ -713,12 +708,10 @@ mod tests {
resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
"inline; filename=\"Cargo.toml\"" "inline; filename=\"Cargo.toml\""
); );
})
} }
#[test] #[actix_rt::test]
fn test_named_file_content_disposition() { async fn test_named_file_content_disposition() {
block_on(async {
assert!(NamedFile::open("test--").is_err()); assert!(NamedFile::open("test--").is_err());
let mut file = NamedFile::open("Cargo.toml").unwrap(); let mut file = NamedFile::open("Cargo.toml").unwrap();
{ {
@ -742,12 +735,10 @@ mod tests {
let req = TestRequest::default().to_http_request(); let req = TestRequest::default().to_http_request();
let resp = file.respond_to(&req).await.unwrap(); let resp = file.respond_to(&req).await.unwrap();
assert!(resp.headers().get(header::CONTENT_DISPOSITION).is_none()); assert!(resp.headers().get(header::CONTENT_DISPOSITION).is_none());
})
} }
#[test] #[actix_rt::test]
fn test_named_file_non_ascii_file_name() { async fn test_named_file_non_ascii_file_name() {
block_on(async {
let mut file = let mut file =
NamedFile::from_file(File::open("Cargo.toml").unwrap(), "貨物.toml") NamedFile::from_file(File::open("Cargo.toml").unwrap(), "貨物.toml")
.unwrap(); .unwrap();
@ -769,12 +760,10 @@ mod tests {
resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
"inline; filename=\"貨物.toml\"; filename*=UTF-8''%E8%B2%A8%E7%89%A9.toml" "inline; filename=\"貨物.toml\"; filename*=UTF-8''%E8%B2%A8%E7%89%A9.toml"
); );
})
} }
#[test] #[actix_rt::test]
fn test_named_file_set_content_type() { async fn test_named_file_set_content_type() {
block_on(async {
let mut file = NamedFile::open("Cargo.toml") let mut file = NamedFile::open("Cargo.toml")
.unwrap() .unwrap()
.set_content_type(mime::TEXT_XML); .set_content_type(mime::TEXT_XML);
@ -796,12 +785,10 @@ mod tests {
resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
"inline; filename=\"Cargo.toml\"" "inline; filename=\"Cargo.toml\""
); );
})
} }
#[test] #[actix_rt::test]
fn test_named_file_image() { async fn test_named_file_image() {
block_on(async {
let mut file = NamedFile::open("tests/test.png").unwrap(); let mut file = NamedFile::open("tests/test.png").unwrap();
{ {
file.file(); file.file();
@ -821,12 +808,10 @@ mod tests {
resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
"inline; filename=\"test.png\"" "inline; filename=\"test.png\""
); );
})
} }
#[test] #[actix_rt::test]
fn test_named_file_image_attachment() { async fn test_named_file_image_attachment() {
block_on(async {
let cd = ContentDisposition { let cd = ContentDisposition {
disposition: DispositionType::Attachment, disposition: DispositionType::Attachment,
parameters: vec![DispositionParam::Filename(String::from("test.png"))], parameters: vec![DispositionParam::Filename(String::from("test.png"))],
@ -852,12 +837,10 @@ mod tests {
resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
"attachment; filename=\"test.png\"" "attachment; filename=\"test.png\""
); );
})
} }
#[test] #[actix_rt::test]
fn test_named_file_binary() { async fn test_named_file_binary() {
block_on(async {
let mut file = NamedFile::open("tests/test.binary").unwrap(); let mut file = NamedFile::open("tests/test.binary").unwrap();
{ {
file.file(); file.file();
@ -877,12 +860,10 @@ mod tests {
resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
"attachment; filename=\"test.binary\"" "attachment; filename=\"test.binary\""
); );
})
} }
#[test] #[actix_rt::test]
fn test_named_file_status_code_text() { async fn test_named_file_status_code_text() {
block_on(async {
let mut file = NamedFile::open("Cargo.toml") let mut file = NamedFile::open("Cargo.toml")
.unwrap() .unwrap()
.set_status_code(StatusCode::NOT_FOUND); .set_status_code(StatusCode::NOT_FOUND);
@ -905,12 +886,10 @@ mod tests {
"inline; filename=\"Cargo.toml\"" "inline; filename=\"Cargo.toml\""
); );
assert_eq!(resp.status(), StatusCode::NOT_FOUND); assert_eq!(resp.status(), StatusCode::NOT_FOUND);
})
} }
#[test] #[actix_rt::test]
fn test_mime_override() { async fn test_mime_override() {
block_on(async {
fn all_attachment(_: &mime::Name) -> DispositionType { fn all_attachment(_: &mime::Name) -> DispositionType {
DispositionType::Attachment DispositionType::Attachment
} }
@ -936,12 +915,10 @@ mod tests {
.to_str() .to_str()
.expect("Convert CONTENT_DISPOSITION to str"); .expect("Convert CONTENT_DISPOSITION to str");
assert_eq!(content_disposition, "attachment; filename=\"Cargo.toml\""); assert_eq!(content_disposition, "attachment; filename=\"Cargo.toml\"");
})
} }
#[test] #[actix_rt::test]
fn test_named_file_ranges_status_code() { async fn test_named_file_ranges_status_code() {
block_on(async {
let mut srv = test::init_service( let mut srv = test::init_service(
App::new().service(Files::new("/test", ".").index_file("Cargo.toml")), App::new().service(Files::new("/test", ".").index_file("Cargo.toml")),
) )
@ -963,15 +940,12 @@ mod tests {
let response = test::call_service(&mut srv, request).await; let response = test::call_service(&mut srv, request).await;
assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE); assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE);
})
} }
#[test] #[actix_rt::test]
fn test_named_file_content_range_headers() { async fn test_named_file_content_range_headers() {
block_on(async {
let mut srv = test::init_service( let mut srv = test::init_service(
App::new() App::new().service(Files::new("/test", ".").index_file("tests/test.binary")),
.service(Files::new("/test", ".").index_file("tests/test.binary")),
) )
.await; .await;
@ -1006,17 +980,14 @@ mod tests {
.unwrap(); .unwrap();
assert_eq!(contentrange, "bytes */100"); assert_eq!(contentrange, "bytes */100");
})
} }
#[test] #[actix_rt::test]
fn test_named_file_content_length_headers() { async fn test_named_file_content_length_headers() {
block_on(async {
// use actix_web::body::{MessageBody, ResponseBody}; // use actix_web::body::{MessageBody, ResponseBody};
let mut srv = test::init_service( let mut srv = test::init_service(
App::new() App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
.service(Files::new("test", ".").index_file("tests/test.binary")),
) )
.await; .await;
@ -1078,15 +1049,12 @@ mod tests {
let bytes = test::read_body(response).await; let bytes = test::read_body(response).await;
let data = Bytes::from(fs::read("tests/test.binary").unwrap()); let data = Bytes::from(fs::read("tests/test.binary").unwrap());
assert_eq!(bytes, data); assert_eq!(bytes, data);
})
} }
#[test] #[actix_rt::test]
fn test_head_content_length_headers() { async fn test_head_content_length_headers() {
block_on(async {
let mut srv = test::init_service( let mut srv = test::init_service(
App::new() App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
.service(Files::new("test", ".").index_file("tests/test.binary")),
) )
.await; .await;
@ -1105,12 +1073,10 @@ mod tests {
// .to_str() // .to_str()
// .unwrap(); // .unwrap();
// assert_eq!(contentlength, "100"); // assert_eq!(contentlength, "100");
})
} }
#[test] #[actix_rt::test]
fn test_static_files_with_spaces() { async fn test_static_files_with_spaces() {
block_on(async {
let mut srv = test::init_service( let mut srv = test::init_service(
App::new().service(Files::new("/", ".").index_file("Cargo.toml")), App::new().service(Files::new("/", ".").index_file("Cargo.toml")),
) )
@ -1124,14 +1090,11 @@ mod tests {
let bytes = test::read_body(response).await; let bytes = test::read_body(response).await;
let data = Bytes::from(fs::read("tests/test space.binary").unwrap()); let data = Bytes::from(fs::read("tests/test space.binary").unwrap());
assert_eq!(bytes, data); assert_eq!(bytes, data);
})
} }
#[test] #[actix_rt::test]
fn test_files_not_allowed() { async fn test_files_not_allowed() {
block_on(async { let mut srv = test::init_service(App::new().service(Files::new("/", "."))).await;
let mut srv =
test::init_service(App::new().service(Files::new("/", "."))).await;
let req = TestRequest::default() let req = TestRequest::default()
.uri("/Cargo.toml") .uri("/Cargo.toml")
@ -1141,20 +1104,17 @@ mod tests {
let resp = test::call_service(&mut srv, req).await; let resp = test::call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
let mut srv = let mut srv = test::init_service(App::new().service(Files::new("/", "."))).await;
test::init_service(App::new().service(Files::new("/", "."))).await;
let req = TestRequest::default() let req = TestRequest::default()
.method(Method::PUT) .method(Method::PUT)
.uri("/Cargo.toml") .uri("/Cargo.toml")
.to_request(); .to_request();
let resp = test::call_service(&mut srv, req).await; let resp = test::call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
})
} }
#[test] #[actix_rt::test]
fn test_files_guards() { async fn test_files_guards() {
block_on(async {
let mut srv = test::init_service( let mut srv = test::init_service(
App::new().service(Files::new("/", ".").use_guards(guard::Post())), App::new().service(Files::new("/", ".").use_guards(guard::Post())),
) )
@ -1167,14 +1127,11 @@ mod tests {
let resp = test::call_service(&mut srv, req).await; let resp = test::call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_named_file_content_encoding() { async fn test_named_file_content_encoding() {
block_on(async { let mut srv = test::init_service(App::new().wrap(Compress::default()).service(
let mut srv =
test::init_service(App::new().wrap(Compress::default()).service(
web::resource("/").to(|| { web::resource("/").to(|| {
async { async {
NamedFile::open("Cargo.toml") NamedFile::open("Cargo.toml")
@ -1192,14 +1149,11 @@ mod tests {
let res = test::call_service(&mut srv, request).await; let res = test::call_service(&mut srv, request).await;
assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.status(), StatusCode::OK);
assert!(!res.headers().contains_key(header::CONTENT_ENCODING)); assert!(!res.headers().contains_key(header::CONTENT_ENCODING));
})
} }
#[test] #[actix_rt::test]
fn test_named_file_content_encoding_gzip() { async fn test_named_file_content_encoding_gzip() {
block_on(async { let mut srv = test::init_service(App::new().wrap(Compress::default()).service(
let mut srv =
test::init_service(App::new().wrap(Compress::default()).service(
web::resource("/").to(|| { web::resource("/").to(|| {
async { async {
NamedFile::open("Cargo.toml") NamedFile::open("Cargo.toml")
@ -1224,22 +1178,18 @@ mod tests {
.unwrap(), .unwrap(),
"gzip" "gzip"
); );
})
} }
#[test] #[actix_rt::test]
fn test_named_file_allowed_method() { async fn test_named_file_allowed_method() {
block_on(async {
let req = TestRequest::default().method(Method::GET).to_http_request(); let req = TestRequest::default().method(Method::GET).to_http_request();
let file = NamedFile::open("Cargo.toml").unwrap(); let file = NamedFile::open("Cargo.toml").unwrap();
let resp = file.respond_to(&req).await.unwrap(); let resp = file.respond_to(&req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_static_files() { async fn test_static_files() {
block_on(async {
let mut srv = test::init_service( let mut srv = test::init_service(
App::new().service(Files::new("/", ".").show_files_listing()), App::new().service(Files::new("/", ".").show_files_listing()),
) )
@ -1249,8 +1199,7 @@ mod tests {
let resp = test::call_service(&mut srv, req).await; let resp = test::call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND); assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let mut srv = let mut srv = test::init_service(App::new().service(Files::new("/", "."))).await;
test::init_service(App::new().service(Files::new("/", "."))).await;
let req = TestRequest::default().to_request(); let req = TestRequest::default().to_request();
let resp = test::call_service(&mut srv, req).await; let resp = test::call_service(&mut srv, req).await;
@ -1269,12 +1218,10 @@ mod tests {
let bytes = test::read_body(resp).await; let bytes = test::read_body(resp).await;
assert!(format!("{:?}", bytes).contains("/tests/test.png")); assert!(format!("{:?}", bytes).contains("/tests/test.png"));
})
} }
#[test] #[actix_rt::test]
fn test_redirect_to_slash_directory() { async fn test_redirect_to_slash_directory() {
block_on(async {
// should not redirect if no index // should not redirect if no index
let mut srv = test::init_service( let mut srv = test::init_service(
App::new().service(Files::new("/", ".").redirect_to_slash_directory()), App::new().service(Files::new("/", ".").redirect_to_slash_directory()),
@ -1301,18 +1248,16 @@ mod tests {
let req = TestRequest::with_uri("/not_existing").to_request(); let req = TestRequest::with_uri("/not_existing").to_request();
let resp = test::call_service(&mut srv, req).await; let resp = test::call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND); assert_eq!(resp.status(), StatusCode::NOT_FOUND);
})
} }
#[test] #[actix_rt::test]
fn test_static_files_bad_directory() { async fn test_static_files_bad_directory() {
let _st: Files = Files::new("/", "missing"); let _st: Files = Files::new("/", "missing");
let _st: Files = Files::new("/", "Cargo.toml"); let _st: Files = Files::new("/", "Cargo.toml");
} }
#[test] #[actix_rt::test]
fn test_default_handler_file_missing() { async fn test_default_handler_file_missing() {
block_on(async {
let mut st = Files::new("/", ".") let mut st = Files::new("/", ".")
.default_handler(|req: ServiceRequest| { .default_handler(|req: ServiceRequest| {
ok(req.into_response(HttpResponse::Ok().body("default content"))) ok(req.into_response(HttpResponse::Ok().body("default content")))
@ -1326,11 +1271,10 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
let bytes = test::read_body(resp).await; let bytes = test::read_body(resp).await;
assert_eq!(bytes, Bytes::from_static(b"default content")); assert_eq!(bytes, Bytes::from_static(b"default content"));
})
} }
// #[test] // #[actix_rt::test]
// fn test_serve_index() { // async fn test_serve_index() {
// let st = Files::new(".").index_file("test.binary"); // let st = Files::new(".").index_file("test.binary");
// let req = TestRequest::default().uri("/tests").finish(); // let req = TestRequest::default().uri("/tests").finish();
@ -1375,8 +1319,8 @@ mod tests {
// assert_eq!(resp.status(), StatusCode::NOT_FOUND); // assert_eq!(resp.status(), StatusCode::NOT_FOUND);
// } // }
// #[test] // #[actix_rt::test]
// fn test_serve_index_nested() { // async fn test_serve_index_nested() {
// let st = Files::new(".").index_file("mod.rs"); // let st = Files::new(".").index_file("mod.rs");
// let req = TestRequest::default().uri("/src/client").finish(); // let req = TestRequest::default().uri("/src/client").finish();
// let resp = st.handle(&req).respond_to(&req).unwrap(); // let resp = st.handle(&req).respond_to(&req).unwrap();
@ -1392,7 +1336,7 @@ mod tests {
// ); // );
// } // }
// #[test] // #[actix_rt::test]
// fn integration_serve_index() { // fn integration_serve_index() {
// let mut srv = test::TestServer::with_factory(|| { // let mut srv = test::TestServer::with_factory(|| {
// App::new().handler( // App::new().handler(
@ -1425,7 +1369,7 @@ mod tests {
// assert_eq!(response.status(), StatusCode::NOT_FOUND); // assert_eq!(response.status(), StatusCode::NOT_FOUND);
// } // }
// #[test] // #[actix_rt::test]
// fn integration_percent_encoded() { // fn integration_percent_encoded() {
// let mut srv = test::TestServer::with_factory(|| { // let mut srv = test::TestServer::with_factory(|| {
// App::new().handler( // App::new().handler(
@ -1443,8 +1387,8 @@ mod tests {
// assert_eq!(response.status(), StatusCode::OK); // assert_eq!(response.status(), StatusCode::OK);
// } // }
#[test] #[actix_rt::test]
fn test_path_buf() { async fn test_path_buf() {
assert_eq!( assert_eq!(
PathBufWrp::get_pathbuf("/test/.tt").map(|t| t.0), PathBufWrp::get_pathbuf("/test/.tt").map(|t| t.0),
Err(UriSegmentError::BadStart('.')) Err(UriSegmentError::BadStart('.'))

View File

@ -7,7 +7,6 @@ use actix_http::http::header::{Header, HeaderName, IntoHeaderValue};
use actix_http::http::{HttpTryFrom, Method, Uri, Version}; use actix_http::http::{HttpTryFrom, Method, Uri, Version};
use actix_http::test::{TestBuffer, TestRequest as HttpTestRequest}; use actix_http::test::{TestBuffer, TestRequest as HttpTestRequest};
use actix_router::{Path, Url}; use actix_router::{Path, Url};
use actix_rt::Runtime;
use crate::{FramedRequest, State}; use crate::{FramedRequest, State};
@ -119,13 +118,12 @@ impl<S> TestRequest<S> {
} }
/// This method generates `FramedRequest` instance and executes async handler /// This method generates `FramedRequest` instance and executes async handler
pub fn run<F, R, I, E>(self, f: F) -> Result<I, E> pub async fn run<F, R, I, E>(self, f: F) -> Result<I, E>
where where
F: FnOnce(FramedRequest<TestBuffer, S>) -> R, F: FnOnce(FramedRequest<TestBuffer, S>) -> R,
R: Future<Output = Result<I, E>>, R: Future<Output = Result<I, E>>,
{ {
let mut rt = Runtime::new().unwrap(); f(self.finish()).await
rt.block_on(f(self.finish()))
} }
} }

View File

@ -1,6 +1,6 @@
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_http::{body, http::StatusCode, ws, Error, HttpService, Response}; use actix_http::{body, http::StatusCode, ws, Error, HttpService, Response};
use actix_http_test::{block_on, TestServer}; use actix_http_test::TestServer;
use actix_service::{pipeline_factory, IntoServiceFactory, ServiceFactory}; use actix_service::{pipeline_factory, IntoServiceFactory, ServiceFactory};
use actix_utils::framed::FramedTransport; use actix_utils::framed::FramedTransport;
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
@ -38,14 +38,12 @@ async fn service(msg: ws::Frame) -> Result<ws::Message, Error> {
Ok(msg) Ok(msg)
} }
#[test] #[actix_rt::test]
fn test_simple() { async fn test_simple() {
block_on(async {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.upgrade( .upgrade(
FramedApp::new() FramedApp::new().service(FramedRoute::get("/index.html").to(ws_service)),
.service(FramedRoute::get("/index.html").to(ws_service)),
) )
.finish(|_| future::ok::<_, Error>(Response::NotFound())) .finish(|_| future::ok::<_, Error>(Response::NotFound()))
}); });
@ -91,12 +89,10 @@ fn test_simple() {
item.unwrap().unwrap(), item.unwrap().unwrap(),
ws::Frame::Close(Some(ws::CloseCode::Normal.into())) ws::Frame::Close(Some(ws::CloseCode::Normal.into()))
); );
})
} }
#[test] #[actix_rt::test]
fn test_service() { async fn test_service() {
block_on(async {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
pipeline_factory(actix_http::h1::OneRequest::new().map_err(|_| ())).and_then( pipeline_factory(actix_http::h1::OneRequest::new().map_err(|_| ())).and_then(
pipeline_factory( pipeline_factory(
@ -159,5 +155,4 @@ fn test_service() {
item.unwrap().unwrap(), item.unwrap().unwrap(),
ws::Frame::Close(Some(ws::CloseCode::Normal.into())) ws::Frame::Close(Some(ws::CloseCode::Normal.into()))
); );
})
} }

View File

@ -29,7 +29,7 @@ default = []
openssl = ["open-ssl", "actix-connect/openssl", "tokio-openssl"] openssl = ["open-ssl", "actix-connect/openssl", "tokio-openssl"]
# rustls support # rustls support
# rustls = ["rust-tls", "webpki-roots", "actix-connect/rustls"] rustls = ["rust-tls", "webpki-roots", "actix-connect/rustls"]
# brotli encoding, requires c compiler # brotli encoding, requires c compiler
brotli = ["brotli2"] brotli = ["brotli2"]
@ -52,6 +52,7 @@ actix-codec = "0.2.0-alpha.1"
actix-connect = "1.0.0-alpha.1" actix-connect = "1.0.0-alpha.1"
actix-utils = "0.5.0-alpha.1" actix-utils = "0.5.0-alpha.1"
actix-server-config = "0.3.0-alpha.1" actix-server-config = "0.3.0-alpha.1"
actix-rt = "1.0.0-alpha.1"
actix-threadpool = "0.2.0-alpha.1" actix-threadpool = "0.2.0-alpha.1"
base64 = "0.10" base64 = "0.10"
@ -83,11 +84,7 @@ slab = "0.4"
serde_urlencoded = "0.6.1" serde_urlencoded = "0.6.1"
time = "0.1.42" time = "0.1.42"
tokio = "=0.2.0-alpha.6"
tokio-io = "=0.2.0-alpha.6"
tokio-net = "=0.2.0-alpha.6" tokio-net = "=0.2.0-alpha.6"
tokio-timer = "0.3.0-alpha.6"
tokio-executor = "=0.2.0-alpha.6"
trust-dns-resolver = { version="0.18.0-alpha.1", default-features = false } trust-dns-resolver = { version="0.18.0-alpha.1", default-features = false }
# for secure cookie # for secure cookie
@ -106,8 +103,7 @@ rust-tls = { version = "0.16.0", package="rustls", optional = true }
webpki-roots = { version = "0.18", optional = true } webpki-roots = { version = "0.18", optional = true }
[dev-dependencies] [dev-dependencies]
actix-rt = "1.0.0-alpha.1" actix-server = { version = "0.8.0-alpha.1", features=["openssl", "rustls"] }
actix-server = { version = "0.8.0-alpha.1", features=["openssl"] }
actix-connect = { version = "1.0.0-alpha.1", features=["openssl"] } actix-connect = { version = "1.0.0-alpha.1", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] } actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] }
env_logger = "0.6" env_logger = "0.6"

View File

@ -432,8 +432,7 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use actix_http_test::block_on; use futures::future::poll_fn;
use futures::future::{lazy, poll_fn};
impl Body { impl Body {
pub(crate) fn get_ref(&self) -> &[u8] { pub(crate) fn get_ref(&self) -> &[u8] {
@ -453,21 +452,21 @@ mod tests {
} }
} }
#[test] #[actix_rt::test]
fn test_static_str() { async fn test_static_str() {
assert_eq!(Body::from("").size(), BodySize::Sized(0)); assert_eq!(Body::from("").size(), BodySize::Sized(0));
assert_eq!(Body::from("test").size(), BodySize::Sized(4)); assert_eq!(Body::from("test").size(), BodySize::Sized(4));
assert_eq!(Body::from("test").get_ref(), b"test"); assert_eq!(Body::from("test").get_ref(), b"test");
assert_eq!("test".size(), BodySize::Sized(4)); assert_eq!("test".size(), BodySize::Sized(4));
assert_eq!( assert_eq!(
block_on(poll_fn(|cx| "test".poll_next(cx))).unwrap().ok(), poll_fn(|cx| "test".poll_next(cx)).await.unwrap().ok(),
Some(Bytes::from("test")) Some(Bytes::from("test"))
); );
} }
#[test] #[actix_rt::test]
fn test_static_bytes() { async fn test_static_bytes() {
assert_eq!(Body::from(b"test".as_ref()).size(), BodySize::Sized(4)); assert_eq!(Body::from(b"test".as_ref()).size(), BodySize::Sized(4));
assert_eq!(Body::from(b"test".as_ref()).get_ref(), b"test"); assert_eq!(Body::from(b"test".as_ref()).get_ref(), b"test");
assert_eq!( assert_eq!(
@ -478,55 +477,57 @@ mod tests {
assert_eq!((&b"test"[..]).size(), BodySize::Sized(4)); assert_eq!((&b"test"[..]).size(), BodySize::Sized(4));
assert_eq!( assert_eq!(
block_on(poll_fn(|cx| (&b"test"[..]).poll_next(cx))) poll_fn(|cx| (&b"test"[..]).poll_next(cx))
.await
.unwrap() .unwrap()
.ok(), .ok(),
Some(Bytes::from("test")) Some(Bytes::from("test"))
); );
} }
#[test] #[actix_rt::test]
fn test_vec() { async fn test_vec() {
assert_eq!(Body::from(Vec::from("test")).size(), BodySize::Sized(4)); assert_eq!(Body::from(Vec::from("test")).size(), BodySize::Sized(4));
assert_eq!(Body::from(Vec::from("test")).get_ref(), b"test"); assert_eq!(Body::from(Vec::from("test")).get_ref(), b"test");
assert_eq!(Vec::from("test").size(), BodySize::Sized(4)); assert_eq!(Vec::from("test").size(), BodySize::Sized(4));
assert_eq!( assert_eq!(
block_on(poll_fn(|cx| Vec::from("test").poll_next(cx))) poll_fn(|cx| Vec::from("test").poll_next(cx))
.await
.unwrap() .unwrap()
.ok(), .ok(),
Some(Bytes::from("test")) Some(Bytes::from("test"))
); );
} }
#[test] #[actix_rt::test]
fn test_bytes() { async fn test_bytes() {
let mut b = Bytes::from("test"); let mut b = Bytes::from("test");
assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4)); assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4));
assert_eq!(Body::from(b.clone()).get_ref(), b"test"); assert_eq!(Body::from(b.clone()).get_ref(), b"test");
assert_eq!(b.size(), BodySize::Sized(4)); assert_eq!(b.size(), BodySize::Sized(4));
assert_eq!( assert_eq!(
block_on(poll_fn(|cx| b.poll_next(cx))).unwrap().ok(), poll_fn(|cx| b.poll_next(cx)).await.unwrap().ok(),
Some(Bytes::from("test")) Some(Bytes::from("test"))
); );
} }
#[test] #[actix_rt::test]
fn test_bytes_mut() { async fn test_bytes_mut() {
let mut b = BytesMut::from("test"); let mut b = BytesMut::from("test");
assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4)); assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4));
assert_eq!(Body::from(b.clone()).get_ref(), b"test"); assert_eq!(Body::from(b.clone()).get_ref(), b"test");
assert_eq!(b.size(), BodySize::Sized(4)); assert_eq!(b.size(), BodySize::Sized(4));
assert_eq!( assert_eq!(
block_on(poll_fn(|cx| b.poll_next(cx))).unwrap().ok(), poll_fn(|cx| b.poll_next(cx)).await.unwrap().ok(),
Some(Bytes::from("test")) Some(Bytes::from("test"))
); );
} }
#[test] #[actix_rt::test]
fn test_string() { async fn test_string() {
let mut b = "test".to_owned(); let mut b = "test".to_owned();
assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4)); assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4));
assert_eq!(Body::from(b.clone()).get_ref(), b"test"); assert_eq!(Body::from(b.clone()).get_ref(), b"test");
@ -535,26 +536,26 @@ mod tests {
assert_eq!(b.size(), BodySize::Sized(4)); assert_eq!(b.size(), BodySize::Sized(4));
assert_eq!( assert_eq!(
block_on(poll_fn(|cx| b.poll_next(cx))).unwrap().ok(), poll_fn(|cx| b.poll_next(cx)).await.unwrap().ok(),
Some(Bytes::from("test")) Some(Bytes::from("test"))
); );
} }
#[test] #[actix_rt::test]
fn test_unit() { async fn test_unit() {
assert_eq!(().size(), BodySize::Empty); assert_eq!(().size(), BodySize::Empty);
assert!(block_on(poll_fn(|cx| ().poll_next(cx))).is_none()); assert!(poll_fn(|cx| ().poll_next(cx)).await.is_none());
} }
#[test] #[actix_rt::test]
fn test_box() { async fn test_box() {
let mut val = Box::new(()); let mut val = Box::new(());
assert_eq!(val.size(), BodySize::Empty); assert_eq!(val.size(), BodySize::Empty);
assert!(block_on(poll_fn(|cx| val.poll_next(cx))).is_none()); assert!(poll_fn(|cx| val.poll_next(cx)).await.is_none());
} }
#[test] #[actix_rt::test]
fn test_body_eq() { async fn test_body_eq() {
assert!(Body::None == Body::None); assert!(Body::None == Body::None);
assert!(Body::None != Body::Empty); assert!(Body::None != Body::Empty);
assert!(Body::Empty == Body::Empty); assert!(Body::Empty == Body::Empty);
@ -566,15 +567,15 @@ mod tests {
assert!(Body::Bytes(Bytes::from_static(b"1")) != Body::None); assert!(Body::Bytes(Bytes::from_static(b"1")) != Body::None);
} }
#[test] #[actix_rt::test]
fn test_body_debug() { async fn test_body_debug() {
assert!(format!("{:?}", Body::None).contains("Body::None")); assert!(format!("{:?}", Body::None).contains("Body::None"));
assert!(format!("{:?}", Body::Empty).contains("Body::Empty")); assert!(format!("{:?}", Body::Empty).contains("Body::Empty"));
assert!(format!("{:?}", Body::Bytes(Bytes::from_static(b"1"))).contains("1")); assert!(format!("{:?}", Body::Bytes(Bytes::from_static(b"1"))).contains("1"));
} }
#[test] #[actix_rt::test]
fn test_serde_json() { async fn test_serde_json() {
use serde_json::json; use serde_json::json;
assert_eq!( assert_eq!(
Body::from(serde_json::Value::String("test".into())).size(), Body::from(serde_json::Value::String("test".into())).size(),

View File

@ -1,8 +1,5 @@
use std::fmt; use std::fmt;
use std::future::Future;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration; use std::time::Duration;
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
@ -11,7 +8,6 @@ use actix_connect::{
}; };
use actix_service::{apply_fn, Service}; use actix_service::{apply_fn, Service};
use actix_utils::timeout::{TimeoutError, TimeoutService}; use actix_utils::timeout::{TimeoutError, TimeoutService};
use futures::future::Ready;
use http::Uri; use http::Uri;
use tokio_net::tcp::TcpStream; use tokio_net::tcp::TcpStream;
@ -344,7 +340,6 @@ mod connect_impl {
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use futures::future::{err, Either, Ready}; use futures::future::{err, Either, Ready};
use futures::ready;
use super::*; use super::*;
use crate::client::connection::IoConnection; use crate::client::connection::IoConnection;
@ -402,7 +397,10 @@ mod connect_impl {
#[cfg(any(feature = "openssl", feature = "rustls"))] #[cfg(any(feature = "openssl", feature = "rustls"))]
mod connect_impl { mod connect_impl {
use std::future::Future;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures::future::Either; use futures::future::Either;
use futures::ready; use futures::ready;

View File

@ -1,4 +1,3 @@
use std::future::Future;
use std::io::Write; use std::io::Write;
use std::pin::Pin; use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
@ -6,8 +5,8 @@ use std::{io, time};
use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Framed};
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
use futures::future::{ok, poll_fn, Either}; use futures::future::poll_fn;
use futures::{Sink, SinkExt, Stream, StreamExt}; use futures::{SinkExt, Stream, StreamExt};
use crate::error::PayloadError; use crate::error::PayloadError;
use crate::h1; use crate::h1;

View File

@ -1,11 +1,8 @@
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time; use std::time;
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use bytes::Bytes; use bytes::Bytes;
use futures::future::{err, poll_fn, Either}; use futures::future::poll_fn;
use h2::{client::SendRequest, SendStream}; use h2::{client::SendRequest, SendStream};
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING}; use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING};
use http::{request::Request, HttpTryFrom, Method, Version}; use http::{request::Request, HttpTryFrom, Method, Version};

View File

@ -1,23 +1,22 @@
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::future::Future; use std::future::Future;
use std::io;
use std::pin::Pin; use std::pin::Pin;
use std::rc::Rc; use std::rc::Rc;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_rt::time::{delay_for, Delay};
use actix_service::Service; use actix_service::Service;
use actix_utils::{oneshot, task::LocalWaker}; use actix_utils::{oneshot, task::LocalWaker};
use bytes::Bytes; use bytes::Bytes;
use futures::future::{err, ok, poll_fn, Either, FutureExt, LocalBoxFuture, Ready}; use futures::future::{poll_fn, FutureExt, LocalBoxFuture};
use h2::client::{handshake, Connection, SendRequest}; use h2::client::{handshake, Connection, SendRequest};
use hashbrown::HashMap; use hashbrown::HashMap;
use http::uri::Authority; use http::uri::Authority;
use indexmap::IndexSet; use indexmap::IndexSet;
use slab::Slab; use slab::Slab;
use tokio_timer::{delay_for, Delay};
use super::connection::{ConnectionType, IoConnection}; use super::connection::{ConnectionType, IoConnection};
use super::error::ConnectError; use super::error::ConnectError;
@ -100,7 +99,7 @@ where
fn call(&mut self, req: Connect) -> Self::Future { fn call(&mut self, req: Connect) -> Self::Future {
// start support future // start support future
tokio_executor::current_thread::spawn(ConnectorPoolSupport { actix_rt::spawn(ConnectorPoolSupport {
connector: self.0.clone(), connector: self.0.clone(),
inner: self.1.clone(), inner: self.1.clone(),
}); });
@ -139,7 +138,7 @@ where
)) ))
} else { } else {
let (snd, connection) = handshake(io).await?; let (snd, connection) = handshake(io).await?;
tokio_executor::current_thread::spawn(connection.map(|_| ())); actix_rt::spawn(connection.map(|_| ()));
Ok(IoConnection::new( Ok(IoConnection::new(
ConnectionType::H2(snd), ConnectionType::H2(snd),
Instant::now(), Instant::now(),
@ -328,9 +327,7 @@ where
{ {
if let Some(timeout) = self.disconnect_timeout { if let Some(timeout) = self.disconnect_timeout {
if let ConnectionType::H1(io) = conn.io { if let ConnectionType::H1(io) = conn.io {
tokio_executor::current_thread::spawn(CloseConnection::new( actix_rt::spawn(CloseConnection::new(io, timeout))
io, timeout,
))
} }
} }
} else { } else {
@ -342,9 +339,9 @@ where
Poll::Ready(Ok(n)) if n > 0 => { Poll::Ready(Ok(n)) if n > 0 => {
if let Some(timeout) = self.disconnect_timeout { if let Some(timeout) = self.disconnect_timeout {
if let ConnectionType::H1(io) = io { if let ConnectionType::H1(io) = io {
tokio_executor::current_thread::spawn( actix_rt::spawn(CloseConnection::new(
CloseConnection::new(io, timeout), io, timeout,
) ))
} }
} }
continue; continue;
@ -376,7 +373,7 @@ where
self.acquired -= 1; self.acquired -= 1;
if let Some(timeout) = self.disconnect_timeout { if let Some(timeout) = self.disconnect_timeout {
if let ConnectionType::H1(io) = io { if let ConnectionType::H1(io) = io {
tokio_executor::current_thread::spawn(CloseConnection::new(io, timeout)) actix_rt::spawn(CloseConnection::new(io, timeout))
} }
} }
self.check_availibility(); self.check_availibility();
@ -518,7 +515,7 @@ where
inner: Rc<RefCell<Inner<Io>>>, inner: Rc<RefCell<Inner<Io>>>,
fut: F, fut: F,
) { ) {
tokio_executor::current_thread::spawn(OpenWaitingConnection { actix_rt::spawn(OpenWaitingConnection {
key, key,
fut, fut,
h2: None, h2: None,
@ -554,7 +551,7 @@ where
if let Some(ref mut h2) = this.h2 { if let Some(ref mut h2) = this.h2 {
return match Pin::new(h2).poll(cx) { return match Pin::new(h2).poll(cx) {
Poll::Ready(Ok((snd, connection))) => { Poll::Ready(Ok((snd, connection))) => {
tokio_executor::current_thread::spawn(connection.map(|_| ())); actix_rt::spawn(connection.map(|_| ()));
let rx = this.rx.take().unwrap(); let rx = this.rx.take().unwrap();
let _ = rx.send(Ok(IoConnection::new( let _ = rx.send(Ok(IoConnection::new(
ConnectionType::H2(snd), ConnectionType::H2(snd),

View File

@ -4,10 +4,10 @@ use std::fmt::Write;
use std::rc::Rc; use std::rc::Rc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use actix_rt::time::{delay, delay_for, Delay};
use bytes::BytesMut; use bytes::BytesMut;
use futures::{future, Future, FutureExt}; use futures::{future, FutureExt};
use time; use time;
use tokio_timer::{delay, delay_for, Delay};
// "Sun, 06 Nov 1994 08:49:37 GMT".len() // "Sun, 06 Nov 1994 08:49:37 GMT".len()
const DATE_VALUE_LENGTH: usize = 29; const DATE_VALUE_LENGTH: usize = 29;
@ -242,12 +242,10 @@ impl DateService {
// periodic date update // periodic date update
let s = self.clone(); let s = self.clone();
tokio_executor::current_thread::spawn( actix_rt::spawn(delay_for(Duration::from_millis(500)).then(move |_| {
delay_for(Duration::from_millis(500)).then(move |_| {
s.0.reset(); s.0.reset();
future::ready(()) future::ready(())
}), }));
);
} }
} }
@ -265,26 +263,19 @@ impl DateService {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use actix_rt::System;
use futures::future;
#[test] #[test]
fn test_date_len() { fn test_date_len() {
assert_eq!(DATE_VALUE_LENGTH, "Sun, 06 Nov 1994 08:49:37 GMT".len()); assert_eq!(DATE_VALUE_LENGTH, "Sun, 06 Nov 1994 08:49:37 GMT".len());
} }
#[test] #[actix_rt::test]
fn test_date() { async fn test_date() {
let mut rt = System::new("test");
let _ = rt.block_on(future::lazy(|_| {
let settings = ServiceConfig::new(KeepAlive::Os, 0, 0); let settings = ServiceConfig::new(KeepAlive::Os, 0, 0);
let mut buf1 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10); let mut buf1 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10);
settings.set_date(&mut buf1); settings.set_date(&mut buf1);
let mut buf2 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10); let mut buf2 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10);
settings.set_date(&mut buf2); settings.set_date(&mut buf2);
assert_eq!(buf1, buf2); assert_eq!(buf1, buf2);
future::ok::<_, ()>(())
}));
} }
} }

View File

@ -1,5 +1,4 @@
use ring::hkdf::{Algorithm, KeyType, Prk, HKDF_SHA256}; use ring::hkdf::{Algorithm, KeyType, Prk, HKDF_SHA256};
use ring::hmac;
use ring::rand::{SecureRandom, SystemRandom}; use ring::rand::{SecureRandom, SystemRandom};
use super::private::KEY_LEN as PRIVATE_KEY_LEN; use super::private::KEY_LEN as PRIVATE_KEY_LEN;

View File

@ -16,7 +16,6 @@ use httparse;
use serde::de::value::Error as DeError; use serde::de::value::Error as DeError;
use serde_json::error::Error as JsonError; use serde_json::error::Error as JsonError;
use serde_urlencoded::ser::Error as FormError; use serde_urlencoded::ser::Error as FormError;
use tokio_timer::Error as TimerError;
// re-export for convinience // re-export for convinience
use crate::body::Body; use crate::body::Body;
@ -178,9 +177,6 @@ impl ResponseError for JsonError {}
/// `InternalServerError` for `FormError` /// `InternalServerError` for `FormError`
impl ResponseError for FormError {} impl ResponseError for FormError {}
/// `InternalServerError` for `TimerError`
impl ResponseError for TimerError {}
#[cfg(feature = "openssl")] #[cfg(feature = "openssl")]
/// `InternalServerError` for `openssl::ssl::Error` /// `InternalServerError` for `openssl::ssl::Error`
impl ResponseError for open_ssl::ssl::Error {} impl ResponseError for open_ssl::ssl::Error {}

View File

@ -1,9 +1,7 @@
use std::future::Future;
use std::io; use std::io;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::mem::MaybeUninit; use std::mem::MaybeUninit;
use std::pin::Pin; use std::task::Poll;
use std::task::{Context, Poll};
use actix_codec::Decoder; use actix_codec::Decoder;
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};

View File

@ -3,15 +3,15 @@ use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use std::time::Instant; use std::time::Instant;
use std::{fmt, io, io::Write, net}; use std::{fmt, io, net};
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed, FramedParts}; use actix_codec::{AsyncRead, Decoder, Encoder, Framed, FramedParts};
use actix_rt::time::{delay, Delay};
use actix_server_config::IoStream; use actix_server_config::IoStream;
use actix_service::Service; use actix_service::Service;
use bitflags::bitflags; use bitflags::bitflags;
use bytes::{BufMut, BytesMut}; use bytes::{BufMut, BytesMut};
use log::{error, trace}; use log::{error, trace};
use tokio_timer::{delay, Delay};
use crate::body::{Body, BodySize, MessageBody, ResponseBody}; use crate::body::{Body, BodySize, MessageBody, ResponseBody};
use crate::cloneable::CloneableService; use crate::cloneable::CloneableService;
@ -893,10 +893,9 @@ mod tests {
use crate::h1::{ExpectHandler, UpgradeHandler}; use crate::h1::{ExpectHandler, UpgradeHandler};
use crate::test::TestBuffer; use crate::test::TestBuffer;
#[test] #[actix_rt::test]
fn test_req_parse_err() { async fn test_req_parse_err() {
let mut sys = actix_rt::System::new("test"); lazy(|cx| {
let _ = sys.block_on(lazy(|cx| {
let buf = TestBuffer::new("GET /test HTTP/1\r\n\r\n"); let buf = TestBuffer::new("GET /test HTTP/1\r\n\r\n");
let mut h1 = Dispatcher::<_, _, _, _, UpgradeHandler<TestBuffer>>::new( let mut h1 = Dispatcher::<_, _, _, _, UpgradeHandler<TestBuffer>>::new(
@ -918,7 +917,7 @@ mod tests {
assert!(inner.flags.contains(Flags::READ_DISCONNECT)); assert!(inner.flags.contains(Flags::READ_DISCONNECT));
assert_eq!(&inner.io.write_buf[..26], b"HTTP/1.1 400 Bad Request\r\n"); assert_eq!(&inner.io.write_buf[..26], b"HTTP/1.1 400 Bad Request\r\n");
} }
ok::<_, ()>(()) })
})); .await;
} }
} }

View File

@ -1,5 +1,3 @@
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_server_config::ServerConfig; use actix_server_config::ServerConfig;

View File

@ -1,7 +1,6 @@
//! Payload stream //! Payload stream
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
use std::rc::{Rc, Weak}; use std::rc::{Rc, Weak};
use std::task::{Context, Poll}; use std::task::{Context, Poll};
@ -227,12 +226,10 @@ impl Inner {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use actix_rt::Runtime; use futures::future::poll_fn;
use futures::future::{poll_fn, ready};
#[test] #[actix_rt::test]
fn test_unread_data() { async fn test_unread_data() {
Runtime::new().unwrap().block_on(async {
let (_, mut payload) = Payload::create(false); let (_, mut payload) = Payload::create(false);
payload.unread_data(Bytes::from("data")); payload.unread_data(Bytes::from("data"));
@ -243,8 +240,5 @@ mod tests {
Bytes::from("data"), Bytes::from("data"),
poll_fn(|cx| payload.readany(cx)).await.unwrap().unwrap() poll_fn(|cx| payload.readany(cx)).await.unwrap().unwrap()
); );
ready(())
});
} }
} }

View File

@ -9,7 +9,7 @@ use actix_codec::Framed;
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig}; use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
use actix_service::{IntoServiceFactory, Service, ServiceFactory}; use actix_service::{IntoServiceFactory, Service, ServiceFactory};
use futures::future::{ok, Ready}; use futures::future::{ok, Ready};
use futures::{ready, Stream}; use futures::ready;
use crate::body::MessageBody; use crate::body::MessageBody;
use crate::cloneable::CloneableService; use crate::cloneable::CloneableService;

View File

@ -1,6 +1,4 @@
use std::future::Future;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_codec::Framed; use actix_codec::Framed;

View File

@ -3,7 +3,6 @@ use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Framed};
use futures::Sink;
use crate::body::{BodySize, MessageBody, ResponseBody}; use crate::body::{BodySize, MessageBody, ResponseBody};
use crate::error::Error; use crate::error::Error;

View File

@ -7,6 +7,7 @@ use std::time::Instant;
use std::{fmt, mem, net}; use std::{fmt, mem, net};
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_rt::time::Delay;
use actix_server_config::IoStream; use actix_server_config::IoStream;
use actix_service::Service; use actix_service::Service;
use bitflags::bitflags; use bitflags::bitflags;
@ -19,7 +20,6 @@ use http::header::{
}; };
use http::HttpTryFrom; use http::HttpTryFrom;
use log::{debug, error, trace}; use log::{debug, error, trace};
use tokio_timer::Delay;
use crate::body::{Body, BodySize, MessageBody, ResponseBody}; use crate::body::{Body, BodySize, MessageBody, ResponseBody};
use crate::cloneable::CloneableService; use crate::cloneable::CloneableService;
@ -139,7 +139,7 @@ where
on_connect.set(&mut req.extensions_mut()); on_connect.set(&mut req.extensions_mut());
} }
tokio_executor::current_thread::spawn(ServiceResponse::< actix_rt::spawn(ServiceResponse::<
S::Future, S::Future,
S::Response, S::Response,
S::Error, S::Error,

View File

@ -4,8 +4,7 @@
clippy::too_many_arguments, clippy::too_many_arguments,
clippy::new_without_default, clippy::new_without_default,
clippy::borrow_interior_mutable_const, clippy::borrow_interior_mutable_const,
clippy::write_with_newline, clippy::write_with_newline
unused_imports
)] )]
#[macro_use] #[macro_use]

View File

@ -1,4 +1,3 @@
use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};

View File

@ -7,7 +7,6 @@ use std::task::{Context, Poll};
use std::{fmt, str}; use std::{fmt, str};
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
use futures::future::{ok, Ready};
use futures::stream::Stream; use futures::stream::Stream;
use serde::Serialize; use serde::Serialize;
use serde_json; use serde_json;

View File

@ -8,7 +8,7 @@ use actix_server_config::{
Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig, Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig,
}; };
use actix_service::{IntoServiceFactory, Service, ServiceFactory}; use actix_service::{IntoServiceFactory, Service, ServiceFactory};
use bytes::{Buf, BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
use futures::{ready, Future}; use futures::{ready, Future};
use h2::server::{self, Handshake}; use h2::server::{self, Handshake};
use pin_project::{pin_project, project}; use pin_project::{pin_project, project};
@ -659,7 +659,7 @@ impl<T: AsyncRead> AsyncRead for Io<T> {
// } // }
} }
impl<T: AsyncWrite> tokio_io::AsyncWrite for Io<T> { impl<T: AsyncWrite> actix_codec::AsyncWrite for Io<T> {
fn poll_write( fn poll_write(
self: Pin<&mut Self>, self: Pin<&mut Self>,
cx: &mut Context<'_>, cx: &mut Context<'_>,

View File

@ -7,7 +7,7 @@ use std::task::{Context, Poll};
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_server_config::IoStream; use actix_server_config::IoStream;
use bytes::{Buf, Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use http::header::{self, HeaderName, HeaderValue}; use http::header::{self, HeaderName, HeaderValue};
use http::{HttpTryFrom, Method, Uri, Version}; use http::{HttpTryFrom, Method, Uri, Version};
use percent_encoding::percent_encode; use percent_encoding::percent_encode;

View File

@ -3,7 +3,7 @@ use bytes::Bytes;
use futures::future::{self, ok}; use futures::future::{self, ok};
use actix_http::{http, HttpService, Request, Response}; use actix_http::{http, HttpService, Request, Response};
use actix_http_test::{block_on, TestServer}; use actix_http_test::TestServer;
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \
@ -27,12 +27,10 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World"; Hello World Hello World Hello World Hello World Hello World";
#[test] #[actix_rt::test]
fn test_h1_v2() { async fn test_h1_v2() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
HttpService::build() HttpService::build().finish(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
.finish(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
}); });
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
@ -52,12 +50,10 @@ fn test_h1_v2() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_connection_close() { async fn test_connection_close() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
HttpService::build() HttpService::build()
.finish(|_| ok::<_, ()>(Response::Ok().body(STR))) .finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
@ -66,12 +62,10 @@ fn test_connection_close() {
let response = srv.get("/").force_close().send().await.unwrap(); let response = srv.get("/").force_close().send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }
#[test] #[actix_rt::test]
fn test_with_query_parameter() { async fn test_with_query_parameter() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
HttpService::build() HttpService::build()
.finish(|req: Request| { .finish(|req: Request| {
@ -87,5 +81,4 @@ fn test_with_query_parameter() {
let request = srv.request(http::Method::GET, srv.url("/?qp=5")); let request = srv.request(http::Method::GET, srv.url("/?qp=5"));
let response = request.send().await.unwrap(); let response = request.send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }

View File

@ -2,7 +2,7 @@
use std::io; use std::io;
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_http_test::{block_on, TestServer}; use actix_http_test::TestServer;
use actix_server::ssl::OpensslAcceptor; use actix_server::ssl::OpensslAcceptor;
use actix_server_config::ServerConfig; use actix_server_config::ServerConfig;
use actix_service::{factory_fn_cfg, pipeline_factory, service_fn2, ServiceFactory}; use actix_service::{factory_fn_cfg, pipeline_factory, service_fn2, ServiceFactory};
@ -57,9 +57,8 @@ fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> io::Result<OpensslAcceptor<T, ()
Ok(OpensslAcceptor::new(builder.build())) Ok(OpensslAcceptor::new(builder.build()))
} }
#[test] #[actix_rt::test]
fn test_h2() -> io::Result<()> { async fn test_h2() -> io::Result<()> {
block_on(async {
let openssl = ssl_acceptor()?; let openssl = ssl_acceptor()?;
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
pipeline_factory( pipeline_factory(
@ -77,12 +76,10 @@ fn test_h2() -> io::Result<()> {
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
Ok(()) Ok(())
})
} }
#[test] #[actix_rt::test]
fn test_h2_1() -> io::Result<()> { async fn test_h2_1() -> io::Result<()> {
block_on(async {
let openssl = ssl_acceptor()?; let openssl = ssl_acceptor()?;
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
pipeline_factory( pipeline_factory(
@ -104,12 +101,10 @@ fn test_h2_1() -> io::Result<()> {
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
Ok(()) Ok(())
})
} }
#[test] #[actix_rt::test]
fn test_h2_body() -> io::Result<()> { async fn test_h2_body() -> io::Result<()> {
block_on(async {
let data = "HELLOWORLD".to_owned().repeat(64 * 1024); let data = "HELLOWORLD".to_owned().repeat(64 * 1024);
let openssl = ssl_acceptor()?; let openssl = ssl_acceptor()?;
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
@ -136,12 +131,10 @@ fn test_h2_body() -> io::Result<()> {
let body = srv.load_body(response).await.unwrap(); let body = srv.load_body(response).await.unwrap();
assert_eq!(&body, data.as_bytes()); assert_eq!(&body, data.as_bytes());
Ok(()) Ok(())
})
} }
#[test] #[actix_rt::test]
fn test_h2_content_length() { async fn test_h2_content_length() {
block_on(async {
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
@ -194,12 +187,10 @@ fn test_h2_content_length() {
assert_eq!(response.headers().get(&header), Some(&value)); assert_eq!(response.headers().get(&header), Some(&value));
} }
} }
})
} }
#[test] #[actix_rt::test]
fn test_h2_headers() { async fn test_h2_headers() {
block_on(async {
let data = STR.repeat(10); let data = STR.repeat(10);
let data2 = data.clone(); let data2 = data.clone();
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
@ -240,7 +231,6 @@ fn test_h2_headers() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from(data2)); assert_eq!(bytes, Bytes::from(data2));
})
} }
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
@ -265,9 +255,8 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World"; Hello World Hello World Hello World Hello World Hello World";
#[test] #[actix_rt::test]
fn test_h2_body2() { async fn test_h2_body2() {
block_on(async {
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory( pipeline_factory(
@ -288,12 +277,10 @@ fn test_h2_body2() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_h2_head_empty() { async fn test_h2_head_empty() {
block_on(async {
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory( pipeline_factory(
@ -320,12 +307,10 @@ fn test_h2_head_empty() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert!(bytes.is_empty()); assert!(bytes.is_empty());
})
} }
#[test] #[actix_rt::test]
fn test_h2_head_binary() { async fn test_h2_head_binary() {
block_on(async {
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory( pipeline_factory(
@ -355,12 +340,10 @@ fn test_h2_head_binary() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert!(bytes.is_empty()); assert!(bytes.is_empty());
})
} }
#[test] #[actix_rt::test]
fn test_h2_head_binary2() { async fn test_h2_head_binary2() {
block_on(async {
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
pipeline_factory( pipeline_factory(
@ -382,12 +365,10 @@ fn test_h2_head_binary2() {
let len = response.headers().get(header::CONTENT_LENGTH).unwrap(); let len = response.headers().get(header::CONTENT_LENGTH).unwrap();
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
} }
})
} }
#[test] #[actix_rt::test]
fn test_h2_body_length() { async fn test_h2_body_length() {
block_on(async {
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory( pipeline_factory(
@ -414,12 +395,10 @@ fn test_h2_body_length() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_h2_body_chunked_explicit() { async fn test_h2_body_chunked_explicit() {
block_on(async {
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory( pipeline_factory(
@ -430,8 +409,7 @@ fn test_h2_body_chunked_explicit() {
.and_then( .and_then(
HttpService::build() HttpService::build()
.h2(|_| { .h2(|_| {
let body = let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::Ok()
.header(header::TRANSFER_ENCODING, "chunked") .header(header::TRANSFER_ENCODING, "chunked")
@ -451,12 +429,10 @@ fn test_h2_body_chunked_explicit() {
// decode // decode
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_h2_response_http_error_handling() { async fn test_h2_response_http_error_handling() {
block_on(async {
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
@ -487,12 +463,10 @@ fn test_h2_response_http_error_handling() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value")); assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
})
} }
#[test] #[actix_rt::test]
fn test_h2_service_error() { async fn test_h2_service_error() {
block_on(async {
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
@ -514,12 +488,10 @@ fn test_h2_service_error() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(b"error")); assert_eq!(bytes, Bytes::from_static(b"error"));
})
} }
#[test] #[actix_rt::test]
fn test_h2_on_connect() { async fn test_h2_on_connect() {
block_on(async {
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
@ -541,5 +513,4 @@ fn test_h2_on_connect() {
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }

View File

@ -4,7 +4,7 @@ use actix_http::error::PayloadError;
use actix_http::http::header::{self, HeaderName, HeaderValue}; use actix_http::http::header::{self, HeaderName, HeaderValue};
use actix_http::http::{Method, StatusCode, Version}; use actix_http::http::{Method, StatusCode, Version};
use actix_http::{body, error, Error, HttpService, Request, Response}; use actix_http::{body, error, Error, HttpService, Request, Response};
use actix_http_test::{block_on, TestServer}; use actix_http_test::TestServer;
use actix_server::ssl::RustlsAcceptor; use actix_server::ssl::RustlsAcceptor;
use actix_server_config::ServerConfig; use actix_server_config::ServerConfig;
use actix_service::{factory_fn_cfg, pipeline_factory, service_fn2, ServiceFactory}; use actix_service::{factory_fn_cfg, pipeline_factory, service_fn2, ServiceFactory};
@ -45,9 +45,8 @@ fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> io::Result<RustlsAcceptor<T, ()>
Ok(RustlsAcceptor::new(config)) Ok(RustlsAcceptor::new(config))
} }
#[test] #[actix_rt::test]
fn test_h2() -> io::Result<()> { async fn test_h2() -> io::Result<()> {
block_on(async {
let rustls = ssl_acceptor()?; let rustls = ssl_acceptor()?;
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e))) pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -61,12 +60,10 @@ fn test_h2() -> io::Result<()> {
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
Ok(()) Ok(())
})
} }
#[test] #[actix_rt::test]
fn test_h2_1() -> io::Result<()> { async fn test_h2_1() -> io::Result<()> {
block_on(async {
let rustls = ssl_acceptor()?; let rustls = ssl_acceptor()?;
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e))) pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -84,12 +81,10 @@ fn test_h2_1() -> io::Result<()> {
let response = srv.sget("/").send().await.unwrap(); let response = srv.sget("/").send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
Ok(()) Ok(())
})
} }
#[test] #[actix_rt::test]
fn test_h2_body1() -> io::Result<()> { async fn test_h2_body1() -> io::Result<()> {
block_on(async {
let data = "HELLOWORLD".to_owned().repeat(64 * 1024); let data = "HELLOWORLD".to_owned().repeat(64 * 1024);
let rustls = ssl_acceptor()?; let rustls = ssl_acceptor()?;
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
@ -112,12 +107,10 @@ fn test_h2_body1() -> io::Result<()> {
let body = srv.load_body(response).await.unwrap(); let body = srv.load_body(response).await.unwrap();
assert_eq!(&body, data.as_bytes()); assert_eq!(&body, data.as_bytes());
Ok(()) Ok(())
})
} }
#[test] #[actix_rt::test]
fn test_h2_content_length() { async fn test_h2_content_length() {
block_on(async {
let rustls = ssl_acceptor().unwrap(); let rustls = ssl_acceptor().unwrap();
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
@ -166,12 +159,10 @@ fn test_h2_content_length() {
assert_eq!(response.headers().get(&header), Some(&value)); assert_eq!(response.headers().get(&header), Some(&value));
} }
} }
})
} }
#[test] #[actix_rt::test]
fn test_h2_headers() { async fn test_h2_headers() {
block_on(async {
let data = STR.repeat(10); let data = STR.repeat(10);
let data2 = data.clone(); let data2 = data.clone();
let rustls = ssl_acceptor().unwrap(); let rustls = ssl_acceptor().unwrap();
@ -212,7 +203,6 @@ fn test_h2_headers() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from(data2)); assert_eq!(bytes, Bytes::from(data2));
})
} }
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
@ -237,9 +227,8 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World"; Hello World Hello World Hello World Hello World Hello World";
#[test] #[actix_rt::test]
fn test_h2_body2() { async fn test_h2_body2() {
block_on(async {
let rustls = ssl_acceptor().unwrap(); let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e))) pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -256,12 +245,10 @@ fn test_h2_body2() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_h2_head_empty() { async fn test_h2_head_empty() {
block_on(async {
let rustls = ssl_acceptor().unwrap(); let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e))) pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -287,12 +274,10 @@ fn test_h2_head_empty() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert!(bytes.is_empty()); assert!(bytes.is_empty());
})
} }
#[test] #[actix_rt::test]
fn test_h2_head_binary() { async fn test_h2_head_binary() {
block_on(async {
let rustls = ssl_acceptor().unwrap(); let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e))) pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -300,9 +285,7 @@ fn test_h2_head_binary() {
HttpService::build() HttpService::build()
.h2(|_| { .h2(|_| {
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::Ok().content_length(STR.len() as u64).body(STR),
.content_length(STR.len() as u64)
.body(STR),
) )
}) })
.map_err(|_| ()), .map_err(|_| ()),
@ -323,12 +306,10 @@ fn test_h2_head_binary() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert!(bytes.is_empty()); assert!(bytes.is_empty());
})
} }
#[test] #[actix_rt::test]
fn test_h2_head_binary2() { async fn test_h2_head_binary2() {
block_on(async {
let rustls = ssl_acceptor().unwrap(); let rustls = ssl_acceptor().unwrap();
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e))) pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -349,12 +330,10 @@ fn test_h2_head_binary2() {
.unwrap(); .unwrap();
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
} }
})
} }
#[test] #[actix_rt::test]
fn test_h2_body_length() { async fn test_h2_body_length() {
block_on(async {
let rustls = ssl_acceptor().unwrap(); let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e))) pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -363,10 +342,8 @@ fn test_h2_body_length() {
.h2(|_| { .h2(|_| {
let body = once(ok(Bytes::from_static(STR.as_ref()))); let body = once(ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
Response::Ok().body(body::SizedStream::new( Response::Ok()
STR.len() as u64, .body(body::SizedStream::new(STR.len() as u64, body)),
body,
)),
) )
}) })
.map_err(|_| ()), .map_err(|_| ()),
@ -379,12 +356,10 @@ fn test_h2_body_length() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_h2_body_chunked_explicit() { async fn test_h2_body_chunked_explicit() {
block_on(async {
let rustls = ssl_acceptor().unwrap(); let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e))) pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -412,12 +387,10 @@ fn test_h2_body_chunked_explicit() {
// decode // decode
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_h2_response_http_error_handling() { async fn test_h2_response_http_error_handling() {
block_on(async {
let rustls = ssl_acceptor().unwrap(); let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
@ -429,10 +402,7 @@ fn test_h2_response_http_error_handling() {
let broken_header = Bytes::from_static(b"\0\0\0"); let broken_header = Bytes::from_static(b"\0\0\0");
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::Ok()
.header( .header(http::header::CONTENT_TYPE, broken_header)
http::header::CONTENT_TYPE,
broken_header,
)
.body(STR), .body(STR),
) )
})) }))
@ -447,12 +417,10 @@ fn test_h2_response_http_error_handling() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value")); assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
})
} }
#[test] #[actix_rt::test]
fn test_h2_service_error() { async fn test_h2_service_error() {
block_on(async {
let rustls = ssl_acceptor().unwrap(); let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || { let mut srv = TestServer::start(move || {
@ -470,5 +438,4 @@ fn test_h2_service_error() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(b"error")); assert_eq!(bytes, Bytes::from_static(b"error"));
})
} }

View File

@ -2,23 +2,22 @@ use std::io::{Read, Write};
use std::time::Duration; use std::time::Duration;
use std::{net, thread}; use std::{net, thread};
use actix_http_test::{block_on, TestServer}; use actix_http_test::TestServer;
use actix_rt::time::delay_for;
use actix_server_config::ServerConfig; use actix_server_config::ServerConfig;
use actix_service::{factory_fn_cfg, pipeline, service_fn, ServiceFactory}; use actix_service::{factory_fn_cfg, pipeline, service_fn, ServiceFactory};
use bytes::Bytes; use bytes::Bytes;
use futures::future::{self, err, ok, ready, FutureExt}; use futures::future::{self, err, ok, ready, FutureExt};
use futures::stream::{once, StreamExt}; use futures::stream::{once, StreamExt};
use regex::Regex; use regex::Regex;
use tokio_timer::delay_for;
use actix_http::httpmessage::HttpMessage; use actix_http::httpmessage::HttpMessage;
use actix_http::{ use actix_http::{
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response, body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
}; };
#[test] #[actix_rt::test]
fn test_h1() { async fn test_h1() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.keep_alive(KeepAlive::Disabled) .keep_alive(KeepAlive::Disabled)
@ -32,12 +31,10 @@ fn test_h1() {
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }
#[test] #[actix_rt::test]
fn test_h1_2() { async fn test_h1_2() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.keep_alive(KeepAlive::Disabled) .keep_alive(KeepAlive::Disabled)
@ -53,12 +50,10 @@ fn test_h1_2() {
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }
#[test] #[actix_rt::test]
fn test_expect_continue() { async fn test_expect_continue() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.expect(service_fn(|req: Request| { .expect(service_fn(|req: Request| {
@ -78,17 +73,14 @@ fn test_expect_continue() {
assert!(data.starts_with("HTTP/1.1 412 Precondition Failed\r\ncontent-length")); assert!(data.starts_with("HTTP/1.1 412 Precondition Failed\r\ncontent-length"));
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
let _ = let _ = stream.write_all(b"GET /test?yes= HTTP/1.1\r\nexpect: 100-continue\r\n\r\n");
stream.write_all(b"GET /test?yes= HTTP/1.1\r\nexpect: 100-continue\r\n\r\n");
let mut data = String::new(); let mut data = String::new();
let _ = stream.read_to_string(&mut data); let _ = stream.read_to_string(&mut data);
assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n")); assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n"));
})
} }
#[test] #[actix_rt::test]
fn test_expect_continue_h1() { async fn test_expect_continue_h1() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.expect(service_fn(|req: Request| { .expect(service_fn(|req: Request| {
@ -110,17 +102,14 @@ fn test_expect_continue_h1() {
assert!(data.starts_with("HTTP/1.1 412 Precondition Failed\r\ncontent-length")); assert!(data.starts_with("HTTP/1.1 412 Precondition Failed\r\ncontent-length"));
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
let _ = let _ = stream.write_all(b"GET /test?yes= HTTP/1.1\r\nexpect: 100-continue\r\n\r\n");
stream.write_all(b"GET /test?yes= HTTP/1.1\r\nexpect: 100-continue\r\n\r\n");
let mut data = String::new(); let mut data = String::new();
let _ = stream.read_to_string(&mut data); let _ = stream.read_to_string(&mut data);
assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n")); assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n"));
})
} }
#[test] #[actix_rt::test]
fn test_chunked_payload() { async fn test_chunked_payload() {
block_on(async {
let chunk_sizes = vec![32768, 32, 32768]; let chunk_sizes = vec![32768, 32, 32768];
let total_size: usize = chunk_sizes.iter().sum(); let total_size: usize = chunk_sizes.iter().sum();
@ -164,20 +153,16 @@ fn test_chunked_payload() {
let re = Regex::new(r"size=(\d+)").unwrap(); let re = Regex::new(r"size=(\d+)").unwrap();
let size: usize = match re.captures(&data) { let size: usize = match re.captures(&data) {
Some(caps) => caps.get(1).unwrap().as_str().parse().unwrap(), Some(caps) => caps.get(1).unwrap().as_str().parse().unwrap(),
None => { None => panic!(format!("Failed to find size in HTTP Response: {}", data)),
panic!(format!("Failed to find size in HTTP Response: {}", data))
}
}; };
size size
}; };
assert_eq!(returned_size, total_size); assert_eq!(returned_size, total_size);
})
} }
#[test] #[actix_rt::test]
fn test_slow_request() { async fn test_slow_request() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.client_timeout(100) .client_timeout(100)
@ -189,12 +174,10 @@ fn test_slow_request() {
let mut data = String::new(); let mut data = String::new();
let _ = stream.read_to_string(&mut data); let _ = stream.read_to_string(&mut data);
assert!(data.starts_with("HTTP/1.1 408 Request Timeout")); assert!(data.starts_with("HTTP/1.1 408 Request Timeout"));
})
} }
#[test] #[actix_rt::test]
fn test_http1_malformed_request() { async fn test_http1_malformed_request() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish())) HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
}); });
@ -204,12 +187,10 @@ fn test_http1_malformed_request() {
let mut data = String::new(); let mut data = String::new();
let _ = stream.read_to_string(&mut data); let _ = stream.read_to_string(&mut data);
assert!(data.starts_with("HTTP/1.1 400 Bad Request")); assert!(data.starts_with("HTTP/1.1 400 Bad Request"));
})
} }
#[test] #[actix_rt::test]
fn test_http1_keepalive() { async fn test_http1_keepalive() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish())) HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
}); });
@ -224,12 +205,10 @@ fn test_http1_keepalive() {
let mut data = vec![0; 1024]; let mut data = vec![0; 1024];
let _ = stream.read(&mut data); let _ = stream.read(&mut data);
assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n"); assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");
})
} }
#[test] #[actix_rt::test]
fn test_http1_keepalive_timeout() { async fn test_http1_keepalive_timeout() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.keep_alive(1) .keep_alive(1)
@ -246,19 +225,17 @@ fn test_http1_keepalive_timeout() {
let mut data = vec![0; 1024]; let mut data = vec![0; 1024];
let res = stream.read(&mut data).unwrap(); let res = stream.read(&mut data).unwrap();
assert_eq!(res, 0); assert_eq!(res, 0);
})
} }
#[test] #[actix_rt::test]
fn test_http1_keepalive_close() { async fn test_http1_keepalive_close() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish())) HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
}); });
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
let _ = stream let _ =
.write_all(b"GET /test/tests/test HTTP/1.1\r\nconnection: close\r\n\r\n"); stream.write_all(b"GET /test/tests/test HTTP/1.1\r\nconnection: close\r\n\r\n");
let mut data = vec![0; 1024]; let mut data = vec![0; 1024];
let _ = stream.read(&mut data); let _ = stream.read(&mut data);
assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n"); assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");
@ -266,12 +243,10 @@ fn test_http1_keepalive_close() {
let mut data = vec![0; 1024]; let mut data = vec![0; 1024];
let res = stream.read(&mut data).unwrap(); let res = stream.read(&mut data).unwrap();
assert_eq!(res, 0); assert_eq!(res, 0);
})
} }
#[test] #[actix_rt::test]
fn test_http10_keepalive_default_close() { async fn test_http10_keepalive_default_close() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish())) HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
}); });
@ -285,20 +260,17 @@ fn test_http10_keepalive_default_close() {
let mut data = vec![0; 1024]; let mut data = vec![0; 1024];
let res = stream.read(&mut data).unwrap(); let res = stream.read(&mut data).unwrap();
assert_eq!(res, 0); assert_eq!(res, 0);
})
} }
#[test] #[actix_rt::test]
fn test_http10_keepalive() { async fn test_http10_keepalive() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish())) HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
}); });
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
let _ = stream.write_all( let _ = stream
b"GET /test/tests/test HTTP/1.0\r\nconnection: keep-alive\r\n\r\n", .write_all(b"GET /test/tests/test HTTP/1.0\r\nconnection: keep-alive\r\n\r\n");
);
let mut data = vec![0; 1024]; let mut data = vec![0; 1024];
let _ = stream.read(&mut data); let _ = stream.read(&mut data);
assert_eq!(&data[..17], b"HTTP/1.0 200 OK\r\n"); assert_eq!(&data[..17], b"HTTP/1.0 200 OK\r\n");
@ -312,12 +284,10 @@ fn test_http10_keepalive() {
let mut data = vec![0; 1024]; let mut data = vec![0; 1024];
let res = stream.read(&mut data).unwrap(); let res = stream.read(&mut data).unwrap();
assert_eq!(res, 0); assert_eq!(res, 0);
})
} }
#[test] #[actix_rt::test]
fn test_http1_keepalive_disabled() { async fn test_http1_keepalive_disabled() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.keep_alive(KeepAlive::Disabled) .keep_alive(KeepAlive::Disabled)
@ -333,12 +303,10 @@ fn test_http1_keepalive_disabled() {
let mut data = vec![0; 1024]; let mut data = vec![0; 1024];
let res = stream.read(&mut data).unwrap(); let res = stream.read(&mut data).unwrap();
assert_eq!(res, 0); assert_eq!(res, 0);
})
} }
#[test] #[actix_rt::test]
fn test_content_length() { async fn test_content_length() {
block_on(async {
use actix_http::http::{ use actix_http::http::{
header::{HeaderName, HeaderValue}, header::{HeaderName, HeaderValue},
StatusCode, StatusCode,
@ -379,12 +347,10 @@ fn test_content_length() {
assert_eq!(response.headers().get(&header), Some(&value)); assert_eq!(response.headers().get(&header), Some(&value));
} }
} }
})
} }
#[test] #[actix_rt::test]
fn test_h1_headers() { async fn test_h1_headers() {
block_on(async {
let data = STR.repeat(10); let data = STR.repeat(10);
let data2 = data.clone(); let data2 = data.clone();
@ -420,7 +386,6 @@ fn test_h1_headers() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from(data2)); assert_eq!(bytes, Bytes::from(data2));
})
} }
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
@ -445,9 +410,8 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World"; Hello World Hello World Hello World Hello World Hello World";
#[test] #[actix_rt::test]
fn test_h1_body() { async fn test_h1_body() {
block_on(async {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| ok::<_, ()>(Response::Ok().body(STR))) HttpService::build().h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
}); });
@ -458,12 +422,10 @@ fn test_h1_body() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_h1_head_empty() { async fn test_h1_head_empty() {
block_on(async {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| ok::<_, ()>(Response::Ok().body(STR))) HttpService::build().h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
}); });
@ -482,12 +444,10 @@ fn test_h1_head_empty() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert!(bytes.is_empty()); assert!(bytes.is_empty());
})
} }
#[test] #[actix_rt::test]
fn test_h1_head_binary() { async fn test_h1_head_binary() {
block_on(async {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| { HttpService::build().h1(|_| {
ok::<_, ()>(Response::Ok().content_length(STR.len() as u64).body(STR)) ok::<_, ()>(Response::Ok().content_length(STR.len() as u64).body(STR))
@ -508,12 +468,10 @@ fn test_h1_head_binary() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert!(bytes.is_empty()); assert!(bytes.is_empty());
})
} }
#[test] #[actix_rt::test]
fn test_h1_head_binary2() { async fn test_h1_head_binary2() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build().h1(|_| ok::<_, ()>(Response::Ok().body(STR))) HttpService::build().h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
}); });
@ -528,12 +486,10 @@ fn test_h1_head_binary2() {
.unwrap(); .unwrap();
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
} }
})
} }
#[test] #[actix_rt::test]
fn test_h1_body_length() { async fn test_h1_body_length() {
block_on(async {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| { HttpService::build().h1(|_| {
let body = once(ok(Bytes::from_static(STR.as_ref()))); let body = once(ok(Bytes::from_static(STR.as_ref())));
@ -549,12 +505,10 @@ fn test_h1_body_length() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_h1_body_chunked_explicit() { async fn test_h1_body_chunked_explicit() {
block_on(async {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| { HttpService::build().h1(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
@ -583,12 +537,10 @@ fn test_h1_body_chunked_explicit() {
// decode // decode
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_h1_body_chunked_implicit() { async fn test_h1_body_chunked_implicit() {
block_on(async {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| { HttpService::build().h1(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
@ -611,12 +563,10 @@ fn test_h1_body_chunked_implicit() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_h1_response_http_error_handling() { async fn test_h1_response_http_error_handling() {
block_on(async {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build().h1(factory_fn_cfg(|_: &ServerConfig| { HttpService::build().h1(factory_fn_cfg(|_: &ServerConfig| {
ok::<_, ()>(pipeline(|_| { ok::<_, ()>(pipeline(|_| {
@ -636,12 +586,10 @@ fn test_h1_response_http_error_handling() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value")); assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
})
} }
#[test] #[actix_rt::test]
fn test_h1_service_error() { async fn test_h1_service_error() {
block_on(async {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.h1(|_| future::err::<Response, Error>(error::ErrorBadRequest("error"))) .h1(|_| future::err::<Response, Error>(error::ErrorBadRequest("error")))
@ -653,12 +601,10 @@ fn test_h1_service_error() {
// read response // read response
let bytes = srv.load_body(response).await.unwrap(); let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(b"error")); assert_eq!(bytes, Bytes::from_static(b"error"));
})
} }
#[test] #[actix_rt::test]
fn test_h1_on_connect() { async fn test_h1_on_connect() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.on_connect(|_| 10usize) .on_connect(|_| 10usize)
@ -670,5 +616,4 @@ fn test_h1_on_connect() {
let response = srv.get("/").send().await.unwrap(); let response = srv.get("/").send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }

View File

@ -1,6 +1,6 @@
use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_http::{body, h1, ws, Error, HttpService, Request, Response}; use actix_http::{body, h1, ws, Error, HttpService, Request, Response};
use actix_http_test::{block_on, TestServer}; use actix_http_test::TestServer;
use actix_utils::framed::FramedTransport; use actix_utils::framed::FramedTransport;
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures::future; use futures::future;
@ -34,9 +34,8 @@ async fn service(msg: ws::Frame) -> Result<ws::Message, Error> {
Ok(msg) Ok(msg)
} }
#[test] #[actix_rt::test]
fn test_simple() { async fn test_simple() {
block_on(async {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.upgrade(actix_service::service_fn(ws_service)) .upgrade(actix_service::service_fn(ws_service))
@ -82,5 +81,4 @@ fn test_simple() {
item.unwrap().unwrap(), item.unwrap().unwrap(),
ws::Frame::Close(Some(ws::CloseCode::Normal.into())) ws::Frame::Close(Some(ws::CloseCode::Normal.into()))
); );
})
} }

View File

@ -607,16 +607,15 @@ mod tests {
use super::*; use super::*;
use actix_web::http::StatusCode; use actix_web::http::StatusCode;
use actix_web::test::{self, block_on, TestRequest}; use actix_web::test::{self, TestRequest};
use actix_web::{web, App, Error, HttpResponse}; use actix_web::{web, App, Error, HttpResponse};
const COOKIE_KEY_MASTER: [u8; 32] = [0; 32]; const COOKIE_KEY_MASTER: [u8; 32] = [0; 32];
const COOKIE_NAME: &'static str = "actix_auth"; const COOKIE_NAME: &'static str = "actix_auth";
const COOKIE_LOGIN: &'static str = "test"; const COOKIE_LOGIN: &'static str = "test";
#[test] #[actix_rt::test]
fn test_identity() { async fn test_identity() {
block_on(async {
let mut srv = test::init_service( let mut srv = test::init_service(
App::new() App::new()
.wrap(IdentityService::new( .wrap(IdentityService::new(
@ -647,17 +646,13 @@ mod tests {
})), })),
) )
.await; .await;
let resp = test::call_service( let resp =
&mut srv, test::call_service(&mut srv, TestRequest::with_uri("/index").to_request())
TestRequest::with_uri("/index").to_request(),
)
.await; .await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
let resp = test::call_service( let resp =
&mut srv, test::call_service(&mut srv, TestRequest::with_uri("/login").to_request())
TestRequest::with_uri("/login").to_request(),
)
.await; .await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
let c = resp.response().cookies().next().unwrap().to_owned(); let c = resp.response().cookies().next().unwrap().to_owned();
@ -680,12 +675,10 @@ mod tests {
.await; .await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert!(resp.headers().contains_key(header::SET_COOKIE)) assert!(resp.headers().contains_key(header::SET_COOKIE))
})
} }
#[test] #[actix_rt::test]
fn test_identity_max_age_time() { async fn test_identity_max_age_time() {
block_on(async {
let duration = Duration::days(1); let duration = Duration::days(1);
let mut srv = test::init_service( let mut srv = test::init_service(
App::new() App::new()
@ -703,21 +696,17 @@ mod tests {
})), })),
) )
.await; .await;
let resp = test::call_service( let resp =
&mut srv, test::call_service(&mut srv, TestRequest::with_uri("/login").to_request())
TestRequest::with_uri("/login").to_request(),
)
.await; .await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert!(resp.headers().contains_key(header::SET_COOKIE)); assert!(resp.headers().contains_key(header::SET_COOKIE));
let c = resp.response().cookies().next().unwrap().to_owned(); let c = resp.response().cookies().next().unwrap().to_owned();
assert_eq!(duration, c.max_age().unwrap()); assert_eq!(duration, c.max_age().unwrap());
})
} }
#[test] #[actix_rt::test]
fn test_identity_max_age() { async fn test_identity_max_age() {
block_on(async {
let seconds = 60; let seconds = 60;
let mut srv = test::init_service( let mut srv = test::init_service(
App::new() App::new()
@ -735,16 +724,13 @@ mod tests {
})), })),
) )
.await; .await;
let resp = test::call_service( let resp =
&mut srv, test::call_service(&mut srv, TestRequest::with_uri("/login").to_request())
TestRequest::with_uri("/login").to_request(),
)
.await; .await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert!(resp.headers().contains_key(header::SET_COOKIE)); assert!(resp.headers().contains_key(header::SET_COOKIE));
let c = resp.response().cookies().next().unwrap().to_owned(); let c = resp.response().cookies().next().unwrap().to_owned();
assert_eq!(Duration::seconds(seconds as i64), c.max_age().unwrap()); assert_eq!(Duration::seconds(seconds as i64), c.max_age().unwrap());
})
} }
async fn create_identity_server< async fn create_identity_server<
@ -885,21 +871,17 @@ mod tests {
assert!(cookies.get(COOKIE_NAME).is_none()); assert!(cookies.get(COOKIE_NAME).is_none());
} }
#[test] #[actix_rt::test]
fn test_identity_legacy_cookie_is_set() { async fn test_identity_legacy_cookie_is_set() {
block_on(async {
let mut srv = create_identity_server(|c| c).await; let mut srv = create_identity_server(|c| c).await;
let mut resp = let mut resp =
test::call_service(&mut srv, TestRequest::with_uri("/").to_request()) test::call_service(&mut srv, TestRequest::with_uri("/").to_request()).await;
.await;
assert_legacy_login_cookie(&mut resp, COOKIE_LOGIN); assert_legacy_login_cookie(&mut resp, COOKIE_LOGIN);
assert_logged_in(resp, None).await; assert_logged_in(resp, None).await;
})
} }
#[test] #[actix_rt::test]
fn test_identity_legacy_cookie_works() { async fn test_identity_legacy_cookie_works() {
block_on(async {
let mut srv = create_identity_server(|c| c).await; let mut srv = create_identity_server(|c| c).await;
let cookie = legacy_login_cookie(COOKIE_LOGIN); let cookie = legacy_login_cookie(COOKIE_LOGIN);
let mut resp = test::call_service( let mut resp = test::call_service(
@ -911,12 +893,10 @@ mod tests {
.await; .await;
assert_no_login_cookie(&mut resp); assert_no_login_cookie(&mut resp);
assert_logged_in(resp, Some(COOKIE_LOGIN)).await; assert_logged_in(resp, Some(COOKIE_LOGIN)).await;
})
} }
#[test] #[actix_rt::test]
fn test_identity_legacy_cookie_rejected_if_visit_timestamp_needed() { async fn test_identity_legacy_cookie_rejected_if_visit_timestamp_needed() {
block_on(async {
let mut srv = let mut srv =
create_identity_server(|c| c.visit_deadline(Duration::days(90))).await; create_identity_server(|c| c.visit_deadline(Duration::days(90))).await;
let cookie = legacy_login_cookie(COOKIE_LOGIN); let cookie = legacy_login_cookie(COOKIE_LOGIN);
@ -934,12 +914,10 @@ mod tests {
VisitTimeStampCheck::NewTimestamp, VisitTimeStampCheck::NewTimestamp,
); );
assert_logged_in(resp, None).await; assert_logged_in(resp, None).await;
})
} }
#[test] #[actix_rt::test]
fn test_identity_legacy_cookie_rejected_if_login_timestamp_needed() { async fn test_identity_legacy_cookie_rejected_if_login_timestamp_needed() {
block_on(async {
let mut srv = let mut srv =
create_identity_server(|c| c.login_deadline(Duration::days(90))).await; create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
let cookie = legacy_login_cookie(COOKIE_LOGIN); let cookie = legacy_login_cookie(COOKIE_LOGIN);
@ -957,12 +935,10 @@ mod tests {
VisitTimeStampCheck::NoTimestamp, VisitTimeStampCheck::NoTimestamp,
); );
assert_logged_in(resp, None).await; assert_logged_in(resp, None).await;
})
} }
#[test] #[actix_rt::test]
fn test_identity_cookie_rejected_if_login_timestamp_needed() { async fn test_identity_cookie_rejected_if_login_timestamp_needed() {
block_on(async {
let mut srv = let mut srv =
create_identity_server(|c| c.login_deadline(Duration::days(90))).await; create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
let cookie = login_cookie(COOKIE_LOGIN, None, Some(SystemTime::now())); let cookie = login_cookie(COOKIE_LOGIN, None, Some(SystemTime::now()));
@ -980,12 +956,10 @@ mod tests {
VisitTimeStampCheck::NoTimestamp, VisitTimeStampCheck::NoTimestamp,
); );
assert_logged_in(resp, None).await; assert_logged_in(resp, None).await;
})
} }
#[test] #[actix_rt::test]
fn test_identity_cookie_rejected_if_visit_timestamp_needed() { async fn test_identity_cookie_rejected_if_visit_timestamp_needed() {
block_on(async {
let mut srv = let mut srv =
create_identity_server(|c| c.visit_deadline(Duration::days(90))).await; create_identity_server(|c| c.visit_deadline(Duration::days(90))).await;
let cookie = login_cookie(COOKIE_LOGIN, Some(SystemTime::now()), None); let cookie = login_cookie(COOKIE_LOGIN, Some(SystemTime::now()), None);
@ -1003,12 +977,10 @@ mod tests {
VisitTimeStampCheck::NewTimestamp, VisitTimeStampCheck::NewTimestamp,
); );
assert_logged_in(resp, None).await; assert_logged_in(resp, None).await;
})
} }
#[test] #[actix_rt::test]
fn test_identity_cookie_rejected_if_login_timestamp_too_old() { async fn test_identity_cookie_rejected_if_login_timestamp_too_old() {
block_on(async {
let mut srv = let mut srv =
create_identity_server(|c| c.login_deadline(Duration::days(90))).await; create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
let cookie = login_cookie( let cookie = login_cookie(
@ -1030,12 +1002,10 @@ mod tests {
VisitTimeStampCheck::NoTimestamp, VisitTimeStampCheck::NoTimestamp,
); );
assert_logged_in(resp, None).await; assert_logged_in(resp, None).await;
})
} }
#[test] #[actix_rt::test]
fn test_identity_cookie_rejected_if_visit_timestamp_too_old() { async fn test_identity_cookie_rejected_if_visit_timestamp_too_old() {
block_on(async {
let mut srv = let mut srv =
create_identity_server(|c| c.visit_deadline(Duration::days(90))).await; create_identity_server(|c| c.visit_deadline(Duration::days(90))).await;
let cookie = login_cookie( let cookie = login_cookie(
@ -1057,12 +1027,10 @@ mod tests {
VisitTimeStampCheck::NewTimestamp, VisitTimeStampCheck::NewTimestamp,
); );
assert_logged_in(resp, None).await; assert_logged_in(resp, None).await;
})
} }
#[test] #[actix_rt::test]
fn test_identity_cookie_not_updated_on_login_deadline() { async fn test_identity_cookie_not_updated_on_login_deadline() {
block_on(async {
let mut srv = let mut srv =
create_identity_server(|c| c.login_deadline(Duration::days(90))).await; create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
let cookie = login_cookie(COOKIE_LOGIN, Some(SystemTime::now()), None); let cookie = login_cookie(COOKIE_LOGIN, Some(SystemTime::now()), None);
@ -1075,12 +1043,10 @@ mod tests {
.await; .await;
assert_no_login_cookie(&mut resp); assert_no_login_cookie(&mut resp);
assert_logged_in(resp, Some(COOKIE_LOGIN)).await; assert_logged_in(resp, Some(COOKIE_LOGIN)).await;
})
} }
#[test] #[actix_rt::test]
fn test_identity_cookie_updated_on_visit_deadline() { async fn test_identity_cookie_updated_on_visit_deadline() {
block_on(async {
let mut srv = create_identity_server(|c| { let mut srv = create_identity_server(|c| {
c.visit_deadline(Duration::days(90)) c.visit_deadline(Duration::days(90))
.login_deadline(Duration::days(90)) .login_deadline(Duration::days(90))
@ -1102,6 +1068,5 @@ mod tests {
VisitTimeStampCheck::NewTimestamp, VisitTimeStampCheck::NewTimestamp,
); );
assert_logged_in(resp, Some(COOKIE_LOGIN)).await; assert_logged_in(resp, Some(COOKIE_LOGIN)).await;
})
} }
} }

View File

@ -813,12 +813,11 @@ mod tests {
use actix_http::h1::Payload; use actix_http::h1::Payload;
use actix_utils::mpsc; use actix_utils::mpsc;
use actix_web::http::header::{DispositionParam, DispositionType}; use actix_web::http::header::{DispositionParam, DispositionType};
use actix_web::test::block_on;
use bytes::Bytes; use bytes::Bytes;
use futures::future::lazy; use futures::future::lazy;
#[test] #[actix_rt::test]
fn test_boundary() { async fn test_boundary() {
let headers = HeaderMap::new(); let headers = HeaderMap::new();
match Multipart::boundary(&headers) { match Multipart::boundary(&headers) {
Err(MultipartError::NoContentType) => (), Err(MultipartError::NoContentType) => (),
@ -891,9 +890,8 @@ mod tests {
(bytes, headers) (bytes, headers)
} }
#[test] #[actix_rt::test]
fn test_multipart_no_end_crlf() { async fn test_multipart_no_end_crlf() {
block_on(async {
let (sender, payload) = create_stream(); let (sender, payload) = create_stream();
let (bytes, headers) = create_simple_request_with_header(); let (bytes, headers) = create_simple_request_with_header();
let bytes_stripped = bytes.slice_to(bytes.len()); // strip crlf let bytes_stripped = bytes.slice_to(bytes.len()); // strip crlf
@ -917,12 +915,10 @@ mod tests {
None => (), None => (),
_ => unreachable!(), _ => unreachable!(),
} }
})
} }
#[test] #[actix_rt::test]
fn test_multipart() { async fn test_multipart() {
block_on(async {
let (sender, payload) = create_stream(); let (sender, payload) = create_stream();
let (bytes, headers) = create_simple_request_with_header(); let (bytes, headers) = create_simple_request_with_header();
@ -971,12 +967,10 @@ mod tests {
None => (), None => (),
_ => unreachable!(), _ => unreachable!(),
} }
});
} }
#[test] #[actix_rt::test]
fn test_stream() { async fn test_stream() {
block_on(async {
let (sender, payload) = create_stream(); let (sender, payload) = create_stream();
let (bytes, headers) = create_simple_request_with_header(); let (bytes, headers) = create_simple_request_with_header();
@ -1025,24 +1019,20 @@ mod tests {
None => (), None => (),
_ => unreachable!(), _ => unreachable!(),
} }
});
} }
#[test] #[actix_rt::test]
fn test_basic() { async fn test_basic() {
block_on(async {
let (_, payload) = Payload::create(false); let (_, payload) = Payload::create(false);
let mut payload = PayloadBuffer::new(payload); let mut payload = PayloadBuffer::new(payload);
assert_eq!(payload.buf.len(), 0); assert_eq!(payload.buf.len(), 0);
lazy(|cx| payload.poll_stream(cx)).await.unwrap(); lazy(|cx| payload.poll_stream(cx)).await.unwrap();
assert_eq!(None, payload.read_max(1).unwrap()); assert_eq!(None, payload.read_max(1).unwrap());
})
} }
#[test] #[actix_rt::test]
fn test_eof() { async fn test_eof() {
block_on(async {
let (mut sender, payload) = Payload::create(false); let (mut sender, payload) = Payload::create(false);
let mut payload = PayloadBuffer::new(payload); let mut payload = PayloadBuffer::new(payload);
@ -1055,23 +1045,19 @@ mod tests {
assert_eq!(payload.buf.len(), 0); assert_eq!(payload.buf.len(), 0);
assert!(payload.read_max(1).is_err()); assert!(payload.read_max(1).is_err());
assert!(payload.eof); assert!(payload.eof);
})
} }
#[test] #[actix_rt::test]
fn test_err() { async fn test_err() {
block_on(async {
let (mut sender, payload) = Payload::create(false); let (mut sender, payload) = Payload::create(false);
let mut payload = PayloadBuffer::new(payload); let mut payload = PayloadBuffer::new(payload);
assert_eq!(None, payload.read_max(1).unwrap()); assert_eq!(None, payload.read_max(1).unwrap());
sender.set_error(PayloadError::Incomplete(None)); sender.set_error(PayloadError::Incomplete(None));
lazy(|cx| payload.poll_stream(cx)).await.err().unwrap(); lazy(|cx| payload.poll_stream(cx)).await.err().unwrap();
})
} }
#[test] #[actix_rt::test]
fn test_readmax() { async fn test_readmax() {
block_on(async {
let (mut sender, payload) = Payload::create(false); let (mut sender, payload) = Payload::create(false);
let mut payload = PayloadBuffer::new(payload); let mut payload = PayloadBuffer::new(payload);
@ -1085,12 +1071,10 @@ mod tests {
assert_eq!(Some(Bytes::from("line2")), payload.read_max(5).unwrap()); assert_eq!(Some(Bytes::from("line2")), payload.read_max(5).unwrap());
assert_eq!(payload.buf.len(), 0); assert_eq!(payload.buf.len(), 0);
})
} }
#[test] #[actix_rt::test]
fn test_readexactly() { async fn test_readexactly() {
block_on(async {
let (mut sender, payload) = Payload::create(false); let (mut sender, payload) = Payload::create(false);
let mut payload = PayloadBuffer::new(payload); let mut payload = PayloadBuffer::new(payload);
@ -1105,12 +1089,10 @@ mod tests {
assert_eq!(Some(Bytes::from_static(b"ne1l")), payload.read_exact(4)); assert_eq!(Some(Bytes::from_static(b"ne1l")), payload.read_exact(4));
assert_eq!(payload.buf.len(), 4); assert_eq!(payload.buf.len(), 4);
})
} }
#[test] #[actix_rt::test]
fn test_readuntil() { async fn test_readuntil() {
block_on(async {
let (mut sender, payload) = Payload::create(false); let (mut sender, payload) = Payload::create(false);
let mut payload = PayloadBuffer::new(payload); let mut payload = PayloadBuffer::new(payload);
@ -1131,6 +1113,5 @@ mod tests {
payload.read_until(b"2").unwrap() payload.read_until(b"2").unwrap()
); );
assert_eq!(payload.buf.len(), 0); assert_eq!(payload.buf.len(), 0);
})
} }
} }

View File

@ -364,9 +364,8 @@ mod tests {
use actix_web::{test, web, App}; use actix_web::{test, web, App};
use bytes::Bytes; use bytes::Bytes;
#[test] #[actix_rt::test]
fn cookie_session() { async fn cookie_session() {
test::block_on(async {
let mut app = test::init_service( let mut app = test::init_service(
App::new() App::new()
.wrap(CookieSession::signed(&[0; 32]).secure(false)) .wrap(CookieSession::signed(&[0; 32]).secure(false))
@ -386,12 +385,10 @@ mod tests {
.cookies() .cookies()
.find(|c| c.name() == "actix-session") .find(|c| c.name() == "actix-session")
.is_some()); .is_some());
})
} }
#[test] #[actix_rt::test]
fn private_cookie() { async fn private_cookie() {
test::block_on(async {
let mut app = test::init_service( let mut app = test::init_service(
App::new() App::new()
.wrap(CookieSession::private(&[0; 32]).secure(false)) .wrap(CookieSession::private(&[0; 32]).secure(false))
@ -411,12 +408,10 @@ mod tests {
.cookies() .cookies()
.find(|c| c.name() == "actix-session") .find(|c| c.name() == "actix-session")
.is_some()); .is_some());
})
} }
#[test] #[actix_rt::test]
fn cookie_session_extractor() { async fn cookie_session_extractor() {
test::block_on(async {
let mut app = test::init_service( let mut app = test::init_service(
App::new() App::new()
.wrap(CookieSession::signed(&[0; 32]).secure(false)) .wrap(CookieSession::signed(&[0; 32]).secure(false))
@ -436,12 +431,10 @@ mod tests {
.cookies() .cookies()
.find(|c| c.name() == "actix-session") .find(|c| c.name() == "actix-session")
.is_some()); .is_some());
})
} }
#[test] #[actix_rt::test]
fn basics() { async fn basics() {
test::block_on(async {
let mut app = test::init_service( let mut app = test::init_service(
App::new() App::new()
.wrap( .wrap(
@ -483,6 +476,5 @@ mod tests {
.to_request(); .to_request();
let body = test::read_response(&mut app, request).await; let body = test::read_response(&mut app, request).await;
assert_eq!(body, Bytes::from_static(b"counter: 100")); assert_eq!(body, Bytes::from_static(b"counter: 100"));
})
} }
} }

View File

@ -17,6 +17,7 @@ syn = { version = "^1", features = ["full", "parsing"] }
proc-macro2 = "^1" proc-macro2 = "^1"
[dev-dependencies] [dev-dependencies]
actix-rt = { version = "1.0.0-alpha.1" }
actix-web = { version = "2.0.0-alpha.1" } actix-web = { version = "2.0.0-alpha.1" }
actix-http = { version = "0.3.0-alpha.1", features=["openssl"] } actix-http = { version = "0.3.0-alpha.1", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] } actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] }

View File

@ -1,5 +1,5 @@
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::{block_on, TestServer}; use actix_http_test::TestServer;
use actix_web::{http, web::Path, App, HttpResponse, Responder}; use actix_web::{http, web::Path, App, HttpResponse, Responder};
use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, trace}; use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, trace};
use futures::{future, Future}; use futures::{future, Future};
@ -69,9 +69,8 @@ async fn get_param_test(_: Path<String>) -> impl Responder {
HttpResponse::Ok() HttpResponse::Ok()
} }
#[test] #[actix_rt::test]
fn test_params() { async fn test_params() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new( HttpService::new(
App::new() App::new()
@ -92,12 +91,10 @@ fn test_params() {
let request = srv.request(http::Method::DELETE, srv.url("/test/it")); let request = srv.request(http::Method::DELETE, srv.url("/test/it"));
let response = request.send().await.unwrap(); let response = request.send().await.unwrap();
assert_eq!(response.status(), http::StatusCode::NO_CONTENT); assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
})
} }
#[test] #[actix_rt::test]
fn test_body() { async fn test_body() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new( HttpService::new(
App::new() App::new()
@ -148,16 +145,13 @@ fn test_body() {
let request = srv.request(http::Method::GET, srv.url("/test")); let request = srv.request(http::Method::GET, srv.url("/test"));
let response = request.send().await.unwrap(); let response = request.send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }
#[test] #[actix_rt::test]
fn test_auto_async() { async fn test_auto_async() {
block_on(async {
let srv = TestServer::start(|| HttpService::new(App::new().service(auto_async))); let srv = TestServer::start(|| HttpService::new(App::new().service(auto_async)));
let request = srv.request(http::Method::GET, srv.url("/test")); let request = srv.request(http::Method::GET, srv.url("/test"));
let response = request.send().await.unwrap(); let response = request.send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }

View File

@ -30,7 +30,7 @@ default = ["brotli", "flate2-zlib"]
openssl = ["open-ssl", "actix-http/openssl"] openssl = ["open-ssl", "actix-http/openssl"]
# rustls # rustls
# rustls = ["rust-tls", "actix-http/rustls"] rustls = ["rust-tls", "actix-http/rustls"]
# brotli encoding, requires c compiler # brotli encoding, requires c compiler
brotli = ["actix-http/brotli"] brotli = ["actix-http/brotli"]
@ -45,6 +45,7 @@ flate2-rust = ["actix-http/flate2-rust"]
actix-codec = "0.2.0-alpha.1" actix-codec = "0.2.0-alpha.1"
actix-service = "1.0.0-alpha.1" actix-service = "1.0.0-alpha.1"
actix-http = "0.3.0-alpha.1" actix-http = "0.3.0-alpha.1"
actix-rt = "1.0.0-alpha.1"
base64 = "0.10.1" base64 = "0.10.1"
bytes = "0.4" bytes = "0.4"
@ -57,12 +58,10 @@ rand = "0.7"
serde = "1.0" serde = "1.0"
serde_json = "1.0" serde_json = "1.0"
serde_urlencoded = "0.6.1" serde_urlencoded = "0.6.1"
tokio-timer = "0.3.0-alpha.6"
open-ssl = { version="0.10", package="openssl", optional = true } open-ssl = { version="0.10", package="openssl", optional = true }
rust-tls = { version = "0.16.0", package="rustls", optional = true, features = ["dangerous_configuration"] } rust-tls = { version = "0.16.0", package="rustls", optional = true, features = ["dangerous_configuration"] }
[dev-dependencies] [dev-dependencies]
actix-rt = "1.0.0-alpha.1"
actix-connect = { version = "1.0.0-alpha.1", features=["openssl"] } actix-connect = { version = "1.0.0-alpha.1", features=["openssl"] }
actix-web = { version = "2.0.0-alpha.1", features=["openssl"] } actix-web = { version = "2.0.0-alpha.1", features=["openssl"] }
actix-http = { version = "0.3.0-alpha.1", features=["openssl"] } actix-http = { version = "0.3.0-alpha.1", features=["openssl"] }
@ -73,5 +72,4 @@ brotli2 = { version="0.3.2" }
flate2 = { version="1.0.2" } flate2 = { version="1.0.2" }
env_logger = "0.6" env_logger = "0.6"
rand = "0.7" rand = "0.7"
tokio-tcp = "0.1"
webpki = { version = "0.21" } webpki = { version = "0.21" }

View File

@ -6,19 +6,16 @@
//! use actix_rt::System; //! use actix_rt::System;
//! use awc::Client; //! use awc::Client;
//! //!
//! fn main() { //! #[actix_rt::main]
//! System::new("test").block_on(async { //! async fn main() {
//! let mut client = Client::default(); //! let mut client = Client::default();
//! //!
//! client.get("http://www.rust-lang.org") // <- Create request builder //! let response = client.get("http://www.rust-lang.org") // <- Create request builder
//! .header("User-Agent", "Actix-web") //! .header("User-Agent", "Actix-web")
//! .send() // <- Send http request //! .send() // <- Send http request
//! .await //! .await;
//! .and_then(|response| { // <- server http response //!
//! println!("Response: {:?}", response); //! println!("Response: {:?}", response);
//! Ok(())
//! })
//! });
//! } //! }
//! ``` //! ```
use std::cell::RefCell; use std::cell::RefCell;

View File

@ -39,8 +39,8 @@ const HTTPS_ENCODING: &str = "gzip, deflate";
/// ```rust /// ```rust
/// use actix_rt::System; /// use actix_rt::System;
/// ///
/// fn main() { /// #[actix_rt::main]
/// System::new("test").block_on(async { /// async fn main() {
/// let response = awc::Client::new() /// let response = awc::Client::new()
/// .get("http://www.rust-lang.org") // <- Create request builder /// .get("http://www.rust-lang.org") // <- Create request builder
/// .header("User-Agent", "Actix-web") /// .header("User-Agent", "Actix-web")
@ -50,7 +50,6 @@ const HTTPS_ENCODING: &str = "gzip, deflate";
/// response.and_then(|response| { // <- server http response /// response.and_then(|response| { // <- server http response
/// println!("Response: {:?}", response); /// println!("Response: {:?}", response);
/// Ok(()) /// Ok(())
/// })
/// }); /// });
/// } /// }
/// ``` /// ```
@ -308,10 +307,9 @@ impl ClientRequest {
/// Set a cookie /// Set a cookie
/// ///
/// ```rust /// ```rust
/// # use actix_rt::System; /// #[actix_rt::main]
/// fn main() { /// async fn main() {
/// System::new("test").block_on(async { /// let resp = awc::Client::new().get("https://www.rust-lang.org")
/// awc::Client::new().get("https://www.rust-lang.org")
/// .cookie( /// .cookie(
/// awc::http::Cookie::build("name", "value") /// awc::http::Cookie::build("name", "value")
/// .domain("www.rust-lang.org") /// .domain("www.rust-lang.org")
@ -321,12 +319,9 @@ impl ClientRequest {
/// .finish(), /// .finish(),
/// ) /// )
/// .send() /// .send()
/// .await /// .await;
/// .and_then(|response| { ///
/// println!("Response: {:?}", response); /// println!("Response: {:?}", resp);
/// Ok(())
/// })
/// });
/// } /// }
/// ``` /// ```
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self { pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {

View File

@ -358,16 +358,13 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use actix_http_test::block_on;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{http::header, test::TestResponse}; use crate::{http::header, test::TestResponse};
#[test] #[actix_rt::test]
fn test_body() { async fn test_body() {
block_on(async { let mut req = TestResponse::with_header(header::CONTENT_LENGTH, "xxxx").finish();
let mut req =
TestResponse::with_header(header::CONTENT_LENGTH, "xxxx").finish();
match req.body().await.err().unwrap() { match req.body().await.err().unwrap() {
PayloadError::UnknownLength => (), PayloadError::UnknownLength => (),
_ => unreachable!("error"), _ => unreachable!("error"),
@ -392,7 +389,6 @@ mod tests {
PayloadError::Overflow => (), PayloadError::Overflow => (),
_ => unreachable!("error"), _ => unreachable!("error"),
} }
})
} }
#[derive(Serialize, Deserialize, PartialEq, Debug)] #[derive(Serialize, Deserialize, PartialEq, Debug)]
@ -414,9 +410,8 @@ mod tests {
} }
} }
#[test] #[actix_rt::test]
fn test_json_body() { async fn test_json_body() {
block_on(async {
let mut req = TestResponse::default().finish(); let mut req = TestResponse::default().finish();
let json = JsonBody::<_, MyObject>::new(&mut req).await; let json = JsonBody::<_, MyObject>::new(&mut req).await;
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType)); assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
@ -466,6 +461,5 @@ mod tests {
name: "test".to_owned() name: "test".to_owned()
} }
); );
})
} }
} }

View File

@ -4,12 +4,12 @@ use std::rc::Rc;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use std::time::Duration; use std::time::Duration;
use actix_rt::time::{delay_for, Delay};
use bytes::Bytes; use bytes::Bytes;
use derive_more::From; use derive_more::From;
use futures::{future::LocalBoxFuture, ready, Future, Stream}; use futures::{future::LocalBoxFuture, ready, Future, Stream};
use serde::Serialize; use serde::Serialize;
use serde_json; use serde_json;
use tokio_timer::{delay_for, Delay};
use actix_http::body::{Body, BodyStream}; use actix_http::body::{Body, BodyStream};
use actix_http::encoding::Decoder; use actix_http::encoding::Decoder;

View File

@ -7,8 +7,8 @@ use std::{fmt, str};
use actix_codec::Framed; use actix_codec::Framed;
use actix_http::cookie::{Cookie, CookieJar}; use actix_http::cookie::{Cookie, CookieJar};
use actix_http::{ws, Payload, RequestHead}; use actix_http::{ws, Payload, RequestHead};
use actix_rt::time::Timeout;
use percent_encoding::percent_encode; use percent_encoding::percent_encode;
use tokio_timer::Timeout;
use actix_http::cookie::USERINFO; use actix_http::cookie::USERINFO;
pub use actix_http::ws::{CloseCode, CloseReason, Codec, Frame, Message}; pub use actix_http::ws::{CloseCode, CloseReason, Codec, Frame, Message};
@ -389,21 +389,19 @@ impl fmt::Debug for WebsocketsRequest {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use actix_web::test::block_on;
use super::*; use super::*;
use crate::Client; use crate::Client;
#[test] #[actix_rt::test]
fn test_debug() { async fn test_debug() {
let request = Client::new().ws("/").header("x-test", "111"); let request = Client::new().ws("/").header("x-test", "111");
let repr = format!("{:?}", request); let repr = format!("{:?}", request);
assert!(repr.contains("WebsocketsRequest")); assert!(repr.contains("WebsocketsRequest"));
assert!(repr.contains("x-test")); assert!(repr.contains("x-test"));
} }
#[test] #[actix_rt::test]
fn test_header_override() { async fn test_header_override() {
let req = Client::build() let req = Client::build()
.header(header::CONTENT_TYPE, "111") .header(header::CONTENT_TYPE, "111")
.finish() .finish()
@ -421,8 +419,8 @@ mod tests {
); );
} }
#[test] #[actix_rt::test]
fn basic_auth() { async fn basic_auth() {
let req = Client::new() let req = Client::new()
.ws("/") .ws("/")
.basic_auth("username", Some("password")); .basic_auth("username", Some("password"));
@ -448,8 +446,8 @@ mod tests {
); );
} }
#[test] #[actix_rt::test]
fn bearer_auth() { async fn bearer_auth() {
let req = Client::new().ws("/").bearer_auth("someS3cr3tAutht0k3n"); let req = Client::new().ws("/").bearer_auth("someS3cr3tAutht0k3n");
assert_eq!( assert_eq!(
req.head req.head
@ -463,9 +461,8 @@ mod tests {
let _ = req.connect(); let _ = req.connect();
} }
#[test] #[actix_rt::test]
fn basics() { async fn basics() {
block_on(async {
let req = Client::new() let req = Client::new()
.ws("http://localhost/") .ws("http://localhost/")
.origin("test-origin") .origin("test-origin")
@ -492,6 +489,5 @@ mod tests {
assert!(Client::new().ws("/").connect().await.is_err()); assert!(Client::new().ws("/").connect().await.is_err());
assert!(Client::new().ws("http:///test").connect().await.is_err()); assert!(Client::new().ws("http:///test").connect().await.is_err());
assert!(Client::new().ws("hmm://test.com/").connect().await.is_err()); assert!(Client::new().ws("hmm://test.com/").connect().await.is_err());
})
} }
} }

View File

@ -13,7 +13,7 @@ use futures::future::ok;
use rand::Rng; use rand::Rng;
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::{block_on, TestServer}; use actix_http_test::TestServer;
use actix_service::pipeline_factory; use actix_service::pipeline_factory;
use actix_web::http::Cookie; use actix_web::http::Cookie;
use actix_web::middleware::{BodyEncoding, Compress}; use actix_web::middleware::{BodyEncoding, Compress};
@ -42,10 +42,10 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World"; Hello World Hello World Hello World Hello World Hello World";
#[test] #[actix_rt::test]
fn test_simple() { async fn test_simple() {
block_on(async { let srv =
let srv = TestServer::start(|| { TestServer::start(|| {
HttpService::new(App::new().service( HttpService::new(App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))), web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
)) ))
@ -69,19 +69,14 @@ fn test_simple() {
// camel case // camel case
let response = srv.post("/").camel_case().send().await.unwrap(); let response = srv.post("/").camel_case().send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }
#[test] #[actix_rt::test]
fn test_json() { async fn test_json() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new( HttpService::new(App::new().service(
App::new().service( web::resource("/").route(web::to(|_: web::Json<String>| HttpResponse::Ok())),
web::resource("/") ))
.route(web::to(|_: web::Json<String>| HttpResponse::Ok())),
),
)
}); });
let request = srv let request = srv
@ -90,12 +85,10 @@ fn test_json() {
.send_json(&"TEST".to_string()); .send_json(&"TEST".to_string());
let response = request.await.unwrap(); let response = request.await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }
#[test] #[actix_rt::test]
fn test_form() { async fn test_form() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to( HttpService::new(App::new().service(web::resource("/").route(web::to(
|_: web::Form<HashMap<String, String>>| HttpResponse::Ok(), |_: web::Form<HashMap<String, String>>| HttpResponse::Ok(),
@ -108,21 +101,17 @@ fn test_form() {
let request = srv.get("/").header("x-test", "111").send_form(&data); let request = srv.get("/").header("x-test", "111").send_form(&data);
let response = request.await.unwrap(); let response = request.await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }
#[test] #[actix_rt::test]
fn test_timeout() { async fn test_timeout() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to( HttpService::new(App::new().service(web::resource("/").route(web::to(|| {
|| {
async { async {
tokio_timer::delay_for(Duration::from_millis(200)).await; actix_rt::time::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()
@ -142,21 +131,17 @@ fn test_timeout() {
Err(SendRequestError::Timeout) => (), Err(SendRequestError::Timeout) => (),
_ => panic!(), _ => panic!(),
} }
})
} }
#[test] #[actix_rt::test]
fn test_timeout_override() { async fn test_timeout_override() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to( HttpService::new(App::new().service(web::resource("/").route(web::to(|| {
|| {
async { async {
tokio_timer::delay_for(Duration::from_millis(200)).await; actix_rt::time::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()
@ -170,12 +155,10 @@ fn test_timeout_override() {
Err(SendRequestError::Timeout) => (), Err(SendRequestError::Timeout) => (),
_ => panic!(), _ => panic!(),
} }
})
} }
#[test] #[actix_rt::test]
fn test_connection_reuse() { async fn test_connection_reuse() {
block_on(async {
let num = Arc::new(AtomicUsize::new(0)); let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone(); let num2 = num.clone();
@ -185,9 +168,9 @@ fn test_connection_reuse() {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })
.and_then(HttpService::new(App::new().service( .and_then(HttpService::new(
web::resource("/").route(web::to(|| HttpResponse::Ok())), App::new().service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
))) ))
}); });
let client = awc::Client::default(); let client = awc::Client::default();
@ -204,12 +187,10 @@ fn test_connection_reuse() {
// one connection // one connection
assert_eq!(num.load(Ordering::Relaxed), 1); assert_eq!(num.load(Ordering::Relaxed), 1);
})
} }
#[test] #[actix_rt::test]
fn test_connection_force_close() { async fn test_connection_force_close() {
block_on(async {
let num = Arc::new(AtomicUsize::new(0)); let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone(); let num2 = num.clone();
@ -219,9 +200,9 @@ fn test_connection_force_close() {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })
.and_then(HttpService::new(App::new().service( .and_then(HttpService::new(
web::resource("/").route(web::to(|| HttpResponse::Ok())), App::new().service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
))) ))
}); });
let client = awc::Client::default(); let client = awc::Client::default();
@ -238,12 +219,10 @@ fn test_connection_force_close() {
// two connection // two connection
assert_eq!(num.load(Ordering::Relaxed), 2); assert_eq!(num.load(Ordering::Relaxed), 2);
})
} }
#[test] #[actix_rt::test]
fn test_connection_server_close() { async fn test_connection_server_close() {
block_on(async {
let num = Arc::new(AtomicUsize::new(0)); let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone(); let num2 = num.clone();
@ -275,12 +254,10 @@ fn test_connection_server_close() {
// two connection // two connection
assert_eq!(num.load(Ordering::Relaxed), 2); assert_eq!(num.load(Ordering::Relaxed), 2);
})
} }
#[test] #[actix_rt::test]
fn test_connection_wait_queue() { async fn test_connection_wait_queue() {
block_on(async {
let num = Arc::new(AtomicUsize::new(0)); let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone(); let num2 = num.clone();
@ -318,12 +295,10 @@ fn test_connection_wait_queue() {
// two connection // two connection
assert_eq!(num.load(Ordering::Relaxed), 1); assert_eq!(num.load(Ordering::Relaxed), 1);
})
} }
#[test] #[actix_rt::test]
fn test_connection_wait_queue_force_close() { async fn test_connection_wait_queue_force_close() {
block_on(async {
let num = Arc::new(AtomicUsize::new(0)); let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone(); let num2 = num.clone();
@ -364,12 +339,10 @@ fn test_connection_wait_queue_force_close() {
// two connection // two connection
assert_eq!(num.load(Ordering::Relaxed), 2); assert_eq!(num.load(Ordering::Relaxed), 2);
})
} }
#[test] #[actix_rt::test]
fn test_with_query_parameter() { async fn test_with_query_parameter() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").to( HttpService::new(App::new().service(web::resource("/").to(
|req: HttpRequest| { |req: HttpRequest| {
@ -388,12 +361,10 @@ fn test_with_query_parameter() {
.await .await
.unwrap(); .unwrap();
assert!(res.status().is_success()); assert!(res.status().is_success());
})
} }
#[test] #[actix_rt::test]
fn test_no_decompress() { async fn test_no_decompress() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().wrap(Compress::default()).service( HttpService::new(App::new().wrap(Compress::default()).service(
web::resource("/").route(web::to(|| { web::resource("/").route(web::to(|| {
@ -434,15 +405,12 @@ fn test_no_decompress() {
let mut dec = Vec::new(); let mut dec = Vec::new();
e.read_to_end(&mut dec).unwrap(); e.read_to_end(&mut dec).unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref())); assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_client_gzip_encoding() { async fn test_client_gzip_encoding() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to( HttpService::new(App::new().service(web::resource("/").route(web::to(|| {
|| {
let mut e = GzEncoder::new(Vec::new(), Compression::default()); let mut e = GzEncoder::new(Vec::new(), Compression::default());
e.write_all(STR.as_ref()).unwrap(); e.write_all(STR.as_ref()).unwrap();
let data = e.finish().unwrap(); let data = e.finish().unwrap();
@ -450,8 +418,7 @@ fn test_client_gzip_encoding() {
HttpResponse::Ok() HttpResponse::Ok()
.header("content-encoding", "gzip") .header("content-encoding", "gzip")
.body(data) .body(data)
}, }))))
))))
}); });
// client request // client request
@ -461,15 +428,12 @@ fn test_client_gzip_encoding() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_client_gzip_encoding_large() { async fn test_client_gzip_encoding_large() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to( HttpService::new(App::new().service(web::resource("/").route(web::to(|| {
|| {
let mut e = GzEncoder::new(Vec::new(), Compression::default()); let mut e = GzEncoder::new(Vec::new(), Compression::default());
e.write_all(STR.repeat(10).as_ref()).unwrap(); e.write_all(STR.repeat(10).as_ref()).unwrap();
let data = e.finish().unwrap(); let data = e.finish().unwrap();
@ -477,8 +441,7 @@ fn test_client_gzip_encoding_large() {
HttpResponse::Ok() HttpResponse::Ok()
.header("content-encoding", "gzip") .header("content-encoding", "gzip")
.body(data) .body(data)
}, }))))
))))
}); });
// client request // client request
@ -488,12 +451,10 @@ fn test_client_gzip_encoding_large() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from(STR.repeat(10))); assert_eq!(bytes, Bytes::from(STR.repeat(10)));
})
} }
#[test] #[actix_rt::test]
fn test_client_gzip_encoding_large_random() { async fn test_client_gzip_encoding_large_random() {
block_on(async {
let data = rand::thread_rng() let data = rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric) .sample_iter(&rand::distributions::Alphanumeric)
.take(100_000) .take(100_000)
@ -519,12 +480,10 @@ fn test_client_gzip_encoding_large_random() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from(data)); assert_eq!(bytes, Bytes::from(data));
})
} }
#[test] #[actix_rt::test]
fn test_client_brotli_encoding() { async fn test_client_brotli_encoding() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to( HttpService::new(App::new().service(web::resource("/").route(web::to(
|data: Bytes| { |data: Bytes| {
@ -545,11 +504,10 @@ fn test_client_brotli_encoding() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
// #[test] // #[actix_rt::test]
// fn test_client_brotli_encoding_large_random() { // async fn test_client_brotli_encoding_large_random() {
// let data = rand::thread_rng() // let data = rand::thread_rng()
// .sample_iter(&rand::distributions::Alphanumeric) // .sample_iter(&rand::distributions::Alphanumeric)
// .take(70_000) // .take(70_000)
@ -583,8 +541,8 @@ fn test_client_brotli_encoding() {
// } // }
// #[cfg(feature = "brotli")] // #[cfg(feature = "brotli")]
// #[test] // #[actix_rt::test]
// fn test_client_deflate_encoding() { // async fn test_client_deflate_encoding() {
// let srv = test::TestServer::start(|app| { // let srv = test::TestServer::start(|app| {
// app.handler(|req: &HttpRequest| { // app.handler(|req: &HttpRequest| {
// req.body() // req.body()
@ -611,8 +569,8 @@ fn test_client_brotli_encoding() {
// assert_eq!(bytes, Bytes::from_static(STR.as_ref())); // assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
// } // }
// #[test] // #[actix_rt::test]
// fn test_client_deflate_encoding_large_random() { // async fn test_client_deflate_encoding_large_random() {
// let data = rand::thread_rng() // let data = rand::thread_rng()
// .sample_iter(&rand::distributions::Alphanumeric) // .sample_iter(&rand::distributions::Alphanumeric)
// .take(70_000) // .take(70_000)
@ -644,8 +602,8 @@ fn test_client_brotli_encoding() {
// assert_eq!(bytes, Bytes::from(data)); // assert_eq!(bytes, Bytes::from(data));
// } // }
// #[test] // #[actix_rt::test]
// fn test_client_streaming_explicit() { // async fn test_client_streaming_explicit() {
// let srv = test::TestServer::start(|app| { // let srv = test::TestServer::start(|app| {
// app.handler(|req: &HttpRequest| { // app.handler(|req: &HttpRequest| {
// req.body() // req.body()
@ -671,8 +629,8 @@ fn test_client_brotli_encoding() {
// assert_eq!(bytes, Bytes::from_static(STR.as_ref())); // assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
// } // }
// #[test] // #[actix_rt::test]
// fn test_body_streaming_implicit() { // async fn test_body_streaming_implicit() {
// let srv = test::TestServer::start(|app| { // let srv = test::TestServer::start(|app| {
// app.handler(|_| { // app.handler(|_| {
// let body = once(Ok(Bytes::from_static(STR.as_ref()))); // let body = once(Ok(Bytes::from_static(STR.as_ref())));
@ -691,11 +649,10 @@ fn test_client_brotli_encoding() {
// assert_eq!(bytes, Bytes::from_static(STR.as_ref())); // assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
// } // }
#[test] #[actix_rt::test]
fn test_client_cookie_handling() { async fn test_client_cookie_handling() {
use std::io::{Error as IoError, ErrorKind}; use std::io::{Error as IoError, ErrorKind};
block_on(async {
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")
@ -737,19 +694,14 @@ fn test_client_cookie_handling() {
Err(()) Err(())
} }
}) })
.map_err(|_| { .map_err(|_| Error::from(IoError::from(ErrorKind::NotFound)));
Error::from(IoError::from(ErrorKind::NotFound))
});
if let Err(e) = res { if let Err(e) = res {
Err(e) Err(e)
} else { } else {
// Send some cookies back // Send some cookies back
Ok::<_, Error>( Ok::<_, Error>(
HttpResponse::Ok() HttpResponse::Ok().cookie(cookie1).cookie(cookie2).finish(),
.cookie(cookie1)
.cookie(cookie2)
.finish(),
) )
} }
} }
@ -764,10 +716,9 @@ fn test_client_cookie_handling() {
assert_eq!(c1, cookie1); assert_eq!(c1, cookie1);
let c2 = response.cookie("cookie2").expect("Missing cookie2"); let c2 = response.cookie("cookie2").expect("Missing cookie2");
assert_eq!(c2, cookie2); assert_eq!(c2, cookie2);
})
} }
// #[test] // #[actix_rt::test]
// fn client_read_until_eof() { // fn client_read_until_eof() {
// let addr = test::TestServer::unused_addr(); // let addr = test::TestServer::unused_addr();
@ -797,9 +748,8 @@ fn test_client_cookie_handling() {
// assert_eq!(bytes, Bytes::from_static(b"welcome!")); // assert_eq!(bytes, Bytes::from_static(b"welcome!"));
// } // }
#[test] #[actix_rt::test]
fn client_basic_auth() { async fn client_basic_auth() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().route( HttpService::new(App::new().route(
"/", "/",
@ -824,12 +774,10 @@ fn client_basic_auth() {
let request = srv.get("/").basic_auth("username", Some("password")); let request = srv.get("/").basic_auth("username", Some("password"));
let response = request.send().await.unwrap(); let response = request.send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }
#[test] #[actix_rt::test]
fn client_bearer_auth() { async fn client_bearer_auth() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().route( HttpService::new(App::new().route(
"/", "/",
@ -854,5 +802,4 @@ fn client_bearer_auth() {
let request = srv.get("/").bearer_auth("someS3cr3tAutht0k3n"); let request = srv.get("/").bearer_auth("someS3cr3tAutht0k3n");
let response = request.send().await.unwrap(); let response = request.send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
})
} }

View File

@ -7,7 +7,7 @@ use std::sync::Arc;
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::{block_on, TestServer}; use actix_http_test::TestServer;
use actix_server::ssl::OpensslAcceptor; use actix_server::ssl::OpensslAcceptor;
use actix_service::{pipeline_factory, ServiceFactory}; use actix_service::{pipeline_factory, ServiceFactory};
use actix_web::http::Version; use actix_web::http::Version;
@ -53,9 +53,8 @@ mod danger {
} }
} }
// #[test] // #[actix_rt::test]
fn _test_connection_reuse_h2() { async fn _test_connection_reuse_h2() {
block_on(async {
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
let num = Arc::new(AtomicUsize::new(0)); let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone(); let num2 = num.clone();
@ -73,9 +72,8 @@ fn _test_connection_reuse_h2() {
) )
.and_then( .and_then(
HttpService::build() HttpService::build()
.h2(App::new().service( .h2(App::new()
web::resource("/").route(web::to(|| HttpResponse::Ok())), .service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
))
.map_err(|_| ()), .map_err(|_| ()),
) )
}); });
@ -105,5 +103,4 @@ fn _test_connection_reuse_h2() {
// one connection // one connection
assert_eq!(num.load(Ordering::Relaxed), 1); assert_eq!(num.load(Ordering::Relaxed), 1);
})
} }

View File

@ -7,7 +7,7 @@ use std::sync::Arc;
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::{block_on, TestServer}; use actix_http_test::TestServer;
use actix_server::ssl::OpensslAcceptor; use actix_server::ssl::OpensslAcceptor;
use actix_service::{pipeline_factory, ServiceFactory}; use actix_service::{pipeline_factory, ServiceFactory};
use actix_web::http::Version; use actix_web::http::Version;
@ -35,9 +35,8 @@ fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
Ok(actix_server::ssl::OpensslAcceptor::new(builder.build())) Ok(actix_server::ssl::OpensslAcceptor::new(builder.build()))
} }
#[test] #[actix_rt::test]
fn test_connection_reuse_h2() { async fn test_connection_reuse_h2() {
block_on(async {
let openssl = ssl_acceptor().unwrap(); let openssl = ssl_acceptor().unwrap();
let num = Arc::new(AtomicUsize::new(0)); let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone(); let num2 = num.clone();
@ -55,9 +54,8 @@ fn test_connection_reuse_h2() {
) )
.and_then( .and_then(
HttpService::build() HttpService::build()
.h2(App::new().service( .h2(App::new()
web::resource("/").route(web::to(|| HttpResponse::Ok())), .service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
))
.map_err(|_| ()), .map_err(|_| ()),
) )
}); });
@ -86,5 +84,4 @@ fn test_connection_reuse_h2() {
// one connection // one connection
assert_eq!(num.load(Ordering::Relaxed), 1); assert_eq!(num.load(Ordering::Relaxed), 1);
})
} }

View File

@ -2,7 +2,7 @@ use std::io;
use actix_codec::Framed; use actix_codec::Framed;
use actix_http::{body::BodySize, h1, ws, Error, HttpService, Request, Response}; use actix_http::{body::BodySize, h1, ws, Error, HttpService, Request, Response};
use actix_http_test::{block_on, TestServer}; use actix_http_test::TestServer;
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures::future::ok; use futures::future::ok;
use futures::{SinkExt, StreamExt}; use futures::{SinkExt, StreamExt};
@ -28,9 +28,8 @@ async fn ws_service(req: ws::Frame) -> Result<ws::Message, io::Error> {
} }
} }
#[test] #[actix_rt::test]
fn test_simple() { async fn test_simple() {
block_on(async {
let mut srv = TestServer::start(|| { let mut srv = TestServer::start(|| {
HttpService::build() HttpService::build()
.upgrade(|(req, mut framed): (Request, Framed<_, _>)| { .upgrade(|(req, mut framed): (Request, Framed<_, _>)| {
@ -79,5 +78,4 @@ fn test_simple() {
let item = framed.next().await.unwrap().unwrap(); let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, ws::Frame::Close(Some(ws::CloseCode::Normal.into()))); assert_eq!(item, ws::Frame::Close(Some(ws::CloseCode::Normal.into())));
})
} }

View File

@ -2,12 +2,10 @@ use std::cell::RefCell;
use std::fmt; use std::fmt;
use std::future::Future; use std::future::Future;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::pin::Pin;
use std::rc::Rc; use std::rc::Rc;
use std::task::{Context, Poll};
use actix_http::body::{Body, MessageBody}; use actix_http::body::{Body, MessageBody};
use actix_service::boxed::{self, BoxedNewService}; use actix_service::boxed::{self, BoxServiceFactory};
use actix_service::{ use actix_service::{
apply, apply_fn_factory, IntoServiceFactory, ServiceFactory, Transform, apply, apply_fn_factory, IntoServiceFactory, ServiceFactory, Transform,
}; };
@ -25,7 +23,7 @@ use crate::service::{
ServiceResponse, ServiceResponse,
}; };
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
type FnDataFactory = type FnDataFactory =
Box<dyn Fn() -> LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>; Box<dyn Fn() -> LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>;
@ -485,18 +483,17 @@ where
mod tests { mod tests {
use actix_service::Service; use actix_service::Service;
use bytes::Bytes; use bytes::Bytes;
use futures::future::{ok, Future}; use futures::future::ok;
use super::*; use super::*;
use crate::http::{header, HeaderValue, Method, StatusCode}; use crate::http::{header, HeaderValue, Method, StatusCode};
use crate::middleware::DefaultHeaders; use crate::middleware::DefaultHeaders;
use crate::service::{ServiceRequest, ServiceResponse}; use crate::service::ServiceRequest;
use crate::test::{block_on, call_service, init_service, read_body, TestRequest}; use crate::test::{call_service, init_service, read_body, TestRequest};
use crate::{web, Error, HttpRequest, HttpResponse}; use crate::{web, HttpRequest, HttpResponse};
#[test] #[actix_rt::test]
fn test_default_resource() { async fn test_default_resource() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().service(web::resource("/test").to(|| HttpResponse::Ok())), App::new().service(web::resource("/test").to(|| HttpResponse::Ok())),
) )
@ -538,12 +535,10 @@ mod tests {
.to_request(); .to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED); assert_eq!(resp.status(), StatusCode::CREATED);
})
} }
#[test] #[actix_rt::test]
fn test_data_factory() { async fn test_data_factory() {
block_on(async {
let mut srv = let mut srv =
init_service(App::new().data_factory(|| ok::<_, ()>(10usize)).service( init_service(App::new().data_factory(|| ok::<_, ()>(10usize)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()), web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
@ -561,39 +556,16 @@ mod tests {
let req = TestRequest::default().to_request(); let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
})
} }
fn md<S, B>( #[actix_rt::test]
req: ServiceRequest, async fn test_wrap() {
srv: &mut S, let mut srv = init_service(
) -> impl Future<Output = Result<ServiceResponse<B>, Error>>
where
S: Service<
Request = ServiceRequest,
Response = ServiceResponse<B>,
Error = Error,
>,
{
let fut = srv.call(req);
async move {
let mut res = fut.await?;
res.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static("0001"));
Ok(res)
}
}
#[test]
fn test_wrap() {
block_on(async {
let mut srv =
init_service(
App::new() App::new()
.wrap(DefaultHeaders::new().header( .wrap(
header::CONTENT_TYPE, DefaultHeaders::new()
HeaderValue::from_static("0001"), .header(header::CONTENT_TYPE, HeaderValue::from_static("0001")),
)) )
.route("/test", web::get().to(|| HttpResponse::Ok())), .route("/test", web::get().to(|| HttpResponse::Ok())),
) )
.await; .await;
@ -604,20 +576,17 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(), resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001") HeaderValue::from_static("0001")
); );
})
} }
#[test] #[actix_rt::test]
fn test_router_wrap() { async fn test_router_wrap() {
block_on(async { let mut srv = init_service(
let mut srv =
init_service(
App::new() App::new()
.route("/test", web::get().to(|| HttpResponse::Ok())) .route("/test", web::get().to(|| HttpResponse::Ok()))
.wrap(DefaultHeaders::new().header( .wrap(
header::CONTENT_TYPE, DefaultHeaders::new()
HeaderValue::from_static("0001"), .header(header::CONTENT_TYPE, HeaderValue::from_static("0001")),
)), ),
) )
.await; .await;
let req = TestRequest::with_uri("/test").to_request(); let req = TestRequest::with_uri("/test").to_request();
@ -627,12 +596,10 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(), resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001") HeaderValue::from_static("0001")
); );
})
} }
#[test] #[actix_rt::test]
fn test_wrap_fn() { async fn test_wrap_fn() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new() App::new()
.wrap_fn(|req, srv| { .wrap_fn(|req, srv| {
@ -656,12 +623,10 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(), resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001") HeaderValue::from_static("0001")
); );
})
} }
#[test] #[actix_rt::test]
fn test_router_wrap_fn() { async fn test_router_wrap_fn() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new() App::new()
.route("/test", web::get().to(|| HttpResponse::Ok())) .route("/test", web::get().to(|| HttpResponse::Ok()))
@ -685,12 +650,10 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(), resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001") HeaderValue::from_static("0001")
); );
})
} }
#[test] #[actix_rt::test]
fn test_external_resource() { async fn test_external_resource() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new() App::new()
.external_resource("youtube", "https://youtube.com/watch/{video_id}") .external_resource("youtube", "https://youtube.com/watch/{video_id}")
@ -710,6 +673,5 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp).await; let body = read_body(resp).await;
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345")); assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
})
} }
} }

View File

@ -8,9 +8,9 @@ use std::task::{Context, Poll};
use actix_http::{Extensions, Request, Response}; use actix_http::{Extensions, Request, Response};
use actix_router::{Path, ResourceDef, ResourceInfo, Router, Url}; use actix_router::{Path, ResourceDef, ResourceInfo, Router, Url};
use actix_server_config::ServerConfig; use actix_server_config::ServerConfig;
use actix_service::boxed::{self, BoxedNewService, BoxedService}; use actix_service::boxed::{self, BoxService, BoxServiceFactory};
use actix_service::{service_fn, Service, ServiceFactory}; use actix_service::{service_fn, Service, ServiceFactory};
use futures::future::{ok, Either, FutureExt, LocalBoxFuture, Ready}; use futures::future::{ok, FutureExt, LocalBoxFuture};
use crate::config::{AppConfig, AppService}; use crate::config::{AppConfig, AppService};
use crate::data::DataFactory; use crate::data::DataFactory;
@ -21,9 +21,9 @@ use crate::rmap::ResourceMap;
use crate::service::{AppServiceFactory, ServiceRequest, ServiceResponse}; use crate::service::{AppServiceFactory, ServiceRequest, ServiceResponse};
type Guards = Vec<Box<dyn Guard>>; type Guards = Vec<Box<dyn Guard>>;
type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>; type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
type BoxedResponse = LocalBoxFuture<'static, Result<ServiceResponse, Error>>; type BoxResponse = LocalBoxFuture<'static, Result<ServiceResponse, Error>>;
type FnDataFactory = type FnDataFactory =
Box<dyn Fn() -> LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>; Box<dyn Fn() -> LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>;
@ -387,7 +387,7 @@ impl Service for AppRouting {
type Request = ServiceRequest; type Request = ServiceRequest;
type Response = ServiceResponse; type Response = ServiceResponse;
type Error = Error; type Error = Error;
type Future = BoxedResponse; type Future = BoxResponse;
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> {
if self.ready.is_none() { if self.ready.is_none() {
@ -447,13 +447,12 @@ impl ServiceFactory for AppEntry {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use actix_service::Service; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{ use std::sync::Arc;
atomic::{AtomicBool, Ordering},
Arc,
};
use crate::{test, web, App, HttpResponse}; use crate::test::{init_service, TestRequest};
use crate::{web, App, HttpResponse};
use actix_service::Service;
struct DropData(Arc<AtomicBool>); struct DropData(Arc<AtomicBool>);
@ -463,19 +462,20 @@ mod tests {
} }
} }
#[test] #[actix_rt::test]
fn drop_data() { async fn test_drop_data() {
let data = Arc::new(AtomicBool::new(false)); let data = Arc::new(AtomicBool::new(false));
test::block_on(async {
let mut app = test::init_service( {
let mut app = init_service(
App::new() App::new()
.data(DropData(data.clone())) .data(DropData(data.clone()))
.service(web::resource("/test").to(|| HttpResponse::Ok())), .service(web::resource("/test").to(|| HttpResponse::Ok())),
) )
.await; .await;
let req = test::TestRequest::with_uri("/test").to_request(); let req = TestRequest::with_uri("/test").to_request();
let _ = app.call(req).await.unwrap(); let _ = app.call(req).await.unwrap();
}); }
assert!(data.load(Ordering::Relaxed)); assert!(data.load(Ordering::Relaxed));
} }
} }

View File

@ -18,7 +18,7 @@ use crate::service::{
type Guards = Vec<Box<dyn Guard>>; type Guards = Vec<Box<dyn Guard>>;
type HttpNewService = type HttpNewService =
boxed::BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; boxed::BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
/// Application configuration /// Application configuration
pub struct AppService { pub struct AppService {
@ -246,28 +246,27 @@ mod tests {
use super::*; use super::*;
use crate::http::{Method, StatusCode}; use crate::http::{Method, StatusCode};
use crate::test::{block_on, call_service, init_service, read_body, TestRequest}; use crate::test::{call_service, init_service, read_body, TestRequest};
use crate::{web, App, HttpRequest, HttpResponse}; use crate::{web, App, HttpRequest, HttpResponse};
#[test] #[actix_rt::test]
fn test_data() { async fn test_data() {
block_on(async {
let cfg = |cfg: &mut ServiceConfig| { let cfg = |cfg: &mut ServiceConfig| {
cfg.data(10usize); cfg.data(10usize);
}; };
let mut srv = init_service(App::new().configure(cfg).service( let mut srv =
init_service(App::new().configure(cfg).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()), web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
)) ))
.await; .await;
let req = TestRequest::default().to_request(); let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
// #[test] // #[actix_rt::test]
// fn test_data_factory() { // async fn test_data_factory() {
// let cfg = |cfg: &mut ServiceConfig| { // let cfg = |cfg: &mut ServiceConfig| {
// cfg.data_factory(|| { // cfg.data_factory(|| {
// sleep(std::time::Duration::from_millis(50)).then(|_| { // sleep(std::time::Duration::from_millis(50)).then(|_| {
@ -282,7 +281,7 @@ mod tests {
// web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()), // web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
// )); // ));
// let req = TestRequest::default().to_request(); // let req = TestRequest::default().to_request();
// let resp = block_on(srv.call(req)).unwrap(); // let resp = srv.call(req).await.unwrap();
// assert_eq!(resp.status(), StatusCode::OK); // assert_eq!(resp.status(), StatusCode::OK);
// let cfg2 = |cfg: &mut ServiceConfig| { // let cfg2 = |cfg: &mut ServiceConfig| {
@ -294,13 +293,12 @@ mod tests {
// .configure(cfg2), // .configure(cfg2),
// ); // );
// let req = TestRequest::default().to_request(); // let req = TestRequest::default().to_request();
// let resp = block_on(srv.call(req)).unwrap(); // let resp = srv.call(req).await.unwrap();
// assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); // assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
// } // }
#[test] #[actix_rt::test]
fn test_external_resource() { async fn test_external_resource() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new() App::new()
.configure(|cfg| { .configure(|cfg| {
@ -325,16 +323,13 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp).await; let body = read_body(resp).await;
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345")); assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
})
} }
#[test] #[actix_rt::test]
fn test_service() { async fn test_service() {
block_on(async {
let mut srv = init_service(App::new().configure(|cfg| { let mut srv = init_service(App::new().configure(|cfg| {
cfg.service( cfg.service(
web::resource("/test") web::resource("/test").route(web::get().to(|| HttpResponse::Created())),
.route(web::get().to(|| HttpResponse::Created())),
) )
.route("/index.html", web::get().to(|| HttpResponse::Ok())); .route("/index.html", web::get().to(|| HttpResponse::Ok()));
})) }))
@ -351,6 +346,5 @@ mod tests {
.to_request(); .to_request();
let resp = call_service(&mut srv, req).await; let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
} }

View File

@ -139,13 +139,13 @@ mod tests {
use super::*; use super::*;
use crate::http::StatusCode; use crate::http::StatusCode;
use crate::test::{block_on, init_service, TestRequest}; use crate::test::{init_service, TestRequest};
use crate::{web, App, HttpResponse}; use crate::{web, App, HttpResponse};
#[test] #[actix_rt::test]
fn test_data_extractor() { async fn test_data_extractor() {
block_on(async { let mut srv =
let mut srv = init_service(App::new().data(10usize).service( init_service(App::new().data(10usize).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()), web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
)) ))
.await; .await;
@ -154,19 +154,18 @@ mod tests {
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
let mut srv = init_service(App::new().data(10u32).service( let mut srv =
init_service(App::new().data(10u32).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()), web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
)) ))
.await; .await;
let req = TestRequest::default().to_request(); let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
})
} }
#[test] #[actix_rt::test]
fn test_register_data_extractor() { async fn test_register_data_extractor() {
block_on(async {
let mut srv = let mut srv =
init_service(App::new().register_data(Data::new(10usize)).service( init_service(App::new().register_data(Data::new(10usize)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()), web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
@ -185,20 +184,17 @@ mod tests {
let req = TestRequest::default().to_request(); let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
})
} }
#[test] #[actix_rt::test]
fn test_route_data_extractor() { async fn test_route_data_extractor() {
block_on(async { let mut srv =
let mut srv = init_service(App::new().service( init_service(App::new().service(web::resource("/").data(10usize).route(
web::resource("/").data(10usize).route(web::get().to( web::get().to(|data: web::Data<usize>| {
|data: web::Data<usize>| {
let _ = data.clone(); let _ = data.clone();
HttpResponse::Ok() HttpResponse::Ok()
}, }),
)), )))
))
.await; .await;
let req = TestRequest::default().to_request(); let req = TestRequest::default().to_request();
@ -217,12 +213,10 @@ mod tests {
let req = TestRequest::default().to_request(); let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
})
} }
#[test] #[actix_rt::test]
fn test_override_data() { async fn test_override_data() {
block_on(async {
let mut srv = init_service(App::new().data(1usize).service( let mut srv = init_service(App::new().data(1usize).service(
web::resource("/").data(10usize).route(web::get().to( web::resource("/").data(10usize).route(web::get().to(
|data: web::Data<usize>| { |data: web::Data<usize>| {
@ -237,6 +231,5 @@ mod tests {
let req = TestRequest::default().to_request(); let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
} }

View File

@ -270,7 +270,7 @@ mod tests {
use serde_derive::Deserialize; use serde_derive::Deserialize;
use super::*; use super::*;
use crate::test::{block_on, TestRequest}; use crate::test::TestRequest;
use crate::types::{Form, FormConfig}; use crate::types::{Form, FormConfig};
#[derive(Deserialize, Debug, PartialEq)] #[derive(Deserialize, Debug, PartialEq)]
@ -278,8 +278,8 @@ mod tests {
hello: String, hello: String,
} }
#[test] #[actix_rt::test]
fn test_option() { async fn test_option() {
let (req, mut pl) = TestRequest::with_header( let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
"application/x-www-form-urlencoded", "application/x-www-form-urlencoded",
@ -287,7 +287,9 @@ mod tests {
.data(FormConfig::default().limit(4096)) .data(FormConfig::default().limit(4096))
.to_http_parts(); .to_http_parts();
let r = block_on(Option::<Form<Info>>::from_request(&req, &mut pl)).unwrap(); let r = Option::<Form<Info>>::from_request(&req, &mut pl)
.await
.unwrap();
assert_eq!(r, None); assert_eq!(r, None);
let (req, mut pl) = TestRequest::with_header( let (req, mut pl) = TestRequest::with_header(
@ -298,7 +300,9 @@ mod tests {
.set_payload(Bytes::from_static(b"hello=world")) .set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts(); .to_http_parts();
let r = block_on(Option::<Form<Info>>::from_request(&req, &mut pl)).unwrap(); let r = Option::<Form<Info>>::from_request(&req, &mut pl)
.await
.unwrap();
assert_eq!( assert_eq!(
r, r,
Some(Form(Info { Some(Form(Info {
@ -314,12 +318,14 @@ mod tests {
.set_payload(Bytes::from_static(b"bye=world")) .set_payload(Bytes::from_static(b"bye=world"))
.to_http_parts(); .to_http_parts();
let r = block_on(Option::<Form<Info>>::from_request(&req, &mut pl)).unwrap(); let r = Option::<Form<Info>>::from_request(&req, &mut pl)
.await
.unwrap();
assert_eq!(r, None); assert_eq!(r, None);
} }
#[test] #[actix_rt::test]
fn test_result() { async fn test_result() {
let (req, mut pl) = TestRequest::with_header( let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
"application/x-www-form-urlencoded", "application/x-www-form-urlencoded",
@ -328,7 +334,8 @@ mod tests {
.set_payload(Bytes::from_static(b"hello=world")) .set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts(); .to_http_parts();
let r = block_on(Result::<Form<Info>, Error>::from_request(&req, &mut pl)) let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl)
.await
.unwrap() .unwrap()
.unwrap(); .unwrap();
assert_eq!( assert_eq!(
@ -346,8 +353,9 @@ mod tests {
.set_payload(Bytes::from_static(b"bye=world")) .set_payload(Bytes::from_static(b"bye=world"))
.to_http_parts(); .to_http_parts();
let r = let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl)
block_on(Result::<Form<Info>, Error>::from_request(&req, &mut pl)).unwrap(); .await
.unwrap();
assert!(r.is_err()); assert!(r.is_err());
} }
} }

View File

@ -1,4 +1,4 @@
#![allow(clippy::borrow_interior_mutable_const, unused_imports, dead_code)] #![allow(clippy::borrow_interior_mutable_const)]
//! Actix web is a small, pragmatic, and extremely fast web framework //! Actix web is a small, pragmatic, and extremely fast web framework
//! for Rust. //! for Rust.
//! //!
@ -143,9 +143,9 @@ pub mod dev {
HttpServiceFactory, ServiceRequest, ServiceResponse, WebService, HttpServiceFactory, ServiceRequest, ServiceResponse, WebService,
}; };
//pub use crate::types::form::UrlEncoded; pub use crate::types::form::UrlEncoded;
//pub use crate::types::json::JsonBody; pub use crate::types::json::JsonBody;
//pub use crate::types::readlines::Readlines; pub use crate::types::readlines::Readlines;
pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody, SizedStream}; pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody, SizedStream};
pub use actix_http::encoding::Decoder as Decompress; pub use actix_http::encoding::Decoder as Decompress;
@ -174,8 +174,8 @@ pub mod client {
//! use actix_rt::System; //! use actix_rt::System;
//! use actix_web::client::Client; //! use actix_web::client::Client;
//! //!
//! fn main() { //! #[actix_rt::main]
//! System::new("test").block_on(async { //! async fn main() {
//! let mut client = Client::default(); //! let mut client = Client::default();
//! //!
//! // Create request builder and send request //! // Create request builder and send request
@ -184,7 +184,6 @@ pub mod client {
//! .send().await; // <- Send http request //! .send().await; // <- Send http request
//! //!
//! println!("Response: {:?}", response); //! println!("Response: {:?}", response);
//! });
//! } //! }
//! ``` //! ```
pub use awc::error::{ pub use awc::error::{

View File

@ -2,7 +2,7 @@
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_service::{Service, Transform}; use actix_service::{Service, Transform};
use futures::future::{ok, Either, FutureExt, LocalBoxFuture, Ready}; use futures::future::{ok, Either, FutureExt, LocalBoxFuture};
/// `Middleware` for conditionally enables another middleware. /// `Middleware` for conditionally enables another middleware.
/// The controled middleware must not change the `Service` interfaces. /// The controled middleware must not change the `Service` interfaces.
@ -102,7 +102,7 @@ mod tests {
use crate::error::Result; use crate::error::Result;
use crate::http::{header::CONTENT_TYPE, HeaderValue, StatusCode}; use crate::http::{header::CONTENT_TYPE, HeaderValue, StatusCode};
use crate::middleware::errhandlers::*; use crate::middleware::errhandlers::*;
use crate::test::{self, block_on, TestRequest}; use crate::test::{self, TestRequest};
use crate::HttpResponse; use crate::HttpResponse;
fn render_500<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { fn render_500<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
@ -112,36 +112,32 @@ mod tests {
Ok(ErrorHandlerResponse::Response(res)) Ok(ErrorHandlerResponse::Response(res))
} }
#[test] #[actix_rt::test]
fn test_handler_enabled() { async fn test_handler_enabled() {
block_on(async {
let srv = |req: ServiceRequest| { let srv = |req: ServiceRequest| {
ok(req.into_response(HttpResponse::InternalServerError().finish())) ok(req.into_response(HttpResponse::InternalServerError().finish()))
}; };
let mw = ErrorHandlers::new() let mw =
.handler(StatusCode::INTERNAL_SERVER_ERROR, render_500); ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, render_500);
let mut mw = Condition::new(true, mw) let mut mw = Condition::new(true, mw)
.new_transform(srv.into_service()) .new_transform(srv.into_service())
.await .await
.unwrap(); .unwrap();
let resp = let resp =
test::call_service(&mut mw, TestRequest::default().to_srv_request()) test::call_service(&mut mw, TestRequest::default().to_srv_request()).await;
.await;
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
})
} }
#[test] #[actix_rt::test]
fn test_handler_disabled() { async fn test_handler_disabled() {
block_on(async {
let srv = |req: ServiceRequest| { let srv = |req: ServiceRequest| {
ok(req.into_response(HttpResponse::InternalServerError().finish())) ok(req.into_response(HttpResponse::InternalServerError().finish()))
}; };
let mw = ErrorHandlers::new() let mw =
.handler(StatusCode::INTERNAL_SERVER_ERROR, render_500); ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, render_500);
let mut mw = Condition::new(false, mw) let mut mw = Condition::new(false, mw)
.new_transform(srv.into_service()) .new_transform(srv.into_service())
@ -149,9 +145,7 @@ mod tests {
.unwrap(); .unwrap();
let resp = let resp =
test::call_service(&mut mw, TestRequest::default().to_srv_request()) test::call_service(&mut mw, TestRequest::default().to_srv_request()).await;
.await;
assert_eq!(resp.headers().get(CONTENT_TYPE), None); assert_eq!(resp.headers().get(CONTENT_TYPE), None);
})
} }
} }

View File

@ -1,6 +1,4 @@
//! Middleware for setting default response headers //! Middleware for setting default response headers
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc; use std::rc::Rc;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
@ -161,12 +159,11 @@ mod tests {
use super::*; use super::*;
use crate::dev::ServiceRequest; use crate::dev::ServiceRequest;
use crate::http::header::CONTENT_TYPE; use crate::http::header::CONTENT_TYPE;
use crate::test::{block_on, ok_service, TestRequest}; use crate::test::{ok_service, TestRequest};
use crate::HttpResponse; use crate::HttpResponse;
#[test] #[actix_rt::test]
fn test_default_headers() { async fn test_default_headers() {
block_on(async {
let mut mw = DefaultHeaders::new() let mut mw = DefaultHeaders::new()
.header(CONTENT_TYPE, "0001") .header(CONTENT_TYPE, "0001")
.new_transform(ok_service()) .new_transform(ok_service())
@ -179,9 +176,8 @@ mod tests {
let req = TestRequest::default().to_srv_request(); let req = TestRequest::default().to_srv_request();
let srv = |req: ServiceRequest| { let srv = |req: ServiceRequest| {
ok(req.into_response( ok(req
HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish(), .into_response(HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish()))
))
}; };
let mut mw = DefaultHeaders::new() let mut mw = DefaultHeaders::new()
.header(CONTENT_TYPE, "0001") .header(CONTENT_TYPE, "0001")
@ -190,12 +186,10 @@ mod tests {
.unwrap(); .unwrap();
let resp = mw.call(req).await.unwrap(); let resp = mw.call(req).await.unwrap();
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0002"); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0002");
})
} }
#[test] #[actix_rt::test]
fn test_content_type() { async fn test_content_type() {
block_on(async {
let srv = let srv =
|req: ServiceRequest| ok(req.into_response(HttpResponse::Ok().finish())); |req: ServiceRequest| ok(req.into_response(HttpResponse::Ok().finish()));
let mut mw = DefaultHeaders::new() let mut mw = DefaultHeaders::new()
@ -210,6 +204,5 @@ mod tests {
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
"application/octet-stream" "application/octet-stream"
); );
})
} }
} }

View File

@ -3,7 +3,7 @@ use std::rc::Rc;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_service::{Service, Transform}; use actix_service::{Service, Transform};
use futures::future::{err, ok, Either, Future, FutureExt, LocalBoxFuture, Ready}; use futures::future::{ok, FutureExt, LocalBoxFuture, Ready};
use hashbrown::HashMap; use hashbrown::HashMap;
use crate::dev::{ServiceRequest, ServiceResponse}; use crate::dev::{ServiceRequest, ServiceResponse};
@ -151,7 +151,7 @@ mod tests {
use super::*; use super::*;
use crate::http::{header::CONTENT_TYPE, HeaderValue, StatusCode}; use crate::http::{header::CONTENT_TYPE, HeaderValue, StatusCode};
use crate::test::{self, block_on, TestRequest}; use crate::test::{self, TestRequest};
use crate::HttpResponse; use crate::HttpResponse;
fn render_500<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { fn render_500<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
@ -161,9 +161,8 @@ mod tests {
Ok(ErrorHandlerResponse::Response(res)) Ok(ErrorHandlerResponse::Response(res))
} }
#[test] #[actix_rt::test]
fn test_handler() { async fn test_handler() {
block_on(async {
let srv = |req: ServiceRequest| { let srv = |req: ServiceRequest| {
ok(req.into_response(HttpResponse::InternalServerError().finish())) ok(req.into_response(HttpResponse::InternalServerError().finish()))
}; };
@ -175,10 +174,8 @@ mod tests {
.unwrap(); .unwrap();
let resp = let resp =
test::call_service(&mut mw, TestRequest::default().to_srv_request()) test::call_service(&mut mw, TestRequest::default().to_srv_request()).await;
.await;
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
})
} }
fn render_500_async<B: 'static>( fn render_500_async<B: 'static>(
@ -190,9 +187,8 @@ mod tests {
Ok(ErrorHandlerResponse::Future(ok(res).boxed_local())) Ok(ErrorHandlerResponse::Future(ok(res).boxed_local()))
} }
#[test] #[actix_rt::test]
fn test_handler_async() { async fn test_handler_async() {
block_on(async {
let srv = |req: ServiceRequest| { let srv = |req: ServiceRequest| {
ok(req.into_response(HttpResponse::InternalServerError().finish())) ok(req.into_response(HttpResponse::InternalServerError().finish()))
}; };
@ -204,9 +200,7 @@ mod tests {
.unwrap(); .unwrap();
let resp = let resp =
test::call_service(&mut mw, TestRequest::default().to_srv_request()) test::call_service(&mut mw, TestRequest::default().to_srv_request()).await;
.await;
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
})
} }
} }

View File

@ -479,10 +479,10 @@ mod tests {
use super::*; use super::*;
use crate::http::{header, StatusCode}; use crate::http::{header, StatusCode};
use crate::test::{block_on, TestRequest}; use crate::test::TestRequest;
#[test] #[actix_rt::test]
fn test_logger() { async fn test_logger() {
let srv = |req: ServiceRequest| { let srv = |req: ServiceRequest| {
ok(req.into_response( ok(req.into_response(
HttpResponse::build(StatusCode::OK) HttpResponse::build(StatusCode::OK)
@ -492,18 +492,18 @@ mod tests {
}; };
let logger = Logger::new("%% %{User-Agent}i %{X-Test}o %{HOME}e %D test"); let logger = Logger::new("%% %{User-Agent}i %{X-Test}o %{HOME}e %D test");
let mut srv = block_on(logger.new_transform(srv.into_service())).unwrap(); let mut srv = logger.new_transform(srv.into_service()).await.unwrap();
let req = TestRequest::with_header( let req = TestRequest::with_header(
header::USER_AGENT, header::USER_AGENT,
header::HeaderValue::from_static("ACTIX-WEB"), header::HeaderValue::from_static("ACTIX-WEB"),
) )
.to_srv_request(); .to_srv_request();
let _res = block_on(srv.call(req)); let _res = srv.call(req).await;
} }
#[test] #[actix_rt::test]
fn test_url_path() { async fn test_url_path() {
let mut format = Format::new("%T %U"); let mut format = Format::new("%T %U");
let req = TestRequest::with_header( let req = TestRequest::with_header(
header::USER_AGENT, header::USER_AGENT,
@ -533,8 +533,8 @@ mod tests {
assert!(s.contains("/test/route/yeah")); assert!(s.contains("/test/route/yeah"));
} }
#[test] #[actix_rt::test]
fn test_default_format() { async fn test_default_format() {
let mut format = Format::default(); let mut format = Format::default();
let req = TestRequest::with_header( let req = TestRequest::with_header(
@ -566,8 +566,8 @@ mod tests {
assert!(s.contains("ACTIX-WEB")); assert!(s.contains("ACTIX-WEB"));
} }
#[test] #[actix_rt::test]
fn test_request_time_format() { async fn test_request_time_format() {
let mut format = Format::new("%t"); let mut format = Format::new("%t");
let req = TestRequest::default().to_srv_request(); let req = TestRequest::default().to_srv_request();

View File

@ -105,12 +105,11 @@ mod tests {
use super::*; use super::*;
use crate::dev::ServiceRequest; use crate::dev::ServiceRequest;
use crate::test::{block_on, call_service, init_service, TestRequest}; use crate::test::{call_service, init_service, TestRequest};
use crate::{web, App, HttpResponse}; use crate::{web, App, HttpResponse};
#[test] #[actix_rt::test]
fn test_wrap() { async fn test_wrap() {
block_on(async {
let mut app = init_service( let mut app = init_service(
App::new() App::new()
.wrap(NormalizePath::default()) .wrap(NormalizePath::default())
@ -121,12 +120,10 @@ mod tests {
let req = TestRequest::with_uri("/v1//something////").to_request(); let req = TestRequest::with_uri("/v1//something////").to_request();
let res = call_service(&mut app, req).await; let res = call_service(&mut app, req).await;
assert!(res.status().is_success()); assert!(res.status().is_success());
})
} }
#[test] #[actix_rt::test]
fn test_in_place_normalization() { async fn test_in_place_normalization() {
block_on(async {
let srv = |req: ServiceRequest| { let srv = |req: ServiceRequest| {
assert_eq!("/v1/something/", req.path()); assert_eq!("/v1/something/", req.path());
ok(req.into_response(HttpResponse::Ok().finish())) ok(req.into_response(HttpResponse::Ok().finish()))
@ -140,12 +137,10 @@ mod tests {
let req = TestRequest::with_uri("/v1//something////").to_srv_request(); let req = TestRequest::with_uri("/v1//something////").to_srv_request();
let res = normalize.call(req).await.unwrap(); let res = normalize.call(req).await.unwrap();
assert!(res.status().is_success()); assert!(res.status().is_success());
})
} }
#[test] #[actix_rt::test]
fn should_normalize_nothing() { async fn should_normalize_nothing() {
block_on(async {
const URI: &str = "/v1/something/"; const URI: &str = "/v1/something/";
let srv = |req: ServiceRequest| { let srv = |req: ServiceRequest| {
@ -161,6 +156,5 @@ mod tests {
let req = TestRequest::with_uri(URI).to_srv_request(); let req = TestRequest::with_uri(URI).to_srv_request();
let res = normalize.call(req).await.unwrap(); let res = normalize.call(req).await.unwrap();
assert!(res.status().is_success()); assert!(res.status().is_success());
})
} }
} }

View File

@ -350,7 +350,7 @@ mod tests {
use super::*; use super::*;
use crate::dev::{ResourceDef, ResourceMap}; use crate::dev::{ResourceDef, ResourceMap};
use crate::http::{header, StatusCode}; use crate::http::{header, StatusCode};
use crate::test::{block_on, call_service, init_service, TestRequest}; use crate::test::{call_service, init_service, TestRequest};
use crate::{web, App, HttpResponse}; use crate::{web, App, HttpResponse};
#[test] #[test]
@ -466,9 +466,8 @@ mod tests {
); );
} }
#[test] #[actix_rt::test]
fn test_app_data() { async fn test_app_data() {
block_on(async {
let mut srv = init_service(App::new().data(10usize).service( let mut srv = init_service(App::new().data(10usize).service(
web::resource("/").to(|req: HttpRequest| { web::resource("/").to(|req: HttpRequest| {
if req.app_data::<usize>().is_some() { if req.app_data::<usize>().is_some() {
@ -498,12 +497,10 @@ mod tests {
let req = TestRequest::default().to_request(); let req = TestRequest::default().to_request();
let resp = call_service(&mut srv, req).await; let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST); assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
})
} }
#[test] #[actix_rt::test]
fn test_extensions_dropped() { async fn test_extensions_dropped() {
block_on(async {
struct Tracker { struct Tracker {
pub dropped: bool, pub dropped: bool,
} }
@ -535,6 +532,5 @@ mod tests {
} }
assert!(tracker.borrow().dropped); assert!(tracker.borrow().dropped);
})
} }
} }

View File

@ -6,12 +6,11 @@ use std::rc::Rc;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_http::{Error, Extensions, Response}; use actix_http::{Error, Extensions, Response};
use actix_service::boxed::{self, BoxedNewService, BoxedService}; use actix_service::boxed::{self, BoxService, BoxServiceFactory};
use actix_service::{ use actix_service::{
apply, apply_fn_factory, IntoServiceFactory, Service, ServiceFactory, Transform, apply, apply_fn_factory, IntoServiceFactory, Service, ServiceFactory, Transform,
}; };
use futures::future::{ok, Either, LocalBoxFuture, Ready}; use futures::future::{ok, Either, LocalBoxFuture, Ready};
use pin_project::pin_project;
use crate::data::Data; use crate::data::Data;
use crate::dev::{insert_slash, AppService, HttpServiceFactory, ResourceDef}; use crate::dev::{insert_slash, AppService, HttpServiceFactory, ResourceDef};
@ -22,8 +21,8 @@ use crate::responder::Responder;
use crate::route::{CreateRouteService, Route, RouteService}; use crate::route::{CreateRouteService, Route, RouteService};
use crate::service::{ServiceRequest, ServiceResponse}; use crate::service::{ServiceRequest, ServiceResponse};
type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>; type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
/// *Resource* is an entry in resources table which corresponds to requested URL. /// *Resource* is an entry in resources table which corresponds to requested URL.
/// ///
@ -585,40 +584,20 @@ impl ServiceFactory for ResourceEndpoint {
mod tests { mod tests {
use std::time::Duration; use std::time::Duration;
use actix_rt::time::delay_for;
use actix_service::Service; use actix_service::Service;
use futures::future::{ok, Future}; use futures::future::ok;
use tokio_timer::delay_for;
use crate::http::{header, HeaderValue, Method, StatusCode}; use crate::http::{header, HeaderValue, Method, StatusCode};
use crate::middleware::DefaultHeaders; use crate::middleware::DefaultHeaders;
use crate::service::{ServiceRequest, ServiceResponse}; use crate::service::ServiceRequest;
use crate::test::{block_on, call_service, init_service, TestRequest}; use crate::test::{call_service, init_service, TestRequest};
use crate::{guard, web, App, Error, HttpResponse}; use crate::{guard, web, App, Error, HttpResponse};
fn md<S, B>( #[actix_rt::test]
req: ServiceRequest, async fn test_middleware() {
srv: &mut S, let mut srv =
) -> impl Future<Output = Result<ServiceResponse<B>, Error>> init_service(
where
S: Service<
Request = ServiceRequest,
Response = ServiceResponse<B>,
Error = Error,
>,
{
let fut = srv.call(req);
async move {
let mut res = fut.await?;
res.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static("0001"));
Ok(res)
}
}
#[test]
fn test_middleware() {
block_on(async {
let mut srv = init_service(
App::new().service( App::new().service(
web::resource("/test") web::resource("/test")
.name("test") .name("test")
@ -637,12 +616,10 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(), resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001") HeaderValue::from_static("0001")
); );
})
} }
#[test] #[actix_rt::test]
fn test_middleware_fn() { async fn test_middleware_fn() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().service( App::new().service(
web::resource("/test") web::resource("/test")
@ -669,12 +646,10 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(), resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001") HeaderValue::from_static("0001")
); );
})
} }
#[test] #[actix_rt::test]
fn test_to() { async fn test_to() {
block_on(async {
let mut srv = let mut srv =
init_service(App::new().service(web::resource("/test").to(|| { init_service(App::new().service(web::resource("/test").to(|| {
async { async {
@ -686,17 +661,14 @@ mod tests {
let req = TestRequest::with_uri("/test").to_request(); let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&mut srv, req).await; let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_default_resource() { async fn test_default_resource() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new() App::new()
.service( .service(
web::resource("/test") web::resource("/test").route(web::get().to(|| HttpResponse::Ok())),
.route(web::get().to(|| HttpResponse::Ok())),
) )
.default_service(|r: ServiceRequest| { .default_service(|r: ServiceRequest| {
ok(r.into_response(HttpResponse::BadRequest())) ok(r.into_response(HttpResponse::BadRequest()))
@ -733,12 +705,10 @@ mod tests {
.to_request(); .to_request();
let resp = call_service(&mut srv, req).await; let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST); assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
})
} }
#[test] #[actix_rt::test]
fn test_resource_guards() { async fn test_resource_guards() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new() App::new()
.service( .service(
@ -776,12 +746,10 @@ mod tests {
.to_request(); .to_request();
let resp = call_service(&mut srv, req).await; let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::NO_CONTENT); assert_eq!(resp.status(), StatusCode::NO_CONTENT);
})
} }
#[test] #[actix_rt::test]
fn test_data() { async fn test_data() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new() App::new()
.data(1.0f64) .data(1.0f64)
@ -809,6 +777,5 @@ mod tests {
let req = TestRequest::get().uri("/test").to_request(); let req = TestRequest::get().uri("/test").to_request();
let resp = call_service(&mut srv, req).await; let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
} }

View File

@ -10,7 +10,7 @@ use actix_http::http::{
}; };
use actix_http::{Error, Response, ResponseBuilder}; use actix_http::{Error, Response, ResponseBuilder};
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures::future::{err, ok, Either as EitherFuture, LocalBoxFuture, Ready}; use futures::future::{err, ok, Either as EitherFuture, Ready};
use futures::ready; use futures::ready;
use pin_project::{pin_project, project}; use pin_project::{pin_project, project};
@ -457,17 +457,15 @@ pub(crate) mod tests {
use super::*; use super::*;
use crate::dev::{Body, ResponseBody}; use crate::dev::{Body, ResponseBody};
use crate::http::{header::CONTENT_TYPE, HeaderValue, StatusCode}; use crate::http::{header::CONTENT_TYPE, HeaderValue, StatusCode};
use crate::test::{block_on, init_service, TestRequest}; use crate::test::{init_service, TestRequest};
use crate::{error, web, App, HttpResponse}; use crate::{error, web, App, HttpResponse};
#[test] #[actix_rt::test]
fn test_option_responder() { async fn test_option_responder() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new() App::new()
.service( .service(
web::resource("/none") web::resource("/none").to(|| async { Option::<&'static str>::None }),
.to(|| async { Option::<&'static str>::None }),
) )
.service(web::resource("/some").to(|| async { Some("some") })), .service(web::resource("/some").to(|| async { Some("some") })),
) )
@ -487,7 +485,6 @@ pub(crate) mod tests {
} }
_ => panic!(), _ => panic!(),
} }
})
} }
pub(crate) trait BodyTest { pub(crate) trait BodyTest {
@ -516,9 +513,8 @@ pub(crate) mod tests {
} }
} }
#[test] #[actix_rt::test]
fn test_responder() { async fn test_responder() {
block_on(async {
let req = TestRequest::default().to_http_request(); let req = TestRequest::default().to_http_request();
let resp: HttpResponse = "test".respond_to(&req).await.unwrap(); let resp: HttpResponse = "test".respond_to(&req).await.unwrap();
@ -545,8 +541,7 @@ pub(crate) mod tests {
HeaderValue::from_static("text/plain; charset=utf-8") HeaderValue::from_static("text/plain; charset=utf-8")
); );
let resp: HttpResponse = let resp: HttpResponse = (&"test".to_string()).respond_to(&req).await.unwrap();
(&"test".to_string()).respond_to(&req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test"); assert_eq!(resp.body().bin_ref(), b"test");
assert_eq!( assert_eq!(
@ -581,12 +576,10 @@ pub(crate) mod tests {
.await .await
.unwrap(); .unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST); assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
})
} }
#[test] #[actix_rt::test]
fn test_result_responder() { async fn test_result_responder() {
block_on(async {
let req = TestRequest::default().to_http_request(); let req = TestRequest::default().to_http_request();
// Result<I, E> // Result<I, E>
@ -601,19 +594,15 @@ pub(crate) mod tests {
HeaderValue::from_static("text/plain; charset=utf-8") HeaderValue::from_static("text/plain; charset=utf-8")
); );
let res = Err::<String, _>(error::InternalError::new( let res =
"err", Err::<String, _>(error::InternalError::new("err", StatusCode::BAD_REQUEST))
StatusCode::BAD_REQUEST,
))
.respond_to(&req) .respond_to(&req)
.await; .await;
assert!(res.is_err()); assert!(res.is_err());
})
} }
#[test] #[actix_rt::test]
fn test_custom_responder() { async fn test_custom_responder() {
block_on(async {
let req = TestRequest::default().to_http_request(); let req = TestRequest::default().to_http_request();
let res = "test" let res = "test"
.to_string() .to_string()
@ -637,12 +626,10 @@ pub(crate) mod tests {
res.headers().get(CONTENT_TYPE).unwrap(), res.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("json") HeaderValue::from_static("json")
); );
})
} }
#[test] #[actix_rt::test]
fn test_tuple_responder_with_status_code() { async fn test_tuple_responder_with_status_code() {
block_on(async {
let req = TestRequest::default().to_http_request(); let req = TestRequest::default().to_http_request();
let res = ("test".to_string(), StatusCode::BAD_REQUEST) let res = ("test".to_string(), StatusCode::BAD_REQUEST)
.respond_to(&req) .respond_to(&req)
@ -663,6 +650,5 @@ pub(crate) mod tests {
res.headers().get(CONTENT_TYPE).unwrap(), res.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("json") HeaderValue::from_static("json")
); );
})
} }
} }

View File

@ -5,7 +5,7 @@ use std::task::{Context, Poll};
use actix_http::{http::Method, Error}; use actix_http::{http::Method, Error};
use actix_service::{Service, ServiceFactory}; use actix_service::{Service, ServiceFactory};
use futures::future::{ok, ready, Either, FutureExt, LocalBoxFuture, Ready}; use futures::future::{ready, FutureExt, LocalBoxFuture};
use crate::extract::FromRequest; use crate::extract::FromRequest;
use crate::guard::{self, Guard}; use crate::guard::{self, Guard};
@ -342,23 +342,21 @@ where
mod tests { mod tests {
use std::time::Duration; use std::time::Duration;
use actix_rt::time::delay_for;
use bytes::Bytes; use bytes::Bytes;
use futures::Future;
use serde_derive::Serialize; use serde_derive::Serialize;
use tokio_timer::delay_for;
use crate::http::{Method, StatusCode}; use crate::http::{Method, StatusCode};
use crate::test::{block_on, call_service, init_service, read_body, TestRequest}; use crate::test::{call_service, init_service, read_body, TestRequest};
use crate::{error, web, App, Error, HttpResponse}; use crate::{error, web, App, HttpResponse};
#[derive(Serialize, PartialEq, Debug)] #[derive(Serialize, PartialEq, Debug)]
struct MyObject { struct MyObject {
name: String, name: String,
} }
#[test] #[actix_rt::test]
fn test_route() { async fn test_route() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new() App::new()
.service( .service(
@ -429,6 +427,5 @@ mod tests {
let body = read_body(resp).await; let body = read_body(resp).await;
assert_eq!(body, Bytes::from_static(b"{\"name\":\"test\"}")); assert_eq!(body, Bytes::from_static(b"{\"name\":\"test\"}"));
})
} }
} }

View File

@ -6,7 +6,7 @@ use std::task::{Context, Poll};
use actix_http::{Extensions, Response}; use actix_http::{Extensions, Response};
use actix_router::{ResourceDef, ResourceInfo, Router}; use actix_router::{ResourceDef, ResourceInfo, Router};
use actix_service::boxed::{self, BoxedNewService, BoxedService}; use actix_service::boxed::{self, BoxService, BoxServiceFactory};
use actix_service::{ use actix_service::{
apply, apply_fn_factory, IntoServiceFactory, Service, ServiceFactory, Transform, apply, apply_fn_factory, IntoServiceFactory, Service, ServiceFactory, Transform,
}; };
@ -25,8 +25,8 @@ use crate::service::{
}; };
type Guards = Vec<Box<dyn Guard>>; type Guards = Vec<Box<dyn Guard>>;
type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>; type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
type BoxedResponse = LocalBoxFuture<'static, Result<ServiceResponse, Error>>; type BoxedResponse = LocalBoxFuture<'static, Result<ServiceResponse, Error>>;
/// Resources scope. /// Resources scope.
@ -666,18 +666,16 @@ mod tests {
use actix_service::Service; use actix_service::Service;
use bytes::Bytes; use bytes::Bytes;
use futures::future::ok; use futures::future::ok;
use futures::Future;
use crate::dev::{Body, ResponseBody}; use crate::dev::{Body, ResponseBody};
use crate::http::{header, HeaderValue, Method, StatusCode}; use crate::http::{header, HeaderValue, Method, StatusCode};
use crate::middleware::DefaultHeaders; use crate::middleware::DefaultHeaders;
use crate::service::{ServiceRequest, ServiceResponse}; use crate::service::ServiceRequest;
use crate::test::{block_on, call_service, init_service, read_body, TestRequest}; use crate::test::{call_service, init_service, read_body, TestRequest};
use crate::{guard, web, App, Error, HttpRequest, HttpResponse}; use crate::{guard, web, App, HttpRequest, HttpResponse};
#[test] #[actix_rt::test]
fn test_scope() { async fn test_scope() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().service( App::new().service(
web::scope("/app") web::scope("/app")
@ -689,12 +687,10 @@ mod tests {
let req = TestRequest::with_uri("/app/path1").to_request(); let req = TestRequest::with_uri("/app/path1").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_scope_root() { async fn test_scope_root() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().service( App::new().service(
web::scope("/app") web::scope("/app")
@ -711,12 +707,10 @@ mod tests {
let req = TestRequest::with_uri("/app/").to_request(); let req = TestRequest::with_uri("/app/").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED); assert_eq!(resp.status(), StatusCode::CREATED);
})
} }
#[test] #[actix_rt::test]
fn test_scope_root2() { async fn test_scope_root2() {
block_on(async {
let mut srv = init_service(App::new().service( let mut srv = init_service(App::new().service(
web::scope("/app/").service(web::resource("").to(|| HttpResponse::Ok())), web::scope("/app/").service(web::resource("").to(|| HttpResponse::Ok())),
)) ))
@ -729,18 +723,13 @@ mod tests {
let req = TestRequest::with_uri("/app/").to_request(); let req = TestRequest::with_uri("/app/").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_scope_root3() { async fn test_scope_root3() {
block_on(async { let mut srv = init_service(App::new().service(
let mut srv = init_service( web::scope("/app/").service(web::resource("/").to(|| HttpResponse::Ok())),
App::new().service( ))
web::scope("/app/")
.service(web::resource("/").to(|| HttpResponse::Ok())),
),
)
.await; .await;
let req = TestRequest::with_uri("/app").to_request(); let req = TestRequest::with_uri("/app").to_request();
@ -750,12 +739,10 @@ mod tests {
let req = TestRequest::with_uri("/app/").to_request(); let req = TestRequest::with_uri("/app/").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND); assert_eq!(resp.status(), StatusCode::NOT_FOUND);
})
} }
#[test] #[actix_rt::test]
fn test_scope_route() { async fn test_scope_route() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().service( App::new().service(
web::scope("app") web::scope("app")
@ -780,12 +767,10 @@ mod tests {
.to_request(); .to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND); assert_eq!(resp.status(), StatusCode::NOT_FOUND);
})
} }
#[test] #[actix_rt::test]
fn test_scope_route_without_leading_slash() { async fn test_scope_route_without_leading_slash() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().service( App::new().service(
web::scope("app").service( web::scope("app").service(
@ -812,12 +797,10 @@ mod tests {
.to_request(); .to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
})
} }
#[test] #[actix_rt::test]
fn test_scope_guard() { async fn test_scope_guard() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().service( App::new().service(
web::scope("/app") web::scope("/app")
@ -838,12 +821,10 @@ mod tests {
.to_request(); .to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_scope_variable_segment() { async fn test_scope_variable_segment() {
block_on(async {
let mut srv = let mut srv =
init_service(App::new().service(web::scope("/ab-{project}").service( init_service(App::new().service(web::scope("/ab-{project}").service(
web::resource("/path1").to(|r: HttpRequest| { web::resource("/path1").to(|r: HttpRequest| {
@ -870,46 +851,44 @@ mod tests {
let req = TestRequest::with_uri("/aa-project1/path1").to_request(); let req = TestRequest::with_uri("/aa-project1/path1").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND); assert_eq!(resp.status(), StatusCode::NOT_FOUND);
})
} }
#[test] #[actix_rt::test]
fn test_nested_scope() { async fn test_nested_scope() {
block_on(async { let mut srv = init_service(
let mut srv = App::new().service(
init_service(App::new().service( web::scope("/app")
web::scope("/app").service(web::scope("/t1").service( .service(web::scope("/t1").service(
web::resource("/path1").to(|| HttpResponse::Created()), web::resource("/path1").to(|| HttpResponse::Created()),
)), )),
)) ),
)
.await; .await;
let req = TestRequest::with_uri("/app/t1/path1").to_request(); let req = TestRequest::with_uri("/app/t1/path1").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED); assert_eq!(resp.status(), StatusCode::CREATED);
})
} }
#[test] #[actix_rt::test]
fn test_nested_scope_no_slash() { async fn test_nested_scope_no_slash() {
block_on(async { let mut srv = init_service(
let mut srv = App::new().service(
init_service(App::new().service( web::scope("/app")
web::scope("/app").service(web::scope("t1").service( .service(web::scope("t1").service(
web::resource("/path1").to(|| HttpResponse::Created()), web::resource("/path1").to(|| HttpResponse::Created()),
)), )),
)) ),
)
.await; .await;
let req = TestRequest::with_uri("/app/t1/path1").to_request(); let req = TestRequest::with_uri("/app/t1/path1").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED); assert_eq!(resp.status(), StatusCode::CREATED);
})
} }
#[test] #[actix_rt::test]
fn test_nested_scope_root() { async fn test_nested_scope_root() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().service( App::new().service(
web::scope("/app").service( web::scope("/app").service(
@ -928,12 +907,10 @@ mod tests {
let req = TestRequest::with_uri("/app/t1/").to_request(); let req = TestRequest::with_uri("/app/t1/").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED); assert_eq!(resp.status(), StatusCode::CREATED);
})
} }
#[test] #[actix_rt::test]
fn test_nested_scope_filter() { async fn test_nested_scope_filter() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().service( App::new().service(
web::scope("/app").service( web::scope("/app").service(
@ -956,20 +933,16 @@ mod tests {
.to_request(); .to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_nested_scope_with_variable_segment() { async fn test_nested_scope_with_variable_segment() {
block_on(async {
let mut srv = init_service(App::new().service(web::scope("/app").service( let mut srv = init_service(App::new().service(web::scope("/app").service(
web::scope("/{project_id}").service(web::resource("/path1").to( web::scope("/{project_id}").service(web::resource("/path1").to(
|r: HttpRequest| { |r: HttpRequest| {
async move { async move {
HttpResponse::Created().body(format!( HttpResponse::Created()
"project: {}", .body(format!("project: {}", &r.match_info()["project_id"]))
&r.match_info()["project_id"]
))
} }
}, },
)), )),
@ -987,12 +960,10 @@ mod tests {
} }
_ => panic!(), _ => panic!(),
} }
})
} }
#[test] #[actix_rt::test]
fn test_nested2_scope_with_variable_segment() { async fn test_nested2_scope_with_variable_segment() {
block_on(async {
let mut srv = init_service(App::new().service(web::scope("/app").service( let mut srv = init_service(App::new().service(web::scope("/app").service(
web::scope("/{project}").service(web::scope("/{id}").service( web::scope("/{project}").service(web::scope("/{id}").service(
web::resource("/path1").to(|r: HttpRequest| { web::resource("/path1").to(|r: HttpRequest| {
@ -1023,12 +994,10 @@ mod tests {
let req = TestRequest::with_uri("/app/test/1/path2").to_request(); let req = TestRequest::with_uri("/app/test/1/path2").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND); assert_eq!(resp.status(), StatusCode::NOT_FOUND);
})
} }
#[test] #[actix_rt::test]
fn test_default_resource() { async fn test_default_resource() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().service( App::new().service(
web::scope("/app") web::scope("/app")
@ -1047,12 +1016,10 @@ mod tests {
let req = TestRequest::with_uri("/path2").to_request(); let req = TestRequest::with_uri("/path2").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND); assert_eq!(resp.status(), StatusCode::NOT_FOUND);
})
} }
#[test] #[actix_rt::test]
fn test_default_resource_propagation() { async fn test_default_resource_propagation() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new() App::new()
.service(web::scope("/app1").default_service( .service(web::scope("/app1").default_service(
@ -1076,33 +1043,12 @@ mod tests {
let req = TestRequest::with_uri("/app2/non-exist").to_request(); let req = TestRequest::with_uri("/app2/non-exist").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
})
} }
fn md<S, B>( #[actix_rt::test]
req: ServiceRequest, async fn test_middleware() {
srv: &mut S, let mut srv =
) -> impl Future<Output = Result<ServiceResponse<B>, Error>> init_service(
where
S: Service<
Request = ServiceRequest,
Response = ServiceResponse<B>,
Error = Error,
>,
{
let fut = srv.call(req);
async move {
let mut res = fut.await?;
res.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static("0001"));
Ok(res)
}
}
#[test]
fn test_middleware() {
block_on(async {
let mut srv = init_service(
App::new().service( App::new().service(
web::scope("app") web::scope("app")
.wrap(DefaultHeaders::new().header( .wrap(DefaultHeaders::new().header(
@ -1124,12 +1070,10 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(), resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001") HeaderValue::from_static("0001")
); );
})
} }
#[test] #[actix_rt::test]
fn test_middleware_fn() { async fn test_middleware_fn() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().service( App::new().service(
web::scope("app") web::scope("app")
@ -1156,12 +1100,10 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(), resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001") HeaderValue::from_static("0001")
); );
})
} }
#[test] #[actix_rt::test]
fn test_override_data() { async fn test_override_data() {
block_on(async {
let mut srv = init_service(App::new().data(1usize).service( let mut srv = init_service(App::new().data(1usize).service(
web::scope("app").data(10usize).route( web::scope("app").data(10usize).route(
"/t", "/t",
@ -1177,12 +1119,10 @@ mod tests {
let req = TestRequest::with_uri("/app/t").to_request(); let req = TestRequest::with_uri("/app/t").to_request();
let resp = call_service(&mut srv, req).await; let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_override_register_data() { async fn test_override_register_data() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().register_data(web::Data::new(1usize)).service( App::new().register_data(web::Data::new(1usize)).service(
web::scope("app") web::scope("app")
@ -1202,12 +1142,10 @@ mod tests {
let req = TestRequest::with_uri("/app/t").to_request(); let req = TestRequest::with_uri("/app/t").to_request();
let resp = call_service(&mut srv, req).await; let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_scope_config() { async fn test_scope_config() {
block_on(async {
let mut srv = let mut srv =
init_service(App::new().service(web::scope("/app").configure(|s| { init_service(App::new().service(web::scope("/app").configure(|s| {
s.route("/path1", web::get().to(|| HttpResponse::Ok())); s.route("/path1", web::get().to(|| HttpResponse::Ok()));
@ -1217,12 +1155,10 @@ mod tests {
let req = TestRequest::with_uri("/app/path1").to_request(); let req = TestRequest::with_uri("/app/path1").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_scope_config_2() { async fn test_scope_config_2() {
block_on(async {
let mut srv = let mut srv =
init_service(App::new().service(web::scope("/app").configure(|s| { init_service(App::new().service(web::scope("/app").configure(|s| {
s.service(web::scope("/v1").configure(|s| { s.service(web::scope("/v1").configure(|s| {
@ -1234,12 +1170,10 @@ mod tests {
let req = TestRequest::with_uri("/app/v1/").to_request(); let req = TestRequest::with_uri("/app/v1/").to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
})
} }
#[test] #[actix_rt::test]
fn test_url_for_external() { async fn test_url_for_external() {
block_on(async {
let mut srv = let mut srv =
init_service(App::new().service(web::scope("/app").configure(|s| { init_service(App::new().service(web::scope("/app").configure(|s| {
s.service(web::scope("/v1").configure(|s| { s.service(web::scope("/v1").configure(|s| {
@ -1269,20 +1203,16 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp).await; let body = read_body(resp).await;
assert_eq!(body, &b"https://youtube.com/watch/xxxxxx"[..]); assert_eq!(body, &b"https://youtube.com/watch/xxxxxx"[..]);
})
} }
#[test] #[actix_rt::test]
fn test_url_for_nested() { async fn test_url_for_nested() {
block_on(async {
let mut srv = init_service(App::new().service(web::scope("/a").service( let mut srv = init_service(App::new().service(web::scope("/a").service(
web::scope("/b").service(web::resource("/c/{stuff}").name("c").route( web::scope("/b").service(web::resource("/c/{stuff}").name("c").route(
web::get().to(|req: HttpRequest| { web::get().to(|req: HttpRequest| {
async move { async move {
HttpResponse::Ok().body(format!( HttpResponse::Ok()
"{}", .body(format!("{}", req.url_for("c", &["12345"]).unwrap()))
req.url_for("c", &["12345"]).unwrap()
))
} }
}), }),
)), )),
@ -1297,6 +1227,5 @@ mod tests {
body, body,
Bytes::from_static(b"http://localhost:8080/a/b/c/12345") Bytes::from_static(b"http://localhost:8080/a/b/c/12345")
); );
})
} }
} }

View File

@ -10,7 +10,6 @@ use actix_http::{
}; };
use actix_router::{Path, Resource, ResourceDef, Url}; use actix_router::{Path, Resource, ResourceDef, Url};
use actix_service::{IntoServiceFactory, ServiceFactory}; use actix_service::{IntoServiceFactory, ServiceFactory};
use futures::future::{ok, Ready};
use crate::config::{AppConfig, AppService}; use crate::config::{AppConfig, AppService};
use crate::data::Data; use crate::data::Data;
@ -529,9 +528,10 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::test::{block_on, init_service, TestRequest}; use crate::test::{init_service, TestRequest};
use crate::{guard, http, web, App, HttpResponse}; use crate::{guard, http, web, App, HttpResponse};
use actix_service::Service; use actix_service::Service;
use futures::future::ok;
#[test] #[test]
fn test_service_request() { fn test_service_request() {
@ -554,14 +554,11 @@ mod tests {
assert!(ServiceRequest::from_request(r).is_err()); assert!(ServiceRequest::from_request(r).is_err());
} }
#[test] #[actix_rt::test]
fn test_service() { async fn test_service() {
block_on(async {
let mut srv = init_service( let mut srv = init_service(
App::new().service(web::service("/test").name("test").finish( App::new().service(web::service("/test").name("test").finish(
|req: ServiceRequest| { |req: ServiceRequest| ok(req.into_response(HttpResponse::Ok().finish())),
ok(req.into_response(HttpResponse::Ok().finish()))
},
)), )),
) )
.await; .await;
@ -569,20 +566,17 @@ mod tests {
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK); assert_eq!(resp.status(), http::StatusCode::OK);
let mut srv = init_service(App::new().service( let mut srv = init_service(
web::service("/test").guard(guard::Get()).finish( App::new().service(web::service("/test").guard(guard::Get()).finish(
|req: ServiceRequest| { |req: ServiceRequest| ok(req.into_response(HttpResponse::Ok().finish())),
ok(req.into_response(HttpResponse::Ok().finish())) )),
}, )
),
))
.await; .await;
let req = TestRequest::with_uri("/test") let req = TestRequest::with_uri("/test")
.method(http::Method::PUT) .method(http::Method::PUT)
.to_request(); .to_request();
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::NOT_FOUND); assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
})
} }
#[test] #[test]

View File

@ -9,14 +9,13 @@ use actix_router::{Path, ResourceDef, Url};
use actix_server_config::ServerConfig; use actix_server_config::ServerConfig;
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory}; use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures::future::{ok, Future, FutureExt}; use futures::future::ok;
use futures::stream::{Stream, StreamExt}; use futures::stream::{Stream, StreamExt};
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde::Serialize; use serde::Serialize;
use serde_json; use serde_json;
pub use actix_http::test::TestBuffer; pub use actix_http::test::TestBuffer;
pub use actix_testing::{block_fn, block_on, run_on};
use crate::config::{AppConfig, AppConfigInner}; use crate::config::{AppConfig, AppConfigInner};
use crate::data::Data; use crate::data::Data;
@ -51,8 +50,8 @@ pub fn default_service(
/// use actix_service::Service; /// use actix_service::Service;
/// use actix_web::{test, web, App, HttpResponse, http::StatusCode}; /// use actix_web::{test, web, App, HttpResponse, http::StatusCode};
/// ///
/// #[test] /// #[actix_rt::test]
/// fn test_init_service() { /// async fn test_init_service() {
/// let mut app = test::init_service( /// let mut app = test::init_service(
/// App::new() /// App::new()
/// .service(web::resource("/test").to(|| async { HttpResponse::Ok() })) /// .service(web::resource("/test").to(|| async { HttpResponse::Ok() }))
@ -62,7 +61,7 @@ pub fn default_service(
/// let req = test::TestRequest::with_uri("/test").to_request(); /// let req = test::TestRequest::with_uri("/test").to_request();
/// ///
/// // Execute application /// // Execute application
/// let resp = test::block_on(app.call(req)).unwrap(); /// let resp = app.call(req).await.unwrap();
/// assert_eq!(resp.status(), StatusCode::OK); /// assert_eq!(resp.status(), StatusCode::OK);
/// } /// }
/// ``` /// ```
@ -116,14 +115,13 @@ where
} }
/// Helper function that returns a response body of a TestRequest /// Helper function that returns a response body of a TestRequest
/// This function blocks the current thread until futures complete.
/// ///
/// ```rust /// ```rust
/// use actix_web::{test, web, App, HttpResponse, http::header}; /// use actix_web::{test, web, App, HttpResponse, http::header};
/// use bytes::Bytes; /// use bytes::Bytes;
/// ///
/// #[test] /// #[actix_rt::test]
/// fn test_index() { /// async fn test_index() {
/// let mut app = test::init_service( /// let mut app = test::init_service(
/// App::new().service( /// App::new().service(
/// web::resource("/index.html") /// web::resource("/index.html")
@ -149,7 +147,7 @@ where
let mut resp = app let mut resp = app
.call(req) .call(req)
.await .await
.unwrap_or_else(|_| panic!("read_response failed at block_on unwrap")); .unwrap_or_else(|_| panic!("read_response failed at application call"));
let mut body = resp.take_body(); let mut body = resp.take_body();
let mut bytes = BytesMut::new(); let mut bytes = BytesMut::new();
@ -160,14 +158,13 @@ where
} }
/// Helper function that returns a response body of a ServiceResponse. /// Helper function that returns a response body of a ServiceResponse.
/// This function blocks the current thread until futures complete.
/// ///
/// ```rust /// ```rust
/// use actix_web::{test, web, App, HttpResponse, http::header}; /// use actix_web::{test, web, App, HttpResponse, http::header};
/// use bytes::Bytes; /// use bytes::Bytes;
/// ///
/// #[test] /// #[actix_rt::test]
/// fn test_index() { /// async fn test_index() {
/// let mut app = test::init_service( /// let mut app = test::init_service(
/// App::new().service( /// App::new().service(
/// web::resource("/index.html") /// web::resource("/index.html")
@ -210,7 +207,6 @@ where
} }
/// Helper function that returns a deserialized response body of a TestRequest /// Helper function that returns a deserialized response body of a TestRequest
/// This function blocks the current thread until futures complete.
/// ///
/// ```rust /// ```rust
/// use actix_web::{App, test, web, HttpResponse, http::header}; /// use actix_web::{App, test, web, HttpResponse, http::header};
@ -222,8 +218,8 @@ where
/// name: String /// name: String
/// } /// }
/// ///
/// #[test] /// #[actix_rt::test]
/// fn test_add_person() { /// async fn test_add_person() {
/// let mut app = test::init_service( /// let mut app = test::init_service(
/// App::new().service( /// App::new().service(
/// web::resource("/people") /// web::resource("/people")
@ -512,9 +508,8 @@ mod tests {
use super::*; use super::*;
use crate::{http::header, web, App, HttpResponse}; use crate::{http::header, web, App, HttpResponse};
#[test] #[actix_rt::test]
fn test_basics() { async fn test_basics() {
block_on(async {
let req = TestRequest::with_hdr(header::ContentType::json()) let req = TestRequest::with_hdr(header::ContentType::json())
.version(Version::HTTP_2) .version(Version::HTTP_2)
.set(header::Date(SystemTime::now().into())) .set(header::Date(SystemTime::now().into()))
@ -533,21 +528,16 @@ mod tests {
assert!(req.app_data::<u64>().is_none()); assert!(req.app_data::<u64>().is_none());
let data = req.app_data::<u32>().unwrap(); let data = req.app_data::<u32>().unwrap();
assert_eq!(*data, 10); assert_eq!(*data, 10);
})
} }
#[test] #[actix_rt::test]
fn test_request_methods() { async fn test_request_methods() {
block_on(async {
let mut app = init_service( let mut app = init_service(
App::new().service( App::new().service(
web::resource("/index.html") web::resource("/index.html")
.route(web::put().to(|| async { HttpResponse::Ok().body("put!") }))
.route( .route(
web::put().to(|| async { HttpResponse::Ok().body("put!") }), web::patch().to(|| async { HttpResponse::Ok().body("patch!") }),
)
.route(
web::patch()
.to(|| async { HttpResponse::Ok().body("patch!") }),
) )
.route( .route(
web::delete() web::delete()
@ -576,12 +566,10 @@ mod tests {
let delete_req = TestRequest::delete().uri("/index.html").to_request(); let delete_req = TestRequest::delete().uri("/index.html").to_request();
let result = read_response(&mut app, delete_req).await; let result = read_response(&mut app, delete_req).await;
assert_eq!(result, Bytes::from_static(b"delete!")); assert_eq!(result, Bytes::from_static(b"delete!"));
})
} }
#[test] #[actix_rt::test]
fn test_response() { async fn test_response() {
block_on(async {
let mut app = let mut app =
init_service(App::new().service(web::resource("/index.html").route( init_service(App::new().service(web::resource("/index.html").route(
web::post().to(|| async { HttpResponse::Ok().body("welcome!") }), web::post().to(|| async { HttpResponse::Ok().body("welcome!") }),
@ -595,7 +583,6 @@ mod tests {
let result = read_response(&mut app, req).await; let result = read_response(&mut app, req).await;
assert_eq!(result, Bytes::from_static(b"welcome!")); assert_eq!(result, Bytes::from_static(b"welcome!"));
})
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@ -604,11 +591,9 @@ mod tests {
name: String, name: String,
} }
#[test] #[actix_rt::test]
fn test_response_json() { async fn test_response_json() {
block_on(async { let mut app = init_service(App::new().service(web::resource("/people").route(
let mut app =
init_service(App::new().service(web::resource("/people").route(
web::post().to(|person: web::Json<Person>| { web::post().to(|person: web::Json<Person>| {
async { HttpResponse::Ok().json(person.into_inner()) } async { HttpResponse::Ok().json(person.into_inner()) }
}), }),
@ -625,14 +610,11 @@ mod tests {
let result: Person = read_response_json(&mut app, req).await; let result: Person = read_response_json(&mut app, req).await;
assert_eq!(&result.id, "12345"); assert_eq!(&result.id, "12345");
})
} }
#[test] #[actix_rt::test]
fn test_request_response_form() { async fn test_request_response_form() {
block_on(async { let mut app = init_service(App::new().service(web::resource("/people").route(
let mut app =
init_service(App::new().service(web::resource("/people").route(
web::post().to(|person: web::Form<Person>| { web::post().to(|person: web::Form<Person>| {
async { HttpResponse::Ok().json(person.into_inner()) } async { HttpResponse::Ok().json(person.into_inner()) }
}), }),
@ -654,14 +636,11 @@ mod tests {
let result: Person = read_response_json(&mut app, req).await; let result: Person = read_response_json(&mut app, req).await;
assert_eq!(&result.id, "12345"); assert_eq!(&result.id, "12345");
assert_eq!(&result.name, "User name"); assert_eq!(&result.name, "User name");
})
} }
#[test] #[actix_rt::test]
fn test_request_response_json() { async fn test_request_response_json() {
block_on(async { let mut app = init_service(App::new().service(web::resource("/people").route(
let mut app =
init_service(App::new().service(web::resource("/people").route(
web::post().to(|person: web::Json<Person>| { web::post().to(|person: web::Json<Person>| {
async { HttpResponse::Ok().json(person.into_inner()) } async { HttpResponse::Ok().json(person.into_inner()) }
}), }),
@ -683,12 +662,10 @@ mod tests {
let result: Person = read_response_json(&mut app, req).await; let result: Person = read_response_json(&mut app, req).await;
assert_eq!(&result.id, "12345"); assert_eq!(&result.id, "12345");
assert_eq!(&result.name, "User name"); assert_eq!(&result.name, "User name");
})
} }
#[test] #[actix_rt::test]
fn test_async_with_block() { async fn test_async_with_block() {
block_on(async {
async fn async_with_block() -> Result<HttpResponse, Error> { async fn async_with_block() -> Result<HttpResponse, Error> {
let res = web::block(move || Some(4usize).ok_or("wrong")).await; let res = web::block(move || Some(4usize).ok_or("wrong")).await;
@ -708,10 +685,9 @@ mod tests {
let req = TestRequest::post().uri("/index.html").to_request(); let req = TestRequest::post().uri("/index.html").to_request();
let res = app.call(req).await.unwrap(); let res = app.call(req).await.unwrap();
assert!(res.status().is_success()); assert!(res.status().is_success());
})
} }
// #[test] // #[actix_rt::test]
// fn test_actor() { // fn test_actor() {
// use actix::Actor; // use actix::Actor;

View File

@ -10,7 +10,7 @@ use actix_http::{Error, HttpMessage, Payload, Response};
use bytes::BytesMut; use bytes::BytesMut;
use encoding_rs::{Encoding, UTF_8}; use encoding_rs::{Encoding, UTF_8};
use futures::future::{err, ok, FutureExt, LocalBoxFuture, Ready}; use futures::future::{err, ok, FutureExt, LocalBoxFuture, Ready};
use futures::{Stream, StreamExt}; use futures::StreamExt;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde::Serialize; use serde::Serialize;
@ -370,7 +370,7 @@ mod tests {
use super::*; use super::*;
use crate::http::header::{HeaderValue, CONTENT_TYPE}; use crate::http::header::{HeaderValue, CONTENT_TYPE};
use crate::test::{block_on, TestRequest}; use crate::test::TestRequest;
#[derive(Deserialize, Serialize, Debug, PartialEq)] #[derive(Deserialize, Serialize, Debug, PartialEq)]
struct Info { struct Info {
@ -378,13 +378,10 @@ mod tests {
counter: i64, counter: i64,
} }
#[test] #[actix_rt::test]
fn test_form() { async fn test_form() {
block_on(async { let (req, mut pl) =
let (req, mut pl) = TestRequest::with_header( TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header(CONTENT_LENGTH, "11") .header(CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world&counter=123")) .set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts(); .to_http_parts();
@ -397,7 +394,6 @@ mod tests {
counter: 123 counter: 123
} }
); );
})
} }
fn eq(err: UrlencodedError, other: UrlencodedError) -> bool { fn eq(err: UrlencodedError, other: UrlencodedError) -> bool {
@ -418,22 +414,17 @@ mod tests {
} }
} }
#[test] #[actix_rt::test]
fn test_urlencoded_error() { async fn test_urlencoded_error() {
block_on(async { let (req, mut pl) =
let (req, mut pl) = TestRequest::with_header( TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header(CONTENT_LENGTH, "xxxx") .header(CONTENT_LENGTH, "xxxx")
.to_http_parts(); .to_http_parts();
let info = UrlEncoded::<Info>::new(&req, &mut pl).await; let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
assert!(eq(info.err().unwrap(), UrlencodedError::UnknownLength)); assert!(eq(info.err().unwrap(), UrlencodedError::UnknownLength));
let (req, mut pl) = TestRequest::with_header( let (req, mut pl) =
CONTENT_TYPE, TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
"application/x-www-form-urlencoded",
)
.header(CONTENT_LENGTH, "1000000") .header(CONTENT_LENGTH, "1000000")
.to_http_parts(); .to_http_parts();
let info = UrlEncoded::<Info>::new(&req, &mut pl).await; let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
@ -447,16 +438,12 @@ mod tests {
.to_http_parts(); .to_http_parts();
let info = UrlEncoded::<Info>::new(&req, &mut pl).await; let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
assert!(eq(info.err().unwrap(), UrlencodedError::ContentType)); assert!(eq(info.err().unwrap(), UrlencodedError::ContentType));
})
} }
#[test] #[actix_rt::test]
fn test_urlencoded() { async fn test_urlencoded() {
block_on(async { let (req, mut pl) =
let (req, mut pl) = TestRequest::with_header( TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header(CONTENT_LENGTH, "11") .header(CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world&counter=123")) .set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts(); .to_http_parts();
@ -486,12 +473,10 @@ mod tests {
counter: 123 counter: 123
} }
); );
})
} }
#[test] #[actix_rt::test]
fn test_responder() { async fn test_responder() {
block_on(async {
let req = TestRequest::default().to_http_request(); let req = TestRequest::default().to_http_request();
let form = Form(Info { let form = Form(Info {
@ -507,6 +492,5 @@ mod tests {
use crate::responder::tests::BodyTest; use crate::responder::tests::BodyTest;
assert_eq!(resp.body().bin_ref(), b"hello=world&counter=123"); assert_eq!(resp.body().bin_ref(), b"hello=world&counter=123");
})
} }
} }

View File

@ -8,7 +8,7 @@ use std::{fmt, ops};
use bytes::BytesMut; use bytes::BytesMut;
use futures::future::{err, ok, FutureExt, LocalBoxFuture, Ready}; use futures::future::{err, ok, FutureExt, LocalBoxFuture, Ready};
use futures::{Stream, StreamExt}; use futures::StreamExt;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde::Serialize; use serde::Serialize;
use serde_json; use serde_json;
@ -402,7 +402,7 @@ mod tests {
use super::*; use super::*;
use crate::error::InternalError; use crate::error::InternalError;
use crate::http::header; use crate::http::header;
use crate::test::{block_on, load_stream, TestRequest}; use crate::test::{load_stream, TestRequest};
use crate::HttpResponse; use crate::HttpResponse;
#[derive(Serialize, Deserialize, PartialEq, Debug)] #[derive(Serialize, Deserialize, PartialEq, Debug)]
@ -424,9 +424,8 @@ mod tests {
} }
} }
#[test] #[actix_rt::test]
fn test_responder() { async fn test_responder() {
block_on(async {
let req = TestRequest::default().to_http_request(); let req = TestRequest::default().to_http_request();
let j = Json(MyObject { let j = Json(MyObject {
@ -441,12 +440,10 @@ mod tests {
use crate::responder::tests::BodyTest; use crate::responder::tests::BodyTest;
assert_eq!(resp.body().bin_ref(), b"{\"name\":\"test\"}"); assert_eq!(resp.body().bin_ref(), b"{\"name\":\"test\"}");
})
} }
#[test] #[actix_rt::test]
fn test_custom_error_responder() { async fn test_custom_error_responder() {
block_on(async {
let (req, mut pl) = TestRequest::default() let (req, mut pl) = TestRequest::default()
.header( .header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
@ -474,12 +471,10 @@ mod tests {
let body = load_stream(resp.take_body()).await.unwrap(); let body = load_stream(resp.take_body()).await.unwrap();
let msg: MyObject = serde_json::from_slice(&body).unwrap(); let msg: MyObject = serde_json::from_slice(&body).unwrap();
assert_eq!(msg.name, "invalid request"); assert_eq!(msg.name, "invalid request");
})
} }
#[test] #[actix_rt::test]
fn test_extract() { async fn test_extract() {
block_on(async {
let (req, mut pl) = TestRequest::default() let (req, mut pl) = TestRequest::default()
.header( .header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
@ -536,12 +531,10 @@ mod tests {
.to_http_parts(); .to_http_parts();
let s = Json::<MyObject>::from_request(&req, &mut pl).await; let s = Json::<MyObject>::from_request(&req, &mut pl).await;
assert!(format!("{}", s.err().unwrap()).contains("Content type error")); assert!(format!("{}", s.err().unwrap()).contains("Content type error"));
})
} }
#[test] #[actix_rt::test]
fn test_json_body() { async fn test_json_body() {
block_on(async {
let (req, mut pl) = TestRequest::default().to_http_parts(); let (req, mut pl) = TestRequest::default().to_http_parts();
let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await; let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType)); assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
@ -590,12 +583,10 @@ mod tests {
name: "test".to_owned() name: "test".to_owned()
} }
); );
})
} }
#[test] #[actix_rt::test]
fn test_with_json_and_bad_content_type() { async fn test_with_json_and_bad_content_type() {
block_on(async {
let (req, mut pl) = TestRequest::with_header( let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain"), header::HeaderValue::from_static("text/plain"),
@ -610,12 +601,10 @@ mod tests {
let s = Json::<MyObject>::from_request(&req, &mut pl).await; let s = Json::<MyObject>::from_request(&req, &mut pl).await;
assert!(s.is_err()) assert!(s.is_err())
})
} }
#[test] #[actix_rt::test]
fn test_with_json_and_good_custom_content_type() { async fn test_with_json_and_good_custom_content_type() {
block_on(async {
let (req, mut pl) = TestRequest::with_header( let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain"), header::HeaderValue::from_static("text/plain"),
@ -632,12 +621,10 @@ mod tests {
let s = Json::<MyObject>::from_request(&req, &mut pl).await; let s = Json::<MyObject>::from_request(&req, &mut pl).await;
assert!(s.is_ok()) assert!(s.is_ok())
})
} }
#[test] #[actix_rt::test]
fn test_with_json_and_bad_custom_content_type() { async fn test_with_json_and_bad_custom_content_type() {
block_on(async {
let (req, mut pl) = TestRequest::with_header( let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
header::HeaderValue::from_static("text/html"), header::HeaderValue::from_static("text/html"),
@ -654,6 +641,5 @@ mod tests {
let s = Json::<MyObject>::from_request(&req, &mut pl).await; let s = Json::<MyObject>::from_request(&req, &mut pl).await;
assert!(s.is_err()) assert!(s.is_err())
})
} }
} }

View File

@ -12,3 +12,4 @@ pub use self::json::{Json, JsonConfig};
pub use self::path::{Path, PathConfig}; pub use self::path::{Path, PathConfig};
pub use self::payload::{Payload, PayloadConfig}; pub use self::payload::{Payload, PayloadConfig};
pub use self::query::{Query, QueryConfig}; pub use self::query::{Query, QueryConfig};
pub use self::readlines::Readlines;

View File

@ -1,5 +1,4 @@
//! Path extractor //! Path extractor
use std::sync::Arc; use std::sync::Arc;
use std::{fmt, ops}; use std::{fmt, ops};
@ -253,7 +252,7 @@ mod tests {
use serde_derive::Deserialize; use serde_derive::Deserialize;
use super::*; use super::*;
use crate::test::{block_on, TestRequest}; use crate::test::TestRequest;
use crate::{error, http, HttpResponse}; use crate::{error, http, HttpResponse};
#[derive(Deserialize, Debug, Display)] #[derive(Deserialize, Debug, Display)]
@ -269,9 +268,8 @@ mod tests {
value: u32, value: u32,
} }
#[test] #[actix_rt::test]
fn test_extract_path_single() { async fn test_extract_path_single() {
block_on(async {
let resource = ResourceDef::new("/{value}/"); let resource = ResourceDef::new("/{value}/");
let mut req = TestRequest::with_uri("/32/").to_srv_request(); let mut req = TestRequest::with_uri("/32/").to_srv_request();
@ -280,12 +278,10 @@ mod tests {
let (req, mut pl) = req.into_parts(); let (req, mut pl) = req.into_parts();
assert_eq!(*Path::<i8>::from_request(&req, &mut pl).await.unwrap(), 32); assert_eq!(*Path::<i8>::from_request(&req, &mut pl).await.unwrap(), 32);
assert!(Path::<MyStruct>::from_request(&req, &mut pl).await.is_err()); assert!(Path::<MyStruct>::from_request(&req, &mut pl).await.is_err());
})
} }
#[test] #[actix_rt::test]
fn test_tuple_extract() { async fn test_tuple_extract() {
block_on(async {
let resource = ResourceDef::new("/{key}/{value}/"); let resource = ResourceDef::new("/{key}/{value}/");
let mut req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request(); let mut req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request();
@ -309,12 +305,10 @@ mod tests {
assert_eq!((res.1).1, "user1"); assert_eq!((res.1).1, "user1");
let () = <()>::from_request(&req, &mut pl).await.unwrap(); let () = <()>::from_request(&req, &mut pl).await.unwrap();
})
} }
#[test] #[actix_rt::test]
fn test_request_extract() { async fn test_request_extract() {
block_on(async {
let mut req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request(); let mut req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request();
let resource = ResourceDef::new("/{key}/{value}/"); let resource = ResourceDef::new("/{key}/{value}/");
@ -359,12 +353,10 @@ mod tests {
.unwrap(); .unwrap();
assert_eq!(res[0], "name".to_owned()); assert_eq!(res[0], "name".to_owned());
assert_eq!(res[1], "32".to_owned()); assert_eq!(res[1], "32".to_owned());
})
} }
#[test] #[actix_rt::test]
fn test_custom_err_handler() { async fn test_custom_err_handler() {
block_on(async {
let (req, mut pl) = TestRequest::with_uri("/name/user1/") let (req, mut pl) = TestRequest::with_uri("/name/user1/")
.data(PathConfig::default().error_handler(|err, _| { .data(PathConfig::default().error_handler(|err, _| {
error::InternalError::from_response( error::InternalError::from_response(
@ -381,6 +373,5 @@ mod tests {
let res: HttpResponse = s.into(); let res: HttpResponse = s.into();
assert_eq!(res.status(), http::StatusCode::CONFLICT); assert_eq!(res.status(), http::StatusCode::CONFLICT);
})
} }
} }

View File

@ -395,10 +395,10 @@ mod tests {
use super::*; use super::*;
use crate::http::header; use crate::http::header;
use crate::test::{block_on, TestRequest}; use crate::test::TestRequest;
#[test] #[actix_rt::test]
fn test_payload_config() { async fn test_payload_config() {
let req = TestRequest::default().to_http_request(); let req = TestRequest::default().to_http_request();
let cfg = PayloadConfig::default().mimetype(mime::APPLICATION_JSON); let cfg = PayloadConfig::default().mimetype(mime::APPLICATION_JSON);
assert!(cfg.check_mimetype(&req).is_err()); assert!(cfg.check_mimetype(&req).is_err());
@ -415,32 +415,32 @@ mod tests {
assert!(cfg.check_mimetype(&req).is_ok()); assert!(cfg.check_mimetype(&req).is_ok());
} }
#[test] #[actix_rt::test]
fn test_bytes() { async fn test_bytes() {
let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "11") let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world")) .set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts(); .to_http_parts();
let s = block_on(Bytes::from_request(&req, &mut pl)).unwrap(); let s = Bytes::from_request(&req, &mut pl).await.unwrap();
assert_eq!(s, Bytes::from_static(b"hello=world")); assert_eq!(s, Bytes::from_static(b"hello=world"));
} }
#[test] #[actix_rt::test]
fn test_string() { async fn test_string() {
let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "11") let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world")) .set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts(); .to_http_parts();
let s = block_on(String::from_request(&req, &mut pl)).unwrap(); let s = String::from_request(&req, &mut pl).await.unwrap();
assert_eq!(s, "hello=world"); assert_eq!(s, "hello=world");
} }
#[test] #[actix_rt::test]
fn test_message_body() { async fn test_message_body() {
let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "xxxx") let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "xxxx")
.to_srv_request() .to_srv_request()
.into_parts(); .into_parts();
let res = block_on(HttpMessageBody::new(&req, &mut pl)); let res = HttpMessageBody::new(&req, &mut pl).await;
match res.err().unwrap() { match res.err().unwrap() {
PayloadError::UnknownLength => (), PayloadError::UnknownLength => (),
_ => unreachable!("error"), _ => unreachable!("error"),
@ -449,7 +449,7 @@ mod tests {
let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "1000000") let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "1000000")
.to_srv_request() .to_srv_request()
.into_parts(); .into_parts();
let res = block_on(HttpMessageBody::new(&req, &mut pl)); let res = HttpMessageBody::new(&req, &mut pl).await;
match res.err().unwrap() { match res.err().unwrap() {
PayloadError::Overflow => (), PayloadError::Overflow => (),
_ => unreachable!("error"), _ => unreachable!("error"),
@ -458,13 +458,13 @@ mod tests {
let (req, mut pl) = TestRequest::default() let (req, mut pl) = TestRequest::default()
.set_payload(Bytes::from_static(b"test")) .set_payload(Bytes::from_static(b"test"))
.to_http_parts(); .to_http_parts();
let res = block_on(HttpMessageBody::new(&req, &mut pl)); let res = HttpMessageBody::new(&req, &mut pl).await;
assert_eq!(res.ok().unwrap(), Bytes::from_static(b"test")); assert_eq!(res.ok().unwrap(), Bytes::from_static(b"test"));
let (req, mut pl) = TestRequest::default() let (req, mut pl) = TestRequest::default()
.set_payload(Bytes::from_static(b"11111111111111")) .set_payload(Bytes::from_static(b"11111111111111"))
.to_http_parts(); .to_http_parts();
let res = block_on(HttpMessageBody::new(&req, &mut pl).limit(5)); let res = HttpMessageBody::new(&req, &mut pl).limit(5).await;
match res.err().unwrap() { match res.err().unwrap() {
PayloadError::Overflow => (), PayloadError::Overflow => (),
_ => unreachable!("error"), _ => unreachable!("error"),

View File

@ -228,7 +228,7 @@ mod tests {
use super::*; use super::*;
use crate::error::InternalError; use crate::error::InternalError;
use crate::test::{block_on, TestRequest}; use crate::test::TestRequest;
use crate::HttpResponse; use crate::HttpResponse;
#[derive(Deserialize, Debug, Display)] #[derive(Deserialize, Debug, Display)]
@ -236,8 +236,8 @@ mod tests {
id: String, id: String,
} }
#[test] #[actix_rt::test]
fn test_service_request_extract() { async fn test_service_request_extract() {
let req = TestRequest::with_uri("/name/user1/").to_srv_request(); let req = TestRequest::with_uri("/name/user1/").to_srv_request();
assert!(Query::<Id>::from_query(&req.query_string()).is_err()); assert!(Query::<Id>::from_query(&req.query_string()).is_err());
@ -252,9 +252,8 @@ mod tests {
assert_eq!(s.id, "test1"); assert_eq!(s.id, "test1");
} }
#[test] #[actix_rt::test]
fn test_request_extract() { async fn test_request_extract() {
block_on(async {
let req = TestRequest::with_uri("/name/user1/").to_srv_request(); let req = TestRequest::with_uri("/name/user1/").to_srv_request();
let (req, mut pl) = req.into_parts(); let (req, mut pl) = req.into_parts();
assert!(Query::<Id>::from_request(&req, &mut pl).await.is_err()); assert!(Query::<Id>::from_request(&req, &mut pl).await.is_err());
@ -269,12 +268,10 @@ mod tests {
s.id = "test1".to_string(); s.id = "test1".to_string();
let s = s.into_inner(); let s = s.into_inner();
assert_eq!(s.id, "test1"); assert_eq!(s.id, "test1");
})
} }
#[test] #[actix_rt::test]
fn test_custom_error_responder() { async fn test_custom_error_responder() {
block_on(async {
let req = TestRequest::with_uri("/name/user1/") let req = TestRequest::with_uri("/name/user1/")
.data(QueryConfig::default().error_handler(|e, _| { .data(QueryConfig::default().error_handler(|e, _| {
let resp = HttpResponse::UnprocessableEntity().finish(); let resp = HttpResponse::UnprocessableEntity().finish();
@ -294,6 +291,5 @@ mod tests {
.status(), .status(),
StatusCode::UNPROCESSABLE_ENTITY StatusCode::UNPROCESSABLE_ENTITY
); );
})
} }
} }

View File

@ -1,5 +1,4 @@
use std::borrow::Cow; use std::borrow::Cow;
use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
use std::str; use std::str;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
@ -7,7 +6,6 @@ use std::task::{Context, Poll};
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use encoding_rs::{Encoding, UTF_8}; use encoding_rs::{Encoding, UTF_8};
use futures::Stream; use futures::Stream;
use pin_project::pin_project;
use crate::dev::Payload; use crate::dev::Payload;
use crate::error::{PayloadError, ReadlinesError}; use crate::error::{PayloadError, ReadlinesError};
@ -174,11 +172,10 @@ mod tests {
use futures::stream::StreamExt; use futures::stream::StreamExt;
use super::*; use super::*;
use crate::test::{block_on, TestRequest}; use crate::test::TestRequest;
#[test] #[actix_rt::test]
fn test_readlines() { async fn test_readlines() {
block_on(async {
let mut req = TestRequest::default() let mut req = TestRequest::default()
.set_payload(Bytes::from_static( .set_payload(Bytes::from_static(
b"Lorem Ipsum is simply dummy text of the printing and typesetting\n\ b"Lorem Ipsum is simply dummy text of the printing and typesetting\n\
@ -202,6 +199,5 @@ mod tests {
stream.next().await.unwrap().unwrap(), stream.next().await.unwrap().unwrap(),
"Contrary to popular belief, Lorem Ipsum is not simply random text." "Contrary to popular belief, Lorem Ipsum is not simply random text."
); );
})
} }
} }

View File

@ -6,7 +6,6 @@ pub use actix_http::Response as HttpResponse;
pub use bytes::{Bytes, BytesMut}; pub use bytes::{Bytes, BytesMut};
pub use futures::channel::oneshot::Canceled; pub use futures::channel::oneshot::Canceled;
use crate::error::Error;
use crate::extract::FromRequest; use crate::extract::FromRequest;
use crate::handler::Factory; use crate::handler::Factory;
use crate::resource::Resource; use crate::resource::Resource;

View File

@ -54,8 +54,6 @@ slab = "0.4"
serde_urlencoded = "0.6.1" serde_urlencoded = "0.6.1"
time = "0.1" time = "0.1"
tokio-net = "0.2.0-alpha.6" tokio-net = "0.2.0-alpha.6"
tokio-timer = "0.3.0-alpha.6"
open-ssl = { version="0.10", package="openssl", optional = true } open-ssl = { version="0.10", package="openssl", optional = true }
[dev-dependencies] [dev-dependencies]

View File

@ -23,15 +23,15 @@ pub use actix_testing::*;
/// ///
/// ```rust /// ```rust
/// use actix_http::HttpService; /// use actix_http::HttpService;
/// use actix_http_test::{block_on, TestServer}; /// use actix_http_test::TestServer;
/// use actix_web::{web, App, HttpResponse, Error}; /// use actix_web::{web, App, HttpResponse, Error};
/// ///
/// async fn my_handler() -> Result<HttpResponse, Error> { /// async fn my_handler() -> Result<HttpResponse, Error> {
/// Ok(HttpResponse::Ok().into()) /// Ok(HttpResponse::Ok().into())
/// } /// }
/// ///
/// fn main() { /// #[actix_rt::test]
/// block_on( async { /// async fn test_example() {
/// let mut srv = TestServer::start( /// let mut srv = TestServer::start(
/// || HttpService::new( /// || HttpService::new(
/// App::new().service( /// App::new().service(
@ -42,7 +42,6 @@ pub use actix_testing::*;
/// let req = srv.get("/"); /// let req = srv.get("/");
/// let response = req.send().await.unwrap(); /// let response = req.send().await.unwrap();
/// assert!(response.status().is_success()); /// assert!(response.status().is_success());
/// })
/// } /// }
/// ``` /// ```
pub struct TestServer; pub struct TestServer;

View File

@ -6,7 +6,7 @@ use std::{net, thread, time::Duration};
use open_ssl::ssl::SslAcceptorBuilder; use open_ssl::ssl::SslAcceptorBuilder;
use actix_http::Response; use actix_http::Response;
use actix_web::{test, web, App, HttpServer}; use actix_web::{web, App, HttpServer};
fn unused_addr() -> net::SocketAddr { fn unused_addr() -> net::SocketAddr {
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap(); let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
@ -17,9 +17,9 @@ fn unused_addr() -> net::SocketAddr {
tcp.local_addr().unwrap() tcp.local_addr().unwrap()
} }
#[test]
#[cfg(unix)] #[cfg(unix)]
fn test_start() { #[actix_rt::test]
async fn test_start() {
let addr = unused_addr(); let addr = unused_addr();
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
@ -53,9 +53,7 @@ fn test_start() {
#[cfg(feature = "client")] #[cfg(feature = "client")]
{ {
use actix_http::client; use actix_http::client;
use actix_web::test;
test::block_on(async {
let client = awc::Client::build() let client = awc::Client::build()
.connector( .connector(
client::Connector::new() client::Connector::new()
@ -67,7 +65,6 @@ fn test_start() {
let host = format!("http://{}", addr); let host = format!("http://{}", addr);
let response = client.get(host.clone()).send().await.unwrap(); let response = client.get(host.clone()).send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
});
} }
// stop // stop
@ -91,9 +88,9 @@ fn ssl_acceptor() -> std::io::Result<SslAcceptorBuilder> {
Ok(builder) Ok(builder)
} }
#[test] #[actix_rt::test]
#[cfg(feature = "openssl")] #[cfg(feature = "openssl")]
fn test_start_ssl() { async fn test_start_ssl() {
let addr = unused_addr(); let addr = unused_addr();
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
@ -119,7 +116,6 @@ fn test_start_ssl() {
}); });
let (srv, sys) = rx.recv().unwrap(); let (srv, sys) = rx.recv().unwrap();
test::block_on(async move {
use open_ssl::ssl::{SslConnector, SslMethod, SslVerifyMode}; use open_ssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
let mut builder = SslConnector::builder(SslMethod::tls()).unwrap(); let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
builder.set_verify(SslVerifyMode::NONE); builder.set_verify(SslVerifyMode::NONE);
@ -139,7 +135,6 @@ fn test_start_ssl() {
let host = format!("https://{}", addr); let host = format!("https://{}", addr);
let response = client.get(host.clone()).send().await.unwrap(); let response = client.get(host.clone()).send().await.unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
});
// stop // stop
let _ = srv.stop(false); let _ = srv.stop(false);

View File

@ -5,7 +5,7 @@ use actix_http::http::header::{
TRANSFER_ENCODING, TRANSFER_ENCODING,
}; };
use actix_http::{h1, Error, HttpService, Response}; use actix_http::{h1, Error, HttpService, Response};
use actix_http_test::{block_on, TestServer}; use actix_http_test::TestServer;
use brotli2::write::{BrotliDecoder, BrotliEncoder}; use brotli2::write::{BrotliDecoder, BrotliEncoder};
use bytes::Bytes; use bytes::Bytes;
use flate2::read::GzDecoder; use flate2::read::GzDecoder;
@ -39,14 +39,13 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World"; Hello World Hello World Hello World Hello World Hello World";
#[test] #[actix_rt::test]
fn test_body() { async fn test_body() {
block_on(async { let srv = TestServer::start(|| {
let srv = h1::H1Service::new(
TestServer::start(|| { App::new()
h1::H1Service::new(App::new().service( .service(web::resource("/").route(web::to(|| Response::Ok().body(STR)))),
web::resource("/").route(web::to(|| Response::Ok().body(STR))), )
))
}); });
let mut response = srv.get("/").send().await.unwrap(); let mut response = srv.get("/").send().await.unwrap();
@ -55,20 +54,16 @@ fn test_body() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
#[test] #[actix_rt::test]
fn test_body_gzip() { async fn test_body_gzip() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
h1::H1Service::new( h1::H1Service::new(
App::new() App::new()
.wrap(Compress::new(ContentEncoding::Gzip)) .wrap(Compress::new(ContentEncoding::Gzip))
.service( .service(web::resource("/").route(web::to(|| Response::Ok().body(STR)))),
web::resource("/").route(web::to(|| Response::Ok().body(STR))),
),
) )
}); });
@ -89,13 +84,11 @@ fn test_body_gzip() {
let mut dec = Vec::new(); let mut dec = Vec::new();
e.read_to_end(&mut dec).unwrap(); e.read_to_end(&mut dec).unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref())); assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
})
} }
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
#[test] #[actix_rt::test]
fn test_body_gzip2() { async fn test_body_gzip2() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
h1::H1Service::new( h1::H1Service::new(
App::new() App::new()
@ -123,13 +116,11 @@ fn test_body_gzip2() {
let mut dec = Vec::new(); let mut dec = Vec::new();
e.read_to_end(&mut dec).unwrap(); e.read_to_end(&mut dec).unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref())); assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
})
} }
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
#[test] #[actix_rt::test]
fn test_body_encoding_override() { async fn test_body_encoding_override() {
block_on(async {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
h1::H1Service::new( h1::H1Service::new(
App::new() App::new()
@ -186,13 +177,11 @@ fn test_body_encoding_override() {
e.write_all(bytes.as_ref()).unwrap(); e.write_all(bytes.as_ref()).unwrap();
let dec = e.finish().unwrap(); let dec = e.finish().unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref())); assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
})
} }
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
#[test] #[actix_rt::test]
fn test_body_gzip_large() { async fn test_body_gzip_large() {
block_on(async {
let data = STR.repeat(10); let data = STR.repeat(10);
let srv_data = data.clone(); let srv_data = data.clone();
@ -225,13 +214,11 @@ fn test_body_gzip_large() {
let mut dec = Vec::new(); let mut dec = Vec::new();
e.read_to_end(&mut dec).unwrap(); e.read_to_end(&mut dec).unwrap();
assert_eq!(Bytes::from(dec), Bytes::from(data)); assert_eq!(Bytes::from(dec), Bytes::from(data));
})
} }
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
#[test] #[actix_rt::test]
fn test_body_gzip_large_random() { async fn test_body_gzip_large_random() {
block_on(async {
let data = rand::thread_rng() let data = rand::thread_rng()
.sample_iter(&Alphanumeric) .sample_iter(&Alphanumeric)
.take(70_000) .take(70_000)
@ -268,21 +255,19 @@ fn test_body_gzip_large_random() {
e.read_to_end(&mut dec).unwrap(); e.read_to_end(&mut dec).unwrap();
assert_eq!(dec.len(), data.len()); assert_eq!(dec.len(), data.len());
assert_eq!(Bytes::from(dec), Bytes::from(data)); assert_eq!(Bytes::from(dec), Bytes::from(data));
})
} }
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
#[test] #[actix_rt::test]
fn test_body_chunked_implicit() { async fn test_body_chunked_implicit() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( h1::H1Service::new(
App::new() App::new()
.wrap(Compress::new(ContentEncoding::Gzip)) .wrap(Compress::new(ContentEncoding::Gzip))
.service(web::resource("/").route(web::get().to(move || { .service(web::resource("/").route(web::get().to(move || {
Response::Ok().streaming(once(ok::<_, Error>( Response::Ok().streaming(once(ok::<_, Error>(Bytes::from_static(
Bytes::from_static(STR.as_ref()), STR.as_ref(),
))) ))))
}))), }))),
) )
}); });
@ -308,23 +293,18 @@ fn test_body_chunked_implicit() {
let mut dec = Vec::new(); let mut dec = Vec::new();
e.read_to_end(&mut dec).unwrap(); e.read_to_end(&mut dec).unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref())); assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
#[cfg(feature = "brotli")] #[cfg(feature = "brotli")]
fn test_body_br_streaming() { async fn test_body_br_streaming() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( h1::H1Service::new(App::new().wrap(Compress::new(ContentEncoding::Br)).service(
App::new().wrap(Compress::new(ContentEncoding::Br)).service(
web::resource("/").route(web::to(move || { web::resource("/").route(web::to(move || {
Response::Ok().streaming(once(ok::<_, Error>( Response::Ok()
Bytes::from_static(STR.as_ref()), .streaming(once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))))
)))
})), })),
), ))
)
}); });
let mut response = srv let mut response = srv
@ -344,12 +324,10 @@ fn test_body_br_streaming() {
e.write_all(bytes.as_ref()).unwrap(); e.write_all(bytes.as_ref()).unwrap();
let dec = e.finish().unwrap(); let dec = e.finish().unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref())); assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
fn test_head_binary() { async fn test_head_binary() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new(App::new().service(web::resource("/").route( h1::H1Service::new(App::new().service(web::resource("/").route(
web::head().to(move || Response::Ok().content_length(100).body(STR)), web::head().to(move || Response::Ok().content_length(100).body(STR)),
@ -367,21 +345,17 @@ fn test_head_binary() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert!(bytes.is_empty()); assert!(bytes.is_empty());
})
} }
#[test] #[actix_rt::test]
fn test_no_chunking() { async fn test_no_chunking() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new(App::new().service(web::resource("/").route(web::to( h1::H1Service::new(App::new().service(web::resource("/").route(web::to(
move || { move || {
Response::Ok() Response::Ok()
.no_chunking() .no_chunking()
.content_length(STR.len() as u64) .content_length(STR.len() as u64)
.streaming(once(ok::<_, Error>(Bytes::from_static( .streaming(once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))))
STR.as_ref(),
))))
}, },
)))) ))))
}); });
@ -393,20 +367,17 @@ fn test_no_chunking() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
fn test_body_deflate() { async fn test_body_deflate() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( h1::H1Service::new(
App::new() App::new()
.wrap(Compress::new(ContentEncoding::Deflate)) .wrap(Compress::new(ContentEncoding::Deflate))
.service( .service(
web::resource("/") web::resource("/").route(web::to(move || Response::Ok().body(STR))),
.route(web::to(move || Response::Ok().body(STR))),
), ),
) )
}); });
@ -428,19 +399,15 @@ fn test_body_deflate() {
e.write_all(bytes.as_ref()).unwrap(); e.write_all(bytes.as_ref()).unwrap();
let dec = e.finish().unwrap(); let dec = e.finish().unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref())); assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
#[cfg(any(feature = "brotli"))] #[cfg(any(feature = "brotli"))]
fn test_body_brotli() { async fn test_body_brotli() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( h1::H1Service::new(App::new().wrap(Compress::new(ContentEncoding::Br)).service(
App::new().wrap(Compress::new(ContentEncoding::Br)).service(
web::resource("/").route(web::to(move || Response::Ok().body(STR))), web::resource("/").route(web::to(move || Response::Ok().body(STR))),
), ))
)
}); });
// client request // client request
@ -461,13 +428,11 @@ fn test_body_brotli() {
e.write_all(bytes.as_ref()).unwrap(); e.write_all(bytes.as_ref()).unwrap();
let dec = e.finish().unwrap(); let dec = e.finish().unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref())); assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
fn test_encoding() { async fn test_encoding() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
HttpService::new( HttpService::new(
App::new().wrap(Compress::default()).service( App::new().wrap(Compress::default()).service(
@ -492,13 +457,11 @@ fn test_encoding() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
fn test_gzip_encoding() { async fn test_gzip_encoding() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
HttpService::new( HttpService::new(
App::new().service( App::new().service(
@ -523,13 +486,11 @@ fn test_gzip_encoding() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
fn test_gzip_encoding_large() { async fn test_gzip_encoding_large() {
block_on(async {
let data = STR.repeat(10); let data = STR.repeat(10);
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( h1::H1Service::new(
@ -555,13 +516,11 @@ fn test_gzip_encoding_large() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from(data)); assert_eq!(bytes, Bytes::from(data));
})
} }
#[test] #[actix_rt::test]
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
fn test_reading_gzip_encoding_large_random() { async fn test_reading_gzip_encoding_large_random() {
block_on(async {
let data = rand::thread_rng() let data = rand::thread_rng()
.sample_iter(&Alphanumeric) .sample_iter(&Alphanumeric)
.take(60_000) .take(60_000)
@ -592,13 +551,11 @@ fn test_reading_gzip_encoding_large_random() {
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes.len(), data.len()); assert_eq!(bytes.len(), data.len());
assert_eq!(bytes, Bytes::from(data)); assert_eq!(bytes, Bytes::from(data));
})
} }
#[test] #[actix_rt::test]
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
fn test_reading_deflate_encoding() { async fn test_reading_deflate_encoding() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( h1::H1Service::new(
App::new().service( App::new().service(
@ -623,13 +580,11 @@ fn test_reading_deflate_encoding() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[test] #[actix_rt::test]
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
fn test_reading_deflate_encoding_large() { async fn test_reading_deflate_encoding_large() {
block_on(async {
let data = STR.repeat(10); let data = STR.repeat(10);
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( h1::H1Service::new(
@ -655,13 +610,11 @@ fn test_reading_deflate_encoding_large() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from(data)); assert_eq!(bytes, Bytes::from(data));
})
} }
#[test] #[actix_rt::test]
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))] #[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
fn test_reading_deflate_encoding_large_random() { async fn test_reading_deflate_encoding_large_random() {
block_on(async {
let data = rand::thread_rng() let data = rand::thread_rng()
.sample_iter(&Alphanumeric) .sample_iter(&Alphanumeric)
.take(160_000) .take(160_000)
@ -692,13 +645,11 @@ fn test_reading_deflate_encoding_large_random() {
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes.len(), data.len()); assert_eq!(bytes.len(), data.len());
assert_eq!(bytes, Bytes::from(data)); assert_eq!(bytes, Bytes::from(data));
})
} }
#[test] #[actix_rt::test]
#[cfg(feature = "brotli")] #[cfg(feature = "brotli")]
fn test_brotli_encoding() { async fn test_brotli_encoding() {
block_on(async {
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( h1::H1Service::new(
App::new().service( App::new().service(
@ -723,13 +674,11 @@ fn test_brotli_encoding() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
} }
#[cfg(feature = "brotli")] #[cfg(feature = "brotli")]
#[test] #[actix_rt::test]
fn test_brotli_encoding_large() { async fn test_brotli_encoding_large() {
block_on(async {
let data = STR.repeat(10); let data = STR.repeat(10);
let srv = TestServer::start(move || { let srv = TestServer::start(move || {
h1::H1Service::new( h1::H1Service::new(
@ -755,12 +704,11 @@ fn test_brotli_encoding_large() {
// read response // read response
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from(data)); assert_eq!(bytes, Bytes::from(data));
})
} }
// #[cfg(all(feature = "brotli", feature = "ssl"))] // #[cfg(all(feature = "brotli", feature = "ssl"))]
// #[test] // #[actix_rt::test]
// fn test_brotli_encoding_large_ssl() { // async fn test_brotli_encoding_large_ssl() {
// use actix::{Actor, System}; // use actix::{Actor, System};
// use openssl::ssl::{ // use openssl::ssl::{
// SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode, // SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode,
@ -819,9 +767,8 @@ fn test_brotli_encoding_large() {
feature = "openssl", feature = "openssl",
any(feature = "flate2-zlib", feature = "flate2-rust") any(feature = "flate2-zlib", feature = "flate2-rust")
))] ))]
#[test] #[actix_rt::test]
fn test_reading_deflate_encoding_large_random_ssl() { async fn test_reading_deflate_encoding_large_random_ssl() {
block_on(async {
use open_ssl::ssl::{SslConnector, SslMethod, SslVerifyMode}; use open_ssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
use rust_tls::internal::pemfile::{certs, pkcs8_private_keys}; use rust_tls::internal::pemfile::{certs, pkcs8_private_keys};
use rust_tls::{NoClientAuth, ServerConfig}; use rust_tls::{NoClientAuth, ServerConfig};
@ -903,7 +850,6 @@ fn test_reading_deflate_encoding_large_random_ssl() {
// stop // stop
let _ = srv.stop(false); let _ = srv.stop(false);
})
} }
// #[cfg(all(feature = "tls", feature = "ssl"))] // #[cfg(all(feature = "tls", feature = "ssl"))]