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:
- cargo update
- cargo check --all --no-default-features
- 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 ..
- |
if [[ "$TRAVIS_RUST_VERSION" == "stable" || "$TRAVIS_RUST_VERSION" == "beta" ]]; then
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
after_success:

View File

@ -66,7 +66,7 @@ fail = ["actix-http/fail"]
openssl = ["open-ssl", "actix-server/openssl", "awc/openssl"]
# rustls
# rustls = ["rust-tls", "actix-server/rustls", "awc/rustls"]
rustls = ["rust-tls", "actix-server/rustls", "awc/rustls"]
[dependencies]
actix-codec = "0.2.0-alpha.1"
@ -110,7 +110,6 @@ actix-http-test = "0.3.0-alpha.1"
rand = "0.7"
env_logger = "0.6"
serde_derive = "1.0"
tokio-timer = "0.3.0-alpha.6"
brotli2 = "0.3.2"
flate2 = "1.0.2"
@ -135,19 +134,9 @@ awc = { path = "awc" }
actix-codec = { 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-macros = { 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-service = { 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-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"
derive_more = "0.99.2"
futures = "0.3.1"
[dev-dependencies]
actix-rt = "1.0.0-alpha.1"

View File

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

View File

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

View File

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

View File

@ -29,7 +29,7 @@ default = []
openssl = ["open-ssl", "actix-connect/openssl", "tokio-openssl"]
# rustls support
# rustls = ["rust-tls", "webpki-roots", "actix-connect/rustls"]
rustls = ["rust-tls", "webpki-roots", "actix-connect/rustls"]
# brotli encoding, requires c compiler
brotli = ["brotli2"]
@ -52,6 +52,7 @@ actix-codec = "0.2.0-alpha.1"
actix-connect = "1.0.0-alpha.1"
actix-utils = "0.5.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"
base64 = "0.10"
@ -83,11 +84,7 @@ slab = "0.4"
serde_urlencoded = "0.6.1"
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-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 }
# for secure cookie
@ -106,8 +103,7 @@ rust-tls = { version = "0.16.0", package="rustls", optional = true }
webpki-roots = { version = "0.18", optional = true }
[dev-dependencies]
actix-rt = "1.0.0-alpha.1"
actix-server = { version = "0.8.0-alpha.1", features=["openssl"] }
actix-server = { version = "0.8.0-alpha.1", features=["openssl", "rustls"] }
actix-connect = { version = "1.0.0-alpha.1", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] }
env_logger = "0.6"

View File

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

View File

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

View File

@ -1,4 +1,3 @@
use std::future::Future;
use std::io::Write;
use std::pin::Pin;
use std::task::{Context, Poll};
@ -6,8 +5,8 @@ use std::{io, time};
use actix_codec::{AsyncRead, AsyncWrite, Framed};
use bytes::{BufMut, Bytes, BytesMut};
use futures::future::{ok, poll_fn, Either};
use futures::{Sink, SinkExt, Stream, StreamExt};
use futures::future::poll_fn;
use futures::{SinkExt, Stream, StreamExt};
use crate::error::PayloadError;
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 actix_codec::{AsyncRead, AsyncWrite};
use bytes::Bytes;
use futures::future::{err, poll_fn, Either};
use futures::future::poll_fn;
use h2::{client::SendRequest, SendStream};
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING};
use http::{request::Request, HttpTryFrom, Method, Version};

View File

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

View File

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

View File

@ -1,5 +1,4 @@
use ring::hkdf::{Algorithm, KeyType, Prk, HKDF_SHA256};
use ring::hmac;
use ring::rand::{SecureRandom, SystemRandom};
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_json::error::Error as JsonError;
use serde_urlencoded::ser::Error as FormError;
use tokio_timer::Error as TimerError;
// re-export for convinience
use crate::body::Body;
@ -178,9 +177,6 @@ impl ResponseError for JsonError {}
/// `InternalServerError` for `FormError`
impl ResponseError for FormError {}
/// `InternalServerError` for `TimerError`
impl ResponseError for TimerError {}
#[cfg(feature = "openssl")]
/// `InternalServerError` for `openssl::ssl::Error`
impl ResponseError for open_ssl::ssl::Error {}

View File

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

View File

@ -3,15 +3,15 @@ use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
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_service::Service;
use bitflags::bitflags;
use bytes::{BufMut, BytesMut};
use log::{error, trace};
use tokio_timer::{delay, Delay};
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
use crate::cloneable::CloneableService;
@ -893,10 +893,9 @@ mod tests {
use crate::h1::{ExpectHandler, UpgradeHandler};
use crate::test::TestBuffer;
#[test]
fn test_req_parse_err() {
let mut sys = actix_rt::System::new("test");
let _ = sys.block_on(lazy(|cx| {
#[actix_rt::test]
async fn test_req_parse_err() {
lazy(|cx| {
let buf = TestBuffer::new("GET /test HTTP/1\r\n\r\n");
let mut h1 = Dispatcher::<_, _, _, _, UpgradeHandler<TestBuffer>>::new(
@ -918,7 +917,7 @@ mod tests {
assert!(inner.flags.contains(Flags::READ_DISCONNECT));
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 actix_server_config::ServerConfig;

View File

@ -1,7 +1,6 @@
//! Payload stream
use std::cell::RefCell;
use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::rc::{Rc, Weak};
use std::task::{Context, Poll};
@ -227,12 +226,10 @@ impl Inner {
#[cfg(test)]
mod tests {
use super::*;
use actix_rt::Runtime;
use futures::future::{poll_fn, ready};
use futures::future::poll_fn;
#[test]
fn test_unread_data() {
Runtime::new().unwrap().block_on(async {
#[actix_rt::test]
async fn test_unread_data() {
let (_, mut payload) = Payload::create(false);
payload.unread_data(Bytes::from("data"));
@ -243,8 +240,5 @@ mod tests {
Bytes::from("data"),
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_service::{IntoServiceFactory, Service, ServiceFactory};
use futures::future::{ok, Ready};
use futures::{ready, Stream};
use futures::ready;
use crate::body::MessageBody;
use crate::cloneable::CloneableService;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -8,7 +8,7 @@ use actix_server_config::{
Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig,
};
use actix_service::{IntoServiceFactory, Service, ServiceFactory};
use bytes::{Buf, BufMut, Bytes, BytesMut};
use bytes::{BufMut, Bytes, BytesMut};
use futures::{ready, Future};
use h2::server::{self, Handshake};
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(
self: Pin<&mut Self>,
cx: &mut Context<'_>,

View File

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

View File

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

View File

@ -2,7 +2,7 @@
use std::io;
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_config::ServerConfig;
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()))
}
#[test]
fn test_h2() -> io::Result<()> {
block_on(async {
#[actix_rt::test]
async fn test_h2() -> io::Result<()> {
let openssl = ssl_acceptor()?;
let srv = TestServer::start(move || {
pipeline_factory(
@ -77,12 +76,10 @@ fn test_h2() -> io::Result<()> {
let response = srv.sget("/").send().await.unwrap();
assert!(response.status().is_success());
Ok(())
})
}
#[test]
fn test_h2_1() -> io::Result<()> {
block_on(async {
#[actix_rt::test]
async fn test_h2_1() -> io::Result<()> {
let openssl = ssl_acceptor()?;
let srv = TestServer::start(move || {
pipeline_factory(
@ -104,12 +101,10 @@ fn test_h2_1() -> io::Result<()> {
let response = srv.sget("/").send().await.unwrap();
assert!(response.status().is_success());
Ok(())
})
}
#[test]
fn test_h2_body() -> io::Result<()> {
block_on(async {
#[actix_rt::test]
async fn test_h2_body() -> io::Result<()> {
let data = "HELLOWORLD".to_owned().repeat(64 * 1024);
let openssl = ssl_acceptor()?;
let mut srv = TestServer::start(move || {
@ -136,12 +131,10 @@ fn test_h2_body() -> io::Result<()> {
let body = srv.load_body(response).await.unwrap();
assert_eq!(&body, data.as_bytes());
Ok(())
})
}
#[test]
fn test_h2_content_length() {
block_on(async {
#[actix_rt::test]
async fn test_h2_content_length() {
let openssl = ssl_acceptor().unwrap();
let srv = TestServer::start(move || {
@ -194,12 +187,10 @@ fn test_h2_content_length() {
assert_eq!(response.headers().get(&header), Some(&value));
}
}
})
}
#[test]
fn test_h2_headers() {
block_on(async {
#[actix_rt::test]
async fn test_h2_headers() {
let data = STR.repeat(10);
let data2 = data.clone();
let openssl = ssl_acceptor().unwrap();
@ -240,7 +231,6 @@ fn test_h2_headers() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from(data2));
})
}
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";
#[test]
fn test_h2_body2() {
block_on(async {
#[actix_rt::test]
async fn test_h2_body2() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
pipeline_factory(
@ -288,12 +277,10 @@ fn test_h2_body2() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
}
#[test]
fn test_h2_head_empty() {
block_on(async {
#[actix_rt::test]
async fn test_h2_head_empty() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
pipeline_factory(
@ -320,12 +307,10 @@ fn test_h2_head_empty() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert!(bytes.is_empty());
})
}
#[test]
fn test_h2_head_binary() {
block_on(async {
#[actix_rt::test]
async fn test_h2_head_binary() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
pipeline_factory(
@ -355,12 +340,10 @@ fn test_h2_head_binary() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert!(bytes.is_empty());
})
}
#[test]
fn test_h2_head_binary2() {
block_on(async {
#[actix_rt::test]
async fn test_h2_head_binary2() {
let openssl = ssl_acceptor().unwrap();
let srv = TestServer::start(move || {
pipeline_factory(
@ -382,12 +365,10 @@ fn test_h2_head_binary2() {
let len = response.headers().get(header::CONTENT_LENGTH).unwrap();
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
}
})
}
#[test]
fn test_h2_body_length() {
block_on(async {
#[actix_rt::test]
async fn test_h2_body_length() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
pipeline_factory(
@ -414,12 +395,10 @@ fn test_h2_body_length() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
}
#[test]
fn test_h2_body_chunked_explicit() {
block_on(async {
#[actix_rt::test]
async fn test_h2_body_chunked_explicit() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
pipeline_factory(
@ -430,8 +409,7 @@ fn test_h2_body_chunked_explicit() {
.and_then(
HttpService::build()
.h2(|_| {
let body =
once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(
Response::Ok()
.header(header::TRANSFER_ENCODING, "chunked")
@ -451,12 +429,10 @@ fn test_h2_body_chunked_explicit() {
// decode
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
}
#[test]
fn test_h2_response_http_error_handling() {
block_on(async {
#[actix_rt::test]
async fn test_h2_response_http_error_handling() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
@ -487,12 +463,10 @@ fn test_h2_response_http_error_handling() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
})
}
#[test]
fn test_h2_service_error() {
block_on(async {
#[actix_rt::test]
async fn test_h2_service_error() {
let openssl = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
@ -514,12 +488,10 @@ fn test_h2_service_error() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(b"error"));
})
}
#[test]
fn test_h2_on_connect() {
block_on(async {
#[actix_rt::test]
async fn test_h2_on_connect() {
let openssl = ssl_acceptor().unwrap();
let srv = TestServer::start(move || {
@ -541,5 +513,4 @@ fn test_h2_on_connect() {
let response = srv.sget("/").send().await.unwrap();
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::{Method, StatusCode, Version};
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_config::ServerConfig;
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))
}
#[test]
fn test_h2() -> io::Result<()> {
block_on(async {
#[actix_rt::test]
async fn test_h2() -> io::Result<()> {
let rustls = ssl_acceptor()?;
let srv = TestServer::start(move || {
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();
assert!(response.status().is_success());
Ok(())
})
}
#[test]
fn test_h2_1() -> io::Result<()> {
block_on(async {
#[actix_rt::test]
async fn test_h2_1() -> io::Result<()> {
let rustls = ssl_acceptor()?;
let srv = TestServer::start(move || {
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();
assert!(response.status().is_success());
Ok(())
})
}
#[test]
fn test_h2_body1() -> io::Result<()> {
block_on(async {
#[actix_rt::test]
async fn test_h2_body1() -> io::Result<()> {
let data = "HELLOWORLD".to_owned().repeat(64 * 1024);
let rustls = ssl_acceptor()?;
let mut srv = TestServer::start(move || {
@ -112,12 +107,10 @@ fn test_h2_body1() -> io::Result<()> {
let body = srv.load_body(response).await.unwrap();
assert_eq!(&body, data.as_bytes());
Ok(())
})
}
#[test]
fn test_h2_content_length() {
block_on(async {
#[actix_rt::test]
async fn test_h2_content_length() {
let rustls = ssl_acceptor().unwrap();
let srv = TestServer::start(move || {
@ -166,12 +159,10 @@ fn test_h2_content_length() {
assert_eq!(response.headers().get(&header), Some(&value));
}
}
})
}
#[test]
fn test_h2_headers() {
block_on(async {
#[actix_rt::test]
async fn test_h2_headers() {
let data = STR.repeat(10);
let data2 = data.clone();
let rustls = ssl_acceptor().unwrap();
@ -212,7 +203,6 @@ fn test_h2_headers() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from(data2));
})
}
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";
#[test]
fn test_h2_body2() {
block_on(async {
#[actix_rt::test]
async fn test_h2_body2() {
let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -256,12 +245,10 @@ fn test_h2_body2() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
}
#[test]
fn test_h2_head_empty() {
block_on(async {
#[actix_rt::test]
async fn test_h2_head_empty() {
let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -287,12 +274,10 @@ fn test_h2_head_empty() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert!(bytes.is_empty());
})
}
#[test]
fn test_h2_head_binary() {
block_on(async {
#[actix_rt::test]
async fn test_h2_head_binary() {
let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -300,9 +285,7 @@ fn test_h2_head_binary() {
HttpService::build()
.h2(|_| {
ok::<_, ()>(
Response::Ok()
.content_length(STR.len() as u64)
.body(STR),
Response::Ok().content_length(STR.len() as u64).body(STR),
)
})
.map_err(|_| ()),
@ -323,12 +306,10 @@ fn test_h2_head_binary() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert!(bytes.is_empty());
})
}
#[test]
fn test_h2_head_binary2() {
block_on(async {
#[actix_rt::test]
async fn test_h2_head_binary2() {
let rustls = ssl_acceptor().unwrap();
let srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -349,12 +330,10 @@ fn test_h2_head_binary2() {
.unwrap();
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
}
})
}
#[test]
fn test_h2_body_length() {
block_on(async {
#[actix_rt::test]
async fn test_h2_body_length() {
let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -363,10 +342,8 @@ fn test_h2_body_length() {
.h2(|_| {
let body = once(ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(
Response::Ok().body(body::SizedStream::new(
STR.len() as u64,
body,
)),
Response::Ok()
.body(body::SizedStream::new(STR.len() as u64, body)),
)
})
.map_err(|_| ()),
@ -379,12 +356,10 @@ fn test_h2_body_length() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
}
#[test]
fn test_h2_body_chunked_explicit() {
block_on(async {
#[actix_rt::test]
async fn test_h2_body_chunked_explicit() {
let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
pipeline_factory(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
@ -412,12 +387,10 @@ fn test_h2_body_chunked_explicit() {
// decode
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
}
#[test]
fn test_h2_response_http_error_handling() {
block_on(async {
#[actix_rt::test]
async fn test_h2_response_http_error_handling() {
let rustls = ssl_acceptor().unwrap();
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");
ok::<_, ()>(
Response::Ok()
.header(
http::header::CONTENT_TYPE,
broken_header,
)
.header(http::header::CONTENT_TYPE, broken_header)
.body(STR),
)
}))
@ -447,12 +417,10 @@ fn test_h2_response_http_error_handling() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
})
}
#[test]
fn test_h2_service_error() {
block_on(async {
#[actix_rt::test]
async fn test_h2_service_error() {
let rustls = ssl_acceptor().unwrap();
let mut srv = TestServer::start(move || {
@ -470,5 +438,4 @@ fn test_h2_service_error() {
// read response
let bytes = srv.load_body(response).await.unwrap();
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::{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_service::{factory_fn_cfg, pipeline, service_fn, ServiceFactory};
use bytes::Bytes;
use futures::future::{self, err, ok, ready, FutureExt};
use futures::stream::{once, StreamExt};
use regex::Regex;
use tokio_timer::delay_for;
use actix_http::httpmessage::HttpMessage;
use actix_http::{
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
};
#[test]
fn test_h1() {
block_on(async {
#[actix_rt::test]
async fn test_h1() {
let srv = TestServer::start(|| {
HttpService::build()
.keep_alive(KeepAlive::Disabled)
@ -32,12 +31,10 @@ fn test_h1() {
let response = srv.get("/").send().await.unwrap();
assert!(response.status().is_success());
})
}
#[test]
fn test_h1_2() {
block_on(async {
#[actix_rt::test]
async fn test_h1_2() {
let srv = TestServer::start(|| {
HttpService::build()
.keep_alive(KeepAlive::Disabled)
@ -53,12 +50,10 @@ fn test_h1_2() {
let response = srv.get("/").send().await.unwrap();
assert!(response.status().is_success());
})
}
#[test]
fn test_expect_continue() {
block_on(async {
#[actix_rt::test]
async fn test_expect_continue() {
let srv = TestServer::start(|| {
HttpService::build()
.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"));
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
let _ =
stream.write_all(b"GET /test?yes= HTTP/1.1\r\nexpect: 100-continue\r\n\r\n");
let _ = stream.write_all(b"GET /test?yes= HTTP/1.1\r\nexpect: 100-continue\r\n\r\n");
let mut data = String::new();
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"));
})
}
#[test]
fn test_expect_continue_h1() {
block_on(async {
#[actix_rt::test]
async fn test_expect_continue_h1() {
let srv = TestServer::start(|| {
HttpService::build()
.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"));
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
let _ =
stream.write_all(b"GET /test?yes= HTTP/1.1\r\nexpect: 100-continue\r\n\r\n");
let _ = stream.write_all(b"GET /test?yes= HTTP/1.1\r\nexpect: 100-continue\r\n\r\n");
let mut data = String::new();
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"));
})
}
#[test]
fn test_chunked_payload() {
block_on(async {
#[actix_rt::test]
async fn test_chunked_payload() {
let chunk_sizes = vec![32768, 32, 32768];
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 size: usize = match re.captures(&data) {
Some(caps) => caps.get(1).unwrap().as_str().parse().unwrap(),
None => {
panic!(format!("Failed to find size in HTTP Response: {}", data))
}
None => panic!(format!("Failed to find size in HTTP Response: {}", data)),
};
size
};
assert_eq!(returned_size, total_size);
})
}
#[test]
fn test_slow_request() {
block_on(async {
#[actix_rt::test]
async fn test_slow_request() {
let srv = TestServer::start(|| {
HttpService::build()
.client_timeout(100)
@ -189,12 +174,10 @@ fn test_slow_request() {
let mut data = String::new();
let _ = stream.read_to_string(&mut data);
assert!(data.starts_with("HTTP/1.1 408 Request Timeout"));
})
}
#[test]
fn test_http1_malformed_request() {
block_on(async {
#[actix_rt::test]
async fn test_http1_malformed_request() {
let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
});
@ -204,12 +187,10 @@ fn test_http1_malformed_request() {
let mut data = String::new();
let _ = stream.read_to_string(&mut data);
assert!(data.starts_with("HTTP/1.1 400 Bad Request"));
})
}
#[test]
fn test_http1_keepalive() {
block_on(async {
#[actix_rt::test]
async fn test_http1_keepalive() {
let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
});
@ -224,12 +205,10 @@ fn test_http1_keepalive() {
let mut data = vec![0; 1024];
let _ = stream.read(&mut data);
assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");
})
}
#[test]
fn test_http1_keepalive_timeout() {
block_on(async {
#[actix_rt::test]
async fn test_http1_keepalive_timeout() {
let srv = TestServer::start(|| {
HttpService::build()
.keep_alive(1)
@ -246,19 +225,17 @@ fn test_http1_keepalive_timeout() {
let mut data = vec![0; 1024];
let res = stream.read(&mut data).unwrap();
assert_eq!(res, 0);
})
}
#[test]
fn test_http1_keepalive_close() {
block_on(async {
#[actix_rt::test]
async fn test_http1_keepalive_close() {
let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
});
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
let _ = stream
.write_all(b"GET /test/tests/test HTTP/1.1\r\nconnection: close\r\n\r\n");
let _ =
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 _ = stream.read(&mut data);
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 res = stream.read(&mut data).unwrap();
assert_eq!(res, 0);
})
}
#[test]
fn test_http10_keepalive_default_close() {
block_on(async {
#[actix_rt::test]
async fn test_http10_keepalive_default_close() {
let srv = TestServer::start(|| {
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 res = stream.read(&mut data).unwrap();
assert_eq!(res, 0);
})
}
#[test]
fn test_http10_keepalive() {
block_on(async {
#[actix_rt::test]
async fn test_http10_keepalive() {
let srv = TestServer::start(|| {
HttpService::build().h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
});
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
let _ = stream.write_all(
b"GET /test/tests/test HTTP/1.0\r\nconnection: keep-alive\r\n\r\n",
);
let _ = stream
.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 _ = stream.read(&mut data);
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 res = stream.read(&mut data).unwrap();
assert_eq!(res, 0);
})
}
#[test]
fn test_http1_keepalive_disabled() {
block_on(async {
#[actix_rt::test]
async fn test_http1_keepalive_disabled() {
let srv = TestServer::start(|| {
HttpService::build()
.keep_alive(KeepAlive::Disabled)
@ -333,12 +303,10 @@ fn test_http1_keepalive_disabled() {
let mut data = vec![0; 1024];
let res = stream.read(&mut data).unwrap();
assert_eq!(res, 0);
})
}
#[test]
fn test_content_length() {
block_on(async {
#[actix_rt::test]
async fn test_content_length() {
use actix_http::http::{
header::{HeaderName, HeaderValue},
StatusCode,
@ -379,12 +347,10 @@ fn test_content_length() {
assert_eq!(response.headers().get(&header), Some(&value));
}
}
})
}
#[test]
fn test_h1_headers() {
block_on(async {
#[actix_rt::test]
async fn test_h1_headers() {
let data = STR.repeat(10);
let data2 = data.clone();
@ -420,7 +386,6 @@ fn test_h1_headers() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from(data2));
})
}
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";
#[test]
fn test_h1_body() {
block_on(async {
#[actix_rt::test]
async fn test_h1_body() {
let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
});
@ -458,12 +422,10 @@ fn test_h1_body() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
}
#[test]
fn test_h1_head_empty() {
block_on(async {
#[actix_rt::test]
async fn test_h1_head_empty() {
let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
});
@ -482,12 +444,10 @@ fn test_h1_head_empty() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert!(bytes.is_empty());
})
}
#[test]
fn test_h1_head_binary() {
block_on(async {
#[actix_rt::test]
async fn test_h1_head_binary() {
let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| {
ok::<_, ()>(Response::Ok().content_length(STR.len() as u64).body(STR))
@ -508,12 +468,10 @@ fn test_h1_head_binary() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert!(bytes.is_empty());
})
}
#[test]
fn test_h1_head_binary2() {
block_on(async {
#[actix_rt::test]
async fn test_h1_head_binary2() {
let srv = TestServer::start(|| {
HttpService::build().h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
});
@ -528,12 +486,10 @@ fn test_h1_head_binary2() {
.unwrap();
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
}
})
}
#[test]
fn test_h1_body_length() {
block_on(async {
#[actix_rt::test]
async fn test_h1_body_length() {
let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| {
let body = once(ok(Bytes::from_static(STR.as_ref())));
@ -549,12 +505,10 @@ fn test_h1_body_length() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
}
#[test]
fn test_h1_body_chunked_explicit() {
block_on(async {
#[actix_rt::test]
async fn test_h1_body_chunked_explicit() {
let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
@ -583,12 +537,10 @@ fn test_h1_body_chunked_explicit() {
// decode
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
}
#[test]
fn test_h1_body_chunked_implicit() {
block_on(async {
#[actix_rt::test]
async fn test_h1_body_chunked_implicit() {
let mut srv = TestServer::start(|| {
HttpService::build().h1(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
@ -611,12 +563,10 @@ fn test_h1_body_chunked_implicit() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
}
#[test]
fn test_h1_response_http_error_handling() {
block_on(async {
#[actix_rt::test]
async fn test_h1_response_http_error_handling() {
let mut srv = TestServer::start(|| {
HttpService::build().h1(factory_fn_cfg(|_: &ServerConfig| {
ok::<_, ()>(pipeline(|_| {
@ -636,12 +586,10 @@ fn test_h1_response_http_error_handling() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
})
}
#[test]
fn test_h1_service_error() {
block_on(async {
#[actix_rt::test]
async fn test_h1_service_error() {
let mut srv = TestServer::start(|| {
HttpService::build()
.h1(|_| future::err::<Response, Error>(error::ErrorBadRequest("error")))
@ -653,12 +601,10 @@ fn test_h1_service_error() {
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(b"error"));
})
}
#[test]
fn test_h1_on_connect() {
block_on(async {
#[actix_rt::test]
async fn test_h1_on_connect() {
let srv = TestServer::start(|| {
HttpService::build()
.on_connect(|_| 10usize)
@ -670,5 +616,4 @@ fn test_h1_on_connect() {
let response = srv.get("/").send().await.unwrap();
assert!(response.status().is_success());
})
}

View File

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

View File

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

View File

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

View File

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

View File

@ -17,6 +17,7 @@ syn = { version = "^1", features = ["full", "parsing"] }
proc-macro2 = "^1"
[dev-dependencies]
actix-rt = { version = "1.0.0-alpha.1" }
actix-web = { version = "2.0.0-alpha.1" }
actix-http = { 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_test::{block_on, TestServer};
use actix_http_test::TestServer;
use actix_web::{http, web::Path, App, HttpResponse, Responder};
use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, trace};
use futures::{future, Future};
@ -69,9 +69,8 @@ async fn get_param_test(_: Path<String>) -> impl Responder {
HttpResponse::Ok()
}
#[test]
fn test_params() {
block_on(async {
#[actix_rt::test]
async fn test_params() {
let srv = TestServer::start(|| {
HttpService::new(
App::new()
@ -92,12 +91,10 @@ fn test_params() {
let request = srv.request(http::Method::DELETE, srv.url("/test/it"));
let response = request.send().await.unwrap();
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
})
}
#[test]
fn test_body() {
block_on(async {
#[actix_rt::test]
async fn test_body() {
let srv = TestServer::start(|| {
HttpService::new(
App::new()
@ -148,16 +145,13 @@ fn test_body() {
let request = srv.request(http::Method::GET, srv.url("/test"));
let response = request.send().await.unwrap();
assert!(response.status().is_success());
})
}
#[test]
fn test_auto_async() {
block_on(async {
#[actix_rt::test]
async fn test_auto_async() {
let srv = TestServer::start(|| HttpService::new(App::new().service(auto_async)));
let request = srv.request(http::Method::GET, srv.url("/test"));
let response = request.send().await.unwrap();
assert!(response.status().is_success());
})
}

View File

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

View File

@ -6,19 +6,16 @@
//! use actix_rt::System;
//! use awc::Client;
//!
//! fn main() {
//! System::new("test").block_on(async {
//! #[actix_rt::main]
//! async fn main() {
//! 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")
//! .send() // <- Send http request
//! .await
//! .and_then(|response| { // <- server http response
//! .await;
//!
//! println!("Response: {:?}", response);
//! Ok(())
//! })
//! });
//! }
//! ```
use std::cell::RefCell;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,7 +2,7 @@ use std::io;
use actix_codec::Framed;
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 futures::future::ok;
use futures::{SinkExt, StreamExt};
@ -28,9 +28,8 @@ async fn ws_service(req: ws::Frame) -> Result<ws::Message, io::Error> {
}
}
#[test]
fn test_simple() {
block_on(async {
#[actix_rt::test]
async fn test_simple() {
let mut srv = TestServer::start(|| {
HttpService::build()
.upgrade(|(req, mut framed): (Request, Framed<_, _>)| {
@ -79,5 +78,4 @@ fn test_simple() {
let item = framed.next().await.unwrap().unwrap();
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::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use actix_http::body::{Body, MessageBody};
use actix_service::boxed::{self, BoxedNewService};
use actix_service::boxed::{self, BoxServiceFactory};
use actix_service::{
apply, apply_fn_factory, IntoServiceFactory, ServiceFactory, Transform,
};
@ -25,7 +23,7 @@ use crate::service::{
ServiceResponse,
};
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
type FnDataFactory =
Box<dyn Fn() -> LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>;
@ -485,18 +483,17 @@ where
mod tests {
use actix_service::Service;
use bytes::Bytes;
use futures::future::{ok, Future};
use futures::future::ok;
use super::*;
use crate::http::{header, HeaderValue, Method, StatusCode};
use crate::middleware::DefaultHeaders;
use crate::service::{ServiceRequest, ServiceResponse};
use crate::test::{block_on, call_service, init_service, read_body, TestRequest};
use crate::{web, Error, HttpRequest, HttpResponse};
use crate::service::ServiceRequest;
use crate::test::{call_service, init_service, read_body, TestRequest};
use crate::{web, HttpRequest, HttpResponse};
#[test]
fn test_default_resource() {
block_on(async {
#[actix_rt::test]
async fn test_default_resource() {
let mut srv = init_service(
App::new().service(web::resource("/test").to(|| HttpResponse::Ok())),
)
@ -538,12 +535,10 @@ mod tests {
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
})
}
#[test]
fn test_data_factory() {
block_on(async {
#[actix_rt::test]
async fn test_data_factory() {
let mut srv =
init_service(App::new().data_factory(|| ok::<_, ()>(10usize)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
@ -561,39 +556,16 @@ mod tests {
let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
})
}
fn md<S, B>(
req: ServiceRequest,
srv: &mut S,
) -> 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(
#[actix_rt::test]
async fn test_wrap() {
let mut srv = init_service(
App::new()
.wrap(DefaultHeaders::new().header(
header::CONTENT_TYPE,
HeaderValue::from_static("0001"),
))
.wrap(
DefaultHeaders::new()
.header(header::CONTENT_TYPE, HeaderValue::from_static("0001")),
)
.route("/test", web::get().to(|| HttpResponse::Ok())),
)
.await;
@ -604,20 +576,17 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
})
}
#[test]
fn test_router_wrap() {
block_on(async {
let mut srv =
init_service(
#[actix_rt::test]
async fn test_router_wrap() {
let mut srv = init_service(
App::new()
.route("/test", web::get().to(|| HttpResponse::Ok()))
.wrap(DefaultHeaders::new().header(
header::CONTENT_TYPE,
HeaderValue::from_static("0001"),
)),
.wrap(
DefaultHeaders::new()
.header(header::CONTENT_TYPE, HeaderValue::from_static("0001")),
),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
@ -627,12 +596,10 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
})
}
#[test]
fn test_wrap_fn() {
block_on(async {
#[actix_rt::test]
async fn test_wrap_fn() {
let mut srv = init_service(
App::new()
.wrap_fn(|req, srv| {
@ -656,12 +623,10 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
})
}
#[test]
fn test_router_wrap_fn() {
block_on(async {
#[actix_rt::test]
async fn test_router_wrap_fn() {
let mut srv = init_service(
App::new()
.route("/test", web::get().to(|| HttpResponse::Ok()))
@ -685,12 +650,10 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
})
}
#[test]
fn test_external_resource() {
block_on(async {
#[actix_rt::test]
async fn test_external_resource() {
let mut srv = init_service(
App::new()
.external_resource("youtube", "https://youtube.com/watch/{video_id}")
@ -710,6 +673,5 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp).await;
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_router::{Path, ResourceDef, ResourceInfo, Router, Url};
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 futures::future::{ok, Either, FutureExt, LocalBoxFuture, Ready};
use futures::future::{ok, FutureExt, LocalBoxFuture};
use crate::config::{AppConfig, AppService};
use crate::data::DataFactory;
@ -21,9 +21,9 @@ use crate::rmap::ResourceMap;
use crate::service::{AppServiceFactory, ServiceRequest, ServiceResponse};
type Guards = Vec<Box<dyn Guard>>;
type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
type BoxedResponse = LocalBoxFuture<'static, Result<ServiceResponse, Error>>;
type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
type BoxResponse = LocalBoxFuture<'static, Result<ServiceResponse, Error>>;
type FnDataFactory =
Box<dyn Fn() -> LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>;
@ -387,7 +387,7 @@ impl Service for AppRouting {
type Request = ServiceRequest;
type Response = ServiceResponse;
type Error = Error;
type Future = BoxedResponse;
type Future = BoxResponse;
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> {
if self.ready.is_none() {
@ -447,13 +447,12 @@ impl ServiceFactory for AppEntry {
#[cfg(test)]
mod tests {
use actix_service::Service;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::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>);
@ -463,19 +462,20 @@ mod tests {
}
}
#[test]
fn drop_data() {
#[actix_rt::test]
async fn test_drop_data() {
let data = Arc::new(AtomicBool::new(false));
test::block_on(async {
let mut app = test::init_service(
{
let mut app = init_service(
App::new()
.data(DropData(data.clone()))
.service(web::resource("/test").to(|| HttpResponse::Ok())),
)
.await;
let req = test::TestRequest::with_uri("/test").to_request();
let req = TestRequest::with_uri("/test").to_request();
let _ = app.call(req).await.unwrap();
});
}
assert!(data.load(Ordering::Relaxed));
}
}

View File

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

View File

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

View File

@ -270,7 +270,7 @@ mod tests {
use serde_derive::Deserialize;
use super::*;
use crate::test::{block_on, TestRequest};
use crate::test::TestRequest;
use crate::types::{Form, FormConfig};
#[derive(Deserialize, Debug, PartialEq)]
@ -278,8 +278,8 @@ mod tests {
hello: String,
}
#[test]
fn test_option() {
#[actix_rt::test]
async fn test_option() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
@ -287,7 +287,9 @@ mod tests {
.data(FormConfig::default().limit(4096))
.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);
let (req, mut pl) = TestRequest::with_header(
@ -298,7 +300,9 @@ mod tests {
.set_payload(Bytes::from_static(b"hello=world"))
.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,
Some(Form(Info {
@ -314,12 +318,14 @@ mod tests {
.set_payload(Bytes::from_static(b"bye=world"))
.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);
}
#[test]
fn test_result() {
#[actix_rt::test]
async fn test_result() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
@ -328,7 +334,8 @@ mod tests {
.set_payload(Bytes::from_static(b"hello=world"))
.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();
assert_eq!(
@ -346,8 +353,9 @@ mod tests {
.set_payload(Bytes::from_static(b"bye=world"))
.to_http_parts();
let r =
block_on(Result::<Form<Info>, Error>::from_request(&req, &mut pl)).unwrap();
let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl)
.await
.unwrap();
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
//! for Rust.
//!
@ -143,9 +143,9 @@ pub mod dev {
HttpServiceFactory, ServiceRequest, ServiceResponse, WebService,
};
//pub use crate::types::form::UrlEncoded;
//pub use crate::types::json::JsonBody;
//pub use crate::types::readlines::Readlines;
pub use crate::types::form::UrlEncoded;
pub use crate::types::json::JsonBody;
pub use crate::types::readlines::Readlines;
pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody, SizedStream};
pub use actix_http::encoding::Decoder as Decompress;
@ -174,8 +174,8 @@ pub mod client {
//! use actix_rt::System;
//! use actix_web::client::Client;
//!
//! fn main() {
//! System::new("test").block_on(async {
//! #[actix_rt::main]
//! async fn main() {
//! let mut client = Client::default();
//!
//! // Create request builder and send request
@ -184,7 +184,6 @@ pub mod client {
//! .send().await; // <- Send http request
//!
//! println!("Response: {:?}", response);
//! });
//! }
//! ```
pub use awc::error::{

View File

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

View File

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

View File

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

View File

@ -479,10 +479,10 @@ mod tests {
use super::*;
use crate::http::{header, StatusCode};
use crate::test::{block_on, TestRequest};
use crate::test::TestRequest;
#[test]
fn test_logger() {
#[actix_rt::test]
async fn test_logger() {
let srv = |req: ServiceRequest| {
ok(req.into_response(
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 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(
header::USER_AGENT,
header::HeaderValue::from_static("ACTIX-WEB"),
)
.to_srv_request();
let _res = block_on(srv.call(req));
let _res = srv.call(req).await;
}
#[test]
fn test_url_path() {
#[actix_rt::test]
async fn test_url_path() {
let mut format = Format::new("%T %U");
let req = TestRequest::with_header(
header::USER_AGENT,
@ -533,8 +533,8 @@ mod tests {
assert!(s.contains("/test/route/yeah"));
}
#[test]
fn test_default_format() {
#[actix_rt::test]
async fn test_default_format() {
let mut format = Format::default();
let req = TestRequest::with_header(
@ -566,8 +566,8 @@ mod tests {
assert!(s.contains("ACTIX-WEB"));
}
#[test]
fn test_request_time_format() {
#[actix_rt::test]
async fn test_request_time_format() {
let mut format = Format::new("%t");
let req = TestRequest::default().to_srv_request();

View File

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

View File

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

View File

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

View File

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

View File

@ -5,7 +5,7 @@ use std::task::{Context, Poll};
use actix_http::{http::Method, Error};
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::guard::{self, Guard};
@ -342,23 +342,21 @@ where
mod tests {
use std::time::Duration;
use actix_rt::time::delay_for;
use bytes::Bytes;
use futures::Future;
use serde_derive::Serialize;
use tokio_timer::delay_for;
use crate::http::{Method, StatusCode};
use crate::test::{block_on, call_service, init_service, read_body, TestRequest};
use crate::{error, web, App, Error, HttpResponse};
use crate::test::{call_service, init_service, read_body, TestRequest};
use crate::{error, web, App, HttpResponse};
#[derive(Serialize, PartialEq, Debug)]
struct MyObject {
name: String,
}
#[test]
fn test_route() {
block_on(async {
#[actix_rt::test]
async fn test_route() {
let mut srv = init_service(
App::new()
.service(
@ -429,6 +427,5 @@ mod tests {
let body = read_body(resp).await;
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_router::{ResourceDef, ResourceInfo, Router};
use actix_service::boxed::{self, BoxedNewService, BoxedService};
use actix_service::boxed::{self, BoxService, BoxServiceFactory};
use actix_service::{
apply, apply_fn_factory, IntoServiceFactory, Service, ServiceFactory, Transform,
};
@ -25,8 +25,8 @@ use crate::service::{
};
type Guards = Vec<Box<dyn Guard>>;
type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
type BoxedResponse = LocalBoxFuture<'static, Result<ServiceResponse, Error>>;
/// Resources scope.
@ -666,18 +666,16 @@ mod tests {
use actix_service::Service;
use bytes::Bytes;
use futures::future::ok;
use futures::Future;
use crate::dev::{Body, ResponseBody};
use crate::http::{header, HeaderValue, Method, StatusCode};
use crate::middleware::DefaultHeaders;
use crate::service::{ServiceRequest, ServiceResponse};
use crate::test::{block_on, call_service, init_service, read_body, TestRequest};
use crate::{guard, web, App, Error, HttpRequest, HttpResponse};
use crate::service::ServiceRequest;
use crate::test::{call_service, init_service, read_body, TestRequest};
use crate::{guard, web, App, HttpRequest, HttpResponse};
#[test]
fn test_scope() {
block_on(async {
#[actix_rt::test]
async fn test_scope() {
let mut srv = init_service(
App::new().service(
web::scope("/app")
@ -689,12 +687,10 @@ mod tests {
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
})
}
#[test]
fn test_scope_root() {
block_on(async {
#[actix_rt::test]
async fn test_scope_root() {
let mut srv = init_service(
App::new().service(
web::scope("/app")
@ -711,12 +707,10 @@ mod tests {
let req = TestRequest::with_uri("/app/").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
})
}
#[test]
fn test_scope_root2() {
block_on(async {
#[actix_rt::test]
async fn test_scope_root2() {
let mut srv = init_service(App::new().service(
web::scope("/app/").service(web::resource("").to(|| HttpResponse::Ok())),
))
@ -729,18 +723,13 @@ mod tests {
let req = TestRequest::with_uri("/app/").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
})
}
#[test]
fn test_scope_root3() {
block_on(async {
let mut srv = init_service(
App::new().service(
web::scope("/app/")
.service(web::resource("/").to(|| HttpResponse::Ok())),
),
)
#[actix_rt::test]
async fn test_scope_root3() {
let mut srv = init_service(App::new().service(
web::scope("/app/").service(web::resource("/").to(|| HttpResponse::Ok())),
))
.await;
let req = TestRequest::with_uri("/app").to_request();
@ -750,12 +739,10 @@ mod tests {
let req = TestRequest::with_uri("/app/").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
})
}
#[test]
fn test_scope_route() {
block_on(async {
#[actix_rt::test]
async fn test_scope_route() {
let mut srv = init_service(
App::new().service(
web::scope("app")
@ -780,12 +767,10 @@ mod tests {
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
})
}
#[test]
fn test_scope_route_without_leading_slash() {
block_on(async {
#[actix_rt::test]
async fn test_scope_route_without_leading_slash() {
let mut srv = init_service(
App::new().service(
web::scope("app").service(
@ -812,12 +797,10 @@ mod tests {
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
})
}
#[test]
fn test_scope_guard() {
block_on(async {
#[actix_rt::test]
async fn test_scope_guard() {
let mut srv = init_service(
App::new().service(
web::scope("/app")
@ -838,12 +821,10 @@ mod tests {
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
})
}
#[test]
fn test_scope_variable_segment() {
block_on(async {
#[actix_rt::test]
async fn test_scope_variable_segment() {
let mut srv =
init_service(App::new().service(web::scope("/ab-{project}").service(
web::resource("/path1").to(|r: HttpRequest| {
@ -870,46 +851,44 @@ mod tests {
let req = TestRequest::with_uri("/aa-project1/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
})
}
#[test]
fn test_nested_scope() {
block_on(async {
let mut srv =
init_service(App::new().service(
web::scope("/app").service(web::scope("/t1").service(
#[actix_rt::test]
async fn test_nested_scope() {
let mut srv = init_service(
App::new().service(
web::scope("/app")
.service(web::scope("/t1").service(
web::resource("/path1").to(|| HttpResponse::Created()),
)),
))
),
)
.await;
let req = TestRequest::with_uri("/app/t1/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
})
}
#[test]
fn test_nested_scope_no_slash() {
block_on(async {
let mut srv =
init_service(App::new().service(
web::scope("/app").service(web::scope("t1").service(
#[actix_rt::test]
async fn test_nested_scope_no_slash() {
let mut srv = init_service(
App::new().service(
web::scope("/app")
.service(web::scope("t1").service(
web::resource("/path1").to(|| HttpResponse::Created()),
)),
))
),
)
.await;
let req = TestRequest::with_uri("/app/t1/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
})
}
#[test]
fn test_nested_scope_root() {
block_on(async {
#[actix_rt::test]
async fn test_nested_scope_root() {
let mut srv = init_service(
App::new().service(
web::scope("/app").service(
@ -928,12 +907,10 @@ mod tests {
let req = TestRequest::with_uri("/app/t1/").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
})
}
#[test]
fn test_nested_scope_filter() {
block_on(async {
#[actix_rt::test]
async fn test_nested_scope_filter() {
let mut srv = init_service(
App::new().service(
web::scope("/app").service(
@ -956,20 +933,16 @@ mod tests {
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
})
}
#[test]
fn test_nested_scope_with_variable_segment() {
block_on(async {
#[actix_rt::test]
async fn test_nested_scope_with_variable_segment() {
let mut srv = init_service(App::new().service(web::scope("/app").service(
web::scope("/{project_id}").service(web::resource("/path1").to(
|r: HttpRequest| {
async move {
HttpResponse::Created().body(format!(
"project: {}",
&r.match_info()["project_id"]
))
HttpResponse::Created()
.body(format!("project: {}", &r.match_info()["project_id"]))
}
},
)),
@ -987,12 +960,10 @@ mod tests {
}
_ => panic!(),
}
})
}
#[test]
fn test_nested2_scope_with_variable_segment() {
block_on(async {
#[actix_rt::test]
async fn test_nested2_scope_with_variable_segment() {
let mut srv = init_service(App::new().service(web::scope("/app").service(
web::scope("/{project}").service(web::scope("/{id}").service(
web::resource("/path1").to(|r: HttpRequest| {
@ -1023,12 +994,10 @@ mod tests {
let req = TestRequest::with_uri("/app/test/1/path2").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
})
}
#[test]
fn test_default_resource() {
block_on(async {
#[actix_rt::test]
async fn test_default_resource() {
let mut srv = init_service(
App::new().service(
web::scope("/app")
@ -1047,12 +1016,10 @@ mod tests {
let req = TestRequest::with_uri("/path2").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
})
}
#[test]
fn test_default_resource_propagation() {
block_on(async {
#[actix_rt::test]
async fn test_default_resource_propagation() {
let mut srv = init_service(
App::new()
.service(web::scope("/app1").default_service(
@ -1076,33 +1043,12 @@ mod tests {
let req = TestRequest::with_uri("/app2/non-exist").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
})
}
fn md<S, B>(
req: ServiceRequest,
srv: &mut S,
) -> 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_middleware() {
block_on(async {
let mut srv = init_service(
#[actix_rt::test]
async fn test_middleware() {
let mut srv =
init_service(
App::new().service(
web::scope("app")
.wrap(DefaultHeaders::new().header(
@ -1124,12 +1070,10 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
})
}
#[test]
fn test_middleware_fn() {
block_on(async {
#[actix_rt::test]
async fn test_middleware_fn() {
let mut srv = init_service(
App::new().service(
web::scope("app")
@ -1156,12 +1100,10 @@ mod tests {
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
})
}
#[test]
fn test_override_data() {
block_on(async {
#[actix_rt::test]
async fn test_override_data() {
let mut srv = init_service(App::new().data(1usize).service(
web::scope("app").data(10usize).route(
"/t",
@ -1177,12 +1119,10 @@ mod tests {
let req = TestRequest::with_uri("/app/t").to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
})
}
#[test]
fn test_override_register_data() {
block_on(async {
#[actix_rt::test]
async fn test_override_register_data() {
let mut srv = init_service(
App::new().register_data(web::Data::new(1usize)).service(
web::scope("app")
@ -1202,12 +1142,10 @@ mod tests {
let req = TestRequest::with_uri("/app/t").to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
})
}
#[test]
fn test_scope_config() {
block_on(async {
#[actix_rt::test]
async fn test_scope_config() {
let mut srv =
init_service(App::new().service(web::scope("/app").configure(|s| {
s.route("/path1", web::get().to(|| HttpResponse::Ok()));
@ -1217,12 +1155,10 @@ mod tests {
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
})
}
#[test]
fn test_scope_config_2() {
block_on(async {
#[actix_rt::test]
async fn test_scope_config_2() {
let mut srv =
init_service(App::new().service(web::scope("/app").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 resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
})
}
#[test]
fn test_url_for_external() {
block_on(async {
#[actix_rt::test]
async fn test_url_for_external() {
let mut srv =
init_service(App::new().service(web::scope("/app").configure(|s| {
s.service(web::scope("/v1").configure(|s| {
@ -1269,20 +1203,16 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp).await;
assert_eq!(body, &b"https://youtube.com/watch/xxxxxx"[..]);
})
}
#[test]
fn test_url_for_nested() {
block_on(async {
#[actix_rt::test]
async fn test_url_for_nested() {
let mut srv = init_service(App::new().service(web::scope("/a").service(
web::scope("/b").service(web::resource("/c/{stuff}").name("c").route(
web::get().to(|req: HttpRequest| {
async move {
HttpResponse::Ok().body(format!(
"{}",
req.url_for("c", &["12345"]).unwrap()
))
HttpResponse::Ok()
.body(format!("{}", req.url_for("c", &["12345"]).unwrap()))
}
}),
)),
@ -1297,6 +1227,5 @@ mod tests {
body,
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_service::{IntoServiceFactory, ServiceFactory};
use futures::future::{ok, Ready};
use crate::config::{AppConfig, AppService};
use crate::data::Data;
@ -529,9 +528,10 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::test::{block_on, init_service, TestRequest};
use crate::test::{init_service, TestRequest};
use crate::{guard, http, web, App, HttpResponse};
use actix_service::Service;
use futures::future::ok;
#[test]
fn test_service_request() {
@ -554,14 +554,11 @@ mod tests {
assert!(ServiceRequest::from_request(r).is_err());
}
#[test]
fn test_service() {
block_on(async {
#[actix_rt::test]
async fn test_service() {
let mut srv = init_service(
App::new().service(web::service("/test").name("test").finish(
|req: ServiceRequest| {
ok(req.into_response(HttpResponse::Ok().finish()))
},
|req: ServiceRequest| ok(req.into_response(HttpResponse::Ok().finish())),
)),
)
.await;
@ -569,20 +566,17 @@ mod tests {
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::OK);
let mut srv = init_service(App::new().service(
web::service("/test").guard(guard::Get()).finish(
|req: ServiceRequest| {
ok(req.into_response(HttpResponse::Ok().finish()))
},
),
))
let mut srv = init_service(
App::new().service(web::service("/test").guard(guard::Get()).finish(
|req: ServiceRequest| ok(req.into_response(HttpResponse::Ok().finish())),
)),
)
.await;
let req = TestRequest::with_uri("/test")
.method(http::Method::PUT)
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
})
}
#[test]

View File

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

View File

@ -10,7 +10,7 @@ use actix_http::{Error, HttpMessage, Payload, Response};
use bytes::BytesMut;
use encoding_rs::{Encoding, UTF_8};
use futures::future::{err, ok, FutureExt, LocalBoxFuture, Ready};
use futures::{Stream, StreamExt};
use futures::StreamExt;
use serde::de::DeserializeOwned;
use serde::Serialize;
@ -370,7 +370,7 @@ mod tests {
use super::*;
use crate::http::header::{HeaderValue, CONTENT_TYPE};
use crate::test::{block_on, TestRequest};
use crate::test::TestRequest;
#[derive(Deserialize, Serialize, Debug, PartialEq)]
struct Info {
@ -378,13 +378,10 @@ mod tests {
counter: i64,
}
#[test]
fn test_form() {
block_on(async {
let (req, mut pl) = TestRequest::with_header(
CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
#[actix_rt::test]
async fn test_form() {
let (req, mut pl) =
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts();
@ -397,7 +394,6 @@ mod tests {
counter: 123
}
);
})
}
fn eq(err: UrlencodedError, other: UrlencodedError) -> bool {
@ -418,22 +414,17 @@ mod tests {
}
}
#[test]
fn test_urlencoded_error() {
block_on(async {
let (req, mut pl) = TestRequest::with_header(
CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
#[actix_rt::test]
async fn test_urlencoded_error() {
let (req, mut pl) =
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(CONTENT_LENGTH, "xxxx")
.to_http_parts();
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
assert!(eq(info.err().unwrap(), UrlencodedError::UnknownLength));
let (req, mut pl) = TestRequest::with_header(
CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
let (req, mut pl) =
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(CONTENT_LENGTH, "1000000")
.to_http_parts();
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
@ -447,16 +438,12 @@ mod tests {
.to_http_parts();
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
assert!(eq(info.err().unwrap(), UrlencodedError::ContentType));
})
}
#[test]
fn test_urlencoded() {
block_on(async {
let (req, mut pl) = TestRequest::with_header(
CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
#[actix_rt::test]
async fn test_urlencoded() {
let (req, mut pl) =
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
.to_http_parts();
@ -486,12 +473,10 @@ mod tests {
counter: 123
}
);
})
}
#[test]
fn test_responder() {
block_on(async {
#[actix_rt::test]
async fn test_responder() {
let req = TestRequest::default().to_http_request();
let form = Form(Info {
@ -507,6 +492,5 @@ mod tests {
use crate::responder::tests::BodyTest;
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 futures::future::{err, ok, FutureExt, LocalBoxFuture, Ready};
use futures::{Stream, StreamExt};
use futures::StreamExt;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json;
@ -402,7 +402,7 @@ mod tests {
use super::*;
use crate::error::InternalError;
use crate::http::header;
use crate::test::{block_on, load_stream, TestRequest};
use crate::test::{load_stream, TestRequest};
use crate::HttpResponse;
#[derive(Serialize, Deserialize, PartialEq, Debug)]
@ -424,9 +424,8 @@ mod tests {
}
}
#[test]
fn test_responder() {
block_on(async {
#[actix_rt::test]
async fn test_responder() {
let req = TestRequest::default().to_http_request();
let j = Json(MyObject {
@ -441,12 +440,10 @@ mod tests {
use crate::responder::tests::BodyTest;
assert_eq!(resp.body().bin_ref(), b"{\"name\":\"test\"}");
})
}
#[test]
fn test_custom_error_responder() {
block_on(async {
#[actix_rt::test]
async fn test_custom_error_responder() {
let (req, mut pl) = TestRequest::default()
.header(
header::CONTENT_TYPE,
@ -474,12 +471,10 @@ mod tests {
let body = load_stream(resp.take_body()).await.unwrap();
let msg: MyObject = serde_json::from_slice(&body).unwrap();
assert_eq!(msg.name, "invalid request");
})
}
#[test]
fn test_extract() {
block_on(async {
#[actix_rt::test]
async fn test_extract() {
let (req, mut pl) = TestRequest::default()
.header(
header::CONTENT_TYPE,
@ -536,12 +531,10 @@ mod tests {
.to_http_parts();
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
assert!(format!("{}", s.err().unwrap()).contains("Content type error"));
})
}
#[test]
fn test_json_body() {
block_on(async {
#[actix_rt::test]
async fn test_json_body() {
let (req, mut pl) = TestRequest::default().to_http_parts();
let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
@ -590,12 +583,10 @@ mod tests {
name: "test".to_owned()
}
);
})
}
#[test]
fn test_with_json_and_bad_content_type() {
block_on(async {
#[actix_rt::test]
async fn test_with_json_and_bad_content_type() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain"),
@ -610,12 +601,10 @@ mod tests {
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
assert!(s.is_err())
})
}
#[test]
fn test_with_json_and_good_custom_content_type() {
block_on(async {
#[actix_rt::test]
async fn test_with_json_and_good_custom_content_type() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain"),
@ -632,12 +621,10 @@ mod tests {
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
assert!(s.is_ok())
})
}
#[test]
fn test_with_json_and_bad_custom_content_type() {
block_on(async {
#[actix_rt::test]
async fn test_with_json_and_bad_custom_content_type() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/html"),
@ -654,6 +641,5 @@ mod tests {
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
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::payload::{Payload, PayloadConfig};
pub use self::query::{Query, QueryConfig};
pub use self::readlines::Readlines;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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