1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-27 17:22:57 +01:00

update awc tests

This commit is contained in:
Nikolay Kim 2019-11-21 00:35:07 +06:00
parent 3127dd4db6
commit b510527a9f
9 changed files with 404 additions and 383 deletions

View File

@ -14,7 +14,7 @@ categories = ["network-programming", "asynchronous",
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
# workspace = ".."
workspace = ".."
[lib]
name = "awc"
@ -59,7 +59,7 @@ 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 }
rust-tls = { version = "0.16.0", package="rustls", optional = true, features = ["dangerous_configuration"] }
[dev-dependencies]
actix-rt = "1.0.0-alpha.1"
@ -67,11 +67,10 @@ actix-web = { version = "2.0.0-alpha.1", features=["openssl"] }
actix-http = { version = "0.3.0-alpha.1", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] }
actix-utils = "0.5.0-alpha.1"
actix-server = { version = "0.8.0-alpha.1", features=["openssl", "rustls"] }
actix-server = { version = "0.8.0-alpha.1", features=["openssl"] }
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" }
rus-tls = { version = "0.16.0", package="rustls", features = ["dangerous_configuration"] }

View File

@ -7,18 +7,18 @@
//! use awc::Client;
//!
//! fn main() {
//! System::new("test").block_on(lazy(|| {
//! System::new("test").block_on(async {
//! let mut client = Client::default();
//!
//! client.get("http://www.rust-lang.org") // <- Create request builder
//! .header("User-Agent", "Actix-web")
//! .send() // <- Send http request
//! .map_err(|_| ())
//! .await
//! .and_then(|response| { // <- server http response
//! println!("Response: {:?}", response);
//! Ok(())
//! })
//! }));
//! });
//! }
//! ```
use std::cell::RefCell;
@ -57,18 +57,18 @@ use self::connect::{Connect, ConnectorWrapper};
/// use awc::Client;
///
/// fn main() {
/// System::new("test").block_on(lazy(|| {
/// System::new("test").block_on(async {
/// let mut client = Client::default();
///
/// client.get("http://www.rust-lang.org") // <- Create request builder
/// .header("User-Agent", "Actix-web")
/// .send() // <- Send http request
/// .map_err(|_| ())
/// .await
/// .and_then(|response| { // <- server http response
/// println!("Response: {:?}", response);
/// Ok(())
/// })
/// }));
/// });
/// }
/// ```
#[derive(Clone)]

View File

@ -41,17 +41,18 @@ const HTTPS_ENCODING: &str = "gzip, deflate";
/// use actix_rt::System;
///
/// fn main() {
/// System::new("test").block_on(lazy(|| {
/// awc::Client::new()
/// System::new("test").block_on(async {
/// let response = awc::Client::new()
/// .get("http://www.rust-lang.org") // <- Create request builder
/// .header("User-Agent", "Actix-web")
/// .send() // <- Send http request
/// .map_err(|_| ())
/// .and_then(|response| { // <- server http response
/// .await;
///
/// response.and_then(|response| { // <- server http response
/// println!("Response: {:?}", response);
/// Ok(())
/// })
/// }));
/// });
/// }
/// ```
pub struct ClientRequest {
@ -158,7 +159,7 @@ impl ClientRequest {
///
/// ```rust
/// fn main() {
/// # actix_rt::System::new("test").block_on(futures::future::lazy(|| {
/// # actix_rt::System::new("test").block_on(futures::future::lazy(|_| {
/// let req = awc::Client::new()
/// .get("http://www.rust-lang.org")
/// .set(awc::http::header::Date::now())
@ -186,13 +187,13 @@ impl ClientRequest {
/// use awc::{http, Client};
///
/// fn main() {
/// # actix_rt::System::new("test").block_on(futures::future::lazy(|| {
/// # actix_rt::System::new("test").block_on(async {
/// let req = Client::new()
/// .get("http://www.rust-lang.org")
/// .header("X-TEST", "value")
/// .header(http::header::CONTENT_TYPE, "application/json");
/// # Ok::<_, ()>(())
/// # }));
/// # });
/// }
/// ```
pub fn header<K, V>(mut self, key: K, value: V) -> Self
@ -311,7 +312,7 @@ impl ClientRequest {
/// # use actix_rt::System;
/// # use futures::future::{lazy, Future};
/// fn main() {
/// System::new("test").block_on(lazy(|| {
/// System::new("test").block_on(async {
/// awc::Client::new().get("https://www.rust-lang.org")
/// .cookie(
/// awc::http::Cookie::build("name", "value")
@ -322,12 +323,12 @@ impl ClientRequest {
/// .finish(),
/// )
/// .send()
/// .map_err(|_| ())
/// .await
/// .and_then(|response| {
/// println!("Response: {:?}", response);
/// Ok(())
/// })
/// }));
/// });
/// }
/// ```
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {

View File

@ -359,22 +359,23 @@ where
mod tests {
use super::*;
use actix_http_test::block_on;
use futures::Async;
use serde::{Deserialize, Serialize};
use crate::{http::header, test::TestResponse};
#[test]
fn test_body() {
let mut req = TestResponse::with_header(header::CONTENT_LENGTH, "xxxx").finish();
match req.body().poll().err().unwrap() {
block_on(async {
let mut req =
TestResponse::with_header(header::CONTENT_LENGTH, "xxxx").finish();
match req.body().await.err().unwrap() {
PayloadError::UnknownLength => (),
_ => unreachable!("error"),
}
let mut req =
TestResponse::with_header(header::CONTENT_LENGTH, "1000000").finish();
match req.body().poll().err().unwrap() {
match req.body().await.err().unwrap() {
PayloadError::Overflow => (),
_ => unreachable!("error"),
}
@ -382,18 +383,16 @@ mod tests {
let mut req = TestResponse::default()
.set_payload(Bytes::from_static(b"test"))
.finish();
match req.body().poll().ok().unwrap() {
Async::Ready(bytes) => assert_eq!(bytes, Bytes::from_static(b"test")),
_ => unreachable!("error"),
}
assert_eq!(req.body().await.ok().unwrap(), Bytes::from_static(b"test"));
let mut req = TestResponse::default()
.set_payload(Bytes::from_static(b"11111111111111"))
.finish();
match req.body().limit(5).poll().err().unwrap() {
match req.body().limit(5).await.err().unwrap() {
PayloadError::Overflow => (),
_ => unreachable!("error"),
}
})
}
#[derive(Serialize, Deserialize, PartialEq, Debug)]
@ -417,8 +416,9 @@ mod tests {
#[test]
fn test_json_body() {
block_on(async {
let mut req = TestResponse::default().finish();
let json = block_on(JsonBody::<_, MyObject>::new(&mut req));
let json = JsonBody::<_, MyObject>::new(&mut req).await;
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
let mut req = TestResponse::default()
@ -427,7 +427,7 @@ mod tests {
header::HeaderValue::from_static("application/text"),
)
.finish();
let json = block_on(JsonBody::<_, MyObject>::new(&mut req));
let json = JsonBody::<_, MyObject>::new(&mut req).await;
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
let mut req = TestResponse::default()
@ -441,7 +441,7 @@ mod tests {
)
.finish();
let json = block_on(JsonBody::<_, MyObject>::new(&mut req).limit(100));
let json = JsonBody::<_, MyObject>::new(&mut req).limit(100).await;
assert!(json_eq(
json.err().unwrap(),
JsonPayloadError::Payload(PayloadError::Overflow)
@ -459,12 +459,13 @@ mod tests {
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.finish();
let json = block_on(JsonBody::<_, MyObject>::new(&mut req));
let json = JsonBody::<_, MyObject>::new(&mut req).await;
assert_eq!(
json.ok().unwrap(),
MyObject {
name: "test".to_owned()
}
);
})
}
}

View File

@ -389,6 +389,8 @@ impl fmt::Debug for WebsocketsRequest {
#[cfg(test)]
mod tests {
use actix_web::test::block_on;
use super::*;
use crate::Client;
@ -463,6 +465,7 @@ mod tests {
#[test]
fn basics() {
block_on(async {
let req = Client::new()
.ws("http://localhost/")
.origin("test-origin")
@ -484,14 +487,11 @@ mod tests {
header::HeaderValue::from_static("json")
);
let _ = actix_http_test::block_fn(move || req.connect());
let _ = req.connect().await;
assert!(Client::new().ws("/").connect().poll().is_err());
assert!(Client::new().ws("http:///test").connect().poll().is_err());
assert!(Client::new()
.ws("hmm://test.com/")
.connect()
.poll()
.is_err());
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

@ -9,12 +9,12 @@ use bytes::Bytes;
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use flate2::Compression;
use futures::Future;
use futures::future::ok;
use rand::Rng;
use actix_http::HttpService;
use actix_http_test::{bloxk_on, TestServer};
use actix_service::{service_fn, ServiceFactory};
use actix_http_test::{block_on, TestServer};
use actix_service::pipeline_factory;
use actix_web::http::Cookie;
use actix_web::middleware::{BodyEncoding, Compress};
use actix_web::{http::header, web, App, Error, HttpMessage, HttpRequest, HttpResponse};
@ -45,29 +45,29 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
#[test]
fn test_simple() {
block_on(async {
let mut srv = TestServer::start(|| {
let srv = TestServer::start(|| {
HttpService::new(App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
))
});
let request = srv.get("/").header("x-test", "111").send();
let mut response = srv.block_on(request).unwrap();
let mut response = request.await.unwrap();
assert!(response.status().is_success());
// read response
let bytes = srv.block_on(response.body()).unwrap();
let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
let mut response = srv.block_on(srv.post("/").send()).unwrap();
let mut response = srv.post("/").send().await.unwrap();
assert!(response.status().is_success());
// read response
let bytes = srv.block_on(response.body()).unwrap();
let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
// camel case
let response = srv.block_on(srv.post("/").camel_case().send()).unwrap();
let response = srv.post("/").camel_case().send().await.unwrap();
assert!(response.status().is_success());
})
}
@ -75,7 +75,7 @@ fn test_simple() {
#[test]
fn test_json() {
block_on(async {
let mut srv = TestServer::start(|| {
let srv = TestServer::start(|| {
HttpService::new(
App::new().service(
web::resource("/")
@ -88,7 +88,7 @@ fn test_json() {
.get("/")
.header("x-test", "111")
.send_json(&"TEST".to_string());
let response = srv.block_on(request).unwrap();
let response = request.await.unwrap();
assert!(response.status().is_success());
})
}
@ -96,7 +96,7 @@ fn test_json() {
#[test]
fn test_form() {
block_on(async {
let mut srv = TestServer::start(|| {
let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to(
|_: web::Form<HashMap<String, String>>| HttpResponse::Ok(),
))))
@ -106,7 +106,7 @@ fn test_form() {
let _ = data.insert("key".to_string(), "TEST".to_string());
let request = srv.get("/").header("x-test", "111").send_form(&data);
let response = srv.block_on(request).unwrap();
let response = request.await.unwrap();
assert!(response.status().is_success());
})
}
@ -114,22 +114,22 @@ fn test_form() {
#[test]
fn test_timeout() {
block_on(async {
let mut srv = TestServer::start(|| {
let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(
web::to_async(|| {
tokio_timer::sleep(Duration::from_millis(200))
.then(|_| Ok::<_, Error>(HttpResponse::Ok().body(STR)))
async {
tokio_timer::delay_for(Duration::from_millis(200)).await;
Ok::<_, Error>(HttpResponse::Ok().body(STR))
}
}),
)))
});
let client = srv.execute(|| {
awc::Client::build()
let client = awc::Client::build()
.timeout(Duration::from_millis(50))
.finish()
});
.finish();
let request = client.get(srv.url("/")).send();
match srv.block_on(request) {
match request.await {
Err(SendRequestError::Timeout) => (),
_ => panic!(),
}
@ -139,11 +139,13 @@ fn test_timeout() {
#[test]
fn test_timeout_override() {
block_on(async {
let mut srv = TestServer::start(|| {
let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(
web::to_async(|| {
tokio_timer::sleep(Duration::from_millis(200))
.then(|_| Ok::<_, Error>(HttpResponse::Ok().body(STR)))
async {
tokio_timer::delay_for(Duration::from_millis(200)).await;
Ok::<_, Error>(HttpResponse::Ok().body(STR))
}
}),
)))
});
@ -155,7 +157,7 @@ fn test_timeout_override() {
.get(srv.url("/"))
.timeout(Duration::from_millis(50))
.send();
match srv.block_on(request) {
match request.await {
Err(SendRequestError::Timeout) => (),
_ => panic!(),
}
@ -168,11 +170,11 @@ fn test_connection_reuse() {
let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone();
let mut srv = TestServer::start(move || {
let srv = TestServer::start(move || {
let num2 = num2.clone();
service_fn(move |io| {
pipeline_factory(move |io| {
num2.fetch_add(1, Ordering::Relaxed);
Ok(io)
ok(io)
})
.and_then(HttpService::new(App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok())),
@ -183,12 +185,12 @@ fn test_connection_reuse() {
// req 1
let request = client.get(srv.url("/")).send();
let response = srv.block_on(request).unwrap();
let response = request.await.unwrap();
assert!(response.status().is_success());
// req 2
let req = client.post(srv.url("/"));
let response = srv.block_on_fn(move || req.send()).unwrap();
let response = req.send().await.unwrap();
assert!(response.status().is_success());
// one connection
@ -202,11 +204,11 @@ fn test_connection_force_close() {
let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone();
let mut srv = TestServer::new(move || {
let srv = TestServer::start(move || {
let num2 = num2.clone();
service_fn(move |io| {
pipeline_factory(move |io| {
num2.fetch_add(1, Ordering::Relaxed);
Ok(io)
ok(io)
})
.and_then(HttpService::new(App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok())),
@ -217,12 +219,12 @@ fn test_connection_force_close() {
// req 1
let request = client.get(srv.url("/")).force_close().send();
let response = srv.block_on(request).unwrap();
let response = request.await.unwrap();
assert!(response.status().is_success());
// req 2
let req = client.post(srv.url("/")).force_close();
let response = srv.block_on_fn(move || req.send()).unwrap();
let response = req.send().await.unwrap();
assert!(response.status().is_success());
// two connection
@ -236,11 +238,11 @@ fn test_connection_server_close() {
let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone();
let mut srv = TestServer::new(move || {
let srv = TestServer::start(move || {
let num2 = num2.clone();
service_fn(move |io| {
pipeline_factory(move |io| {
num2.fetch_add(1, Ordering::Relaxed);
Ok(io)
ok(io)
})
.and_then(HttpService::new(
App::new().service(
@ -254,12 +256,12 @@ fn test_connection_server_close() {
// req 1
let request = client.get(srv.url("/")).send();
let response = srv.block_on(request).unwrap();
let response = request.await.unwrap();
assert!(response.status().is_success());
// req 2
let req = client.post(srv.url("/"));
let response = srv.block_on_fn(move || req.send()).unwrap();
let response = req.send().await.unwrap();
assert!(response.status().is_success());
// two connection
@ -273,11 +275,11 @@ fn test_connection_wait_queue() {
let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone();
let mut srv = TestServer::new(move || {
let srv = TestServer::start(move || {
let num2 = num2.clone();
service_fn(move |io| {
pipeline_factory(move |io| {
num2.fetch_add(1, Ordering::Relaxed);
Ok(io)
ok(io)
})
.and_then(HttpService::new(App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
@ -290,23 +292,19 @@ fn test_connection_wait_queue() {
// req 1
let request = client.get(srv.url("/")).send();
let mut response = srv.block_on(request).unwrap();
let mut response = request.await.unwrap();
assert!(response.status().is_success());
// req 2
let req2 = client.post(srv.url("/"));
let req2_fut = srv.execute(move || {
let mut fut = req2.send();
assert!(fut.poll().unwrap().is_not_ready());
fut
});
let req2_fut = req2.send();
// read response 1
let bytes = srv.block_on(response.body()).unwrap();
let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
// req 2
let response = srv.block_on(req2_fut).unwrap();
let response = req2_fut.await.unwrap();
assert!(response.status().is_success());
// two connection
@ -320,11 +318,11 @@ fn test_connection_wait_queue_force_close() {
let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone();
let mut srv = TestServer::new(move || {
let srv = TestServer::start(move || {
let num2 = num2.clone();
service_fn(move |io| {
pipeline_factory(move |io| {
num2.fetch_add(1, Ordering::Relaxed);
Ok(io)
ok(io)
})
.and_then(HttpService::new(
App::new().service(
@ -340,23 +338,19 @@ fn test_connection_wait_queue_force_close() {
// req 1
let request = client.get(srv.url("/")).send();
let mut response = srv.block_on(request).unwrap();
let mut response = request.await.unwrap();
assert!(response.status().is_success());
// req 2
let req2 = client.post(srv.url("/"));
let req2_fut = srv.execute(move || {
let mut fut = req2.send();
assert!(fut.poll().unwrap().is_not_ready());
fut
});
let req2_fut = req2.send();
// read response 1
let bytes = srv.block_on(response.body()).unwrap();
let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
// req 2
let response = srv.block_on(req2_fut).unwrap();
let response = req2_fut.await.unwrap();
assert!(response.status().is_success());
// two connection
@ -367,7 +361,7 @@ fn test_connection_wait_queue_force_close() {
#[test]
fn test_with_query_parameter() {
block_on(async {
let mut srv = TestServer::new(|| {
let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").to(
|req: HttpRequest| {
if req.query_string().contains("qp") {
@ -379,8 +373,10 @@ fn test_with_query_parameter() {
)))
});
let res = srv
.block_on(awc::Client::new().get(srv.url("/?qp=5")).send())
let res = awc::Client::new()
.get(srv.url("/?qp=5"))
.send()
.await
.unwrap();
assert!(res.status().is_success());
})
@ -389,7 +385,7 @@ fn test_with_query_parameter() {
#[test]
fn test_no_decompress() {
block_on(async {
let mut srv = TestServer::new(|| {
let srv = TestServer::start(|| {
HttpService::new(App::new().wrap(Compress::default()).service(
web::resource("/").route(web::to(|| {
let mut res = HttpResponse::Ok().body(STR);
@ -399,13 +395,16 @@ fn test_no_decompress() {
))
});
let mut res = srv
.block_on(awc::Client::new().get(srv.url("/")).no_decompress().send())
let mut res = awc::Client::new()
.get(srv.url("/"))
.no_decompress()
.send()
.await
.unwrap();
assert!(res.status().is_success());
// read response
let bytes = srv.block_on(res.body()).unwrap();
let bytes = res.body().await.unwrap();
let mut e = GzDecoder::new(&bytes[..]);
let mut dec = Vec::new();
@ -413,12 +412,15 @@ fn test_no_decompress() {
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
// POST
let mut res = srv
.block_on(awc::Client::new().post(srv.url("/")).no_decompress().send())
let mut res = awc::Client::new()
.post(srv.url("/"))
.no_decompress()
.send()
.await
.unwrap();
assert!(res.status().is_success());
let bytes = srv.block_on(res.body()).unwrap();
let bytes = res.body().await.unwrap();
let mut e = GzDecoder::new(&bytes[..]);
let mut dec = Vec::new();
e.read_to_end(&mut dec).unwrap();
@ -429,7 +431,7 @@ fn test_no_decompress() {
#[test]
fn test_client_gzip_encoding() {
block_on(async {
let mut srv = TestServer::new(|| {
let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to(
|| {
let mut e = GzEncoder::new(Vec::new(), Compression::default());
@ -444,11 +446,11 @@ fn test_client_gzip_encoding() {
});
// client request
let mut response = srv.block_on(srv.post("/").send()).unwrap();
let mut response = srv.post("/").send().await.unwrap();
assert!(response.status().is_success());
// read response
let bytes = srv.block_on(response.body()).unwrap();
let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
}
@ -456,7 +458,7 @@ fn test_client_gzip_encoding() {
#[test]
fn test_client_gzip_encoding_large() {
block_on(async {
let mut srv = TestServer::new(|| {
let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to(
|| {
let mut e = GzEncoder::new(Vec::new(), Compression::default());
@ -471,11 +473,11 @@ fn test_client_gzip_encoding_large() {
});
// client request
let mut response = srv.block_on(srv.post("/").send()).unwrap();
let mut response = srv.post("/").send().await.unwrap();
assert!(response.status().is_success());
// read response
let bytes = srv.block_on(response.body()).unwrap();
let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from(STR.repeat(10)));
})
}
@ -488,7 +490,7 @@ fn test_client_gzip_encoding_large_random() {
.take(100_000)
.collect::<String>();
let mut srv = TestServer::new(|| {
let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to(
|data: Bytes| {
let mut e = GzEncoder::new(Vec::new(), Compression::default());
@ -502,11 +504,11 @@ fn test_client_gzip_encoding_large_random() {
});
// client request
let mut response = srv.block_on(srv.post("/").send_body(data.clone())).unwrap();
let mut response = srv.post("/").send_body(data.clone()).await.unwrap();
assert!(response.status().is_success());
// read response
let bytes = srv.block_on(response.body()).unwrap();
let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from(data));
})
}
@ -514,7 +516,7 @@ fn test_client_gzip_encoding_large_random() {
#[test]
fn test_client_brotli_encoding() {
block_on(async {
let mut srv = TestServer::new(|| {
let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to(
|data: Bytes| {
let mut e = BrotliEncoder::new(Vec::new(), 5);
@ -528,11 +530,11 @@ fn test_client_brotli_encoding() {
});
// client request
let mut response = srv.block_on(srv.post("/").send_body(STR)).unwrap();
let mut response = srv.post("/").send_body(STR).await.unwrap();
assert!(response.status().is_success());
// read response
let bytes = srv.block_on(response.body()).unwrap();
let bytes = response.body().await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
})
}
@ -544,7 +546,7 @@ fn test_client_brotli_encoding() {
// .take(70_000)
// .collect::<String>();
// let mut srv = test::TestServer::new(|app| {
// let srv = test::TestServer::start(|app| {
// app.handler(|req: &HttpRequest| {
// req.body()
// .and_then(move |bytes: Bytes| {
@ -562,11 +564,11 @@ fn test_client_brotli_encoding() {
// .content_encoding(http::ContentEncoding::Br)
// .body(data.clone())
// .unwrap();
// let response = srv.execute(request.send()).unwrap();
// let response = request.send().await.unwrap();
// assert!(response.status().is_success());
// // read response
// let bytes = srv.execute(response.body()).unwrap();
// let bytes = response.body().await.unwrap();
// assert_eq!(bytes.len(), data.len());
// assert_eq!(bytes, Bytes::from(data));
// }
@ -574,7 +576,7 @@ fn test_client_brotli_encoding() {
// #[cfg(feature = "brotli")]
// #[test]
// fn test_client_deflate_encoding() {
// let mut srv = test::TestServer::new(|app| {
// let srv = test::TestServer::start(|app| {
// app.handler(|req: &HttpRequest| {
// req.body()
// .and_then(|bytes: Bytes| {
@ -607,7 +609,7 @@ fn test_client_brotli_encoding() {
// .take(70_000)
// .collect::<String>();
// let mut srv = test::TestServer::new(|app| {
// let srv = test::TestServer::start(|app| {
// app.handler(|req: &HttpRequest| {
// req.body()
// .and_then(|bytes: Bytes| {
@ -635,7 +637,7 @@ fn test_client_brotli_encoding() {
// #[test]
// fn test_client_streaming_explicit() {
// let mut srv = test::TestServer::new(|app| {
// let srv = test::TestServer::start(|app| {
// app.handler(|req: &HttpRequest| {
// req.body()
// .map_err(Error::from)
@ -662,7 +664,7 @@ fn test_client_brotli_encoding() {
// #[test]
// fn test_body_streaming_implicit() {
// let mut srv = test::TestServer::new(|app| {
// let srv = test::TestServer::start(|app| {
// app.handler(|_| {
// let body = once(Ok(Bytes::from_static(STR.as_ref())));
// HttpResponse::Ok()
@ -699,7 +701,7 @@ fn test_client_cookie_handling() {
let cookie1b = cookie1.clone();
let cookie2b = cookie2.clone();
let mut srv = TestServer::new(move || {
let srv = TestServer::start(move || {
let cookie1 = cookie1b.clone();
let cookie2 = cookie2b.clone();
@ -736,7 +738,7 @@ fn test_client_cookie_handling() {
});
let request = srv.get("/").cookie(cookie1.clone()).cookie(cookie2.clone());
let response = srv.block_on(request.send()).unwrap();
let response = request.send().await.unwrap();
assert!(response.status().is_success());
let c1 = response.cookie("cookie1").expect("Missing cookie1");
assert_eq!(c1, cookie1);
@ -767,18 +769,18 @@ fn test_client_cookie_handling() {
// let req = client::ClientRequest::get(format!("http://{}/", addr).as_str())
// .finish()
// .unwrap();
// let response = sys.block_on(req.send()).unwrap();
// let response = req.send().await.unwrap();
// assert!(response.status().is_success());
// // read response
// let bytes = sys.block_on(response.body()).unwrap();
// let bytes = response.body().await.unwrap();
// assert_eq!(bytes, Bytes::from_static(b"welcome!"));
// }
#[test]
fn client_basic_auth() {
block_on(async {
let mut srv = TestServer::new(|| {
let srv = TestServer::start(|| {
HttpService::new(App::new().route(
"/",
web::to(|req: HttpRequest| {
@ -800,7 +802,7 @@ fn client_basic_auth() {
// set authorization header to Basic <base64 encoded username:password>
let request = srv.get("/").basic_auth("username", Some("password"));
let response = srv.block_on(request.send()).unwrap();
let response = request.send().await.unwrap();
assert!(response.status().is_success());
})
}
@ -808,7 +810,7 @@ fn client_basic_auth() {
#[test]
fn client_bearer_auth() {
block_on(async {
let mut srv = TestServer::new(|| {
let srv = TestServer::start(|| {
HttpService::new(App::new().route(
"/",
web::to(|req: HttpRequest| {
@ -830,7 +832,7 @@ fn client_bearer_auth() {
// set authorization header to Bearer <token>
let request = srv.get("/").bearer_auth("someS3cr3tAutht0k3n");
let response = srv.block_on(request.send()).unwrap();
let response = request.send().await.unwrap();
assert!(response.status().is_success());
})
}

View File

@ -1,69 +1,81 @@
#![cfg(feature = "rust-tls")]
use rustls::{
internal::pemfile::{certs, pkcs8_private_keys},
ClientConfig, NoClientAuth,
};
#![cfg(feature = "rustls")]
use rust_tls::ClientConfig;
use std::fs::File;
use std::io::{BufReader, Result};
use std::io::Result;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use actix_codec::{AsyncRead, AsyncWrite};
use actix_http::HttpService;
use actix_http_test::TestServer;
use actix_server::ssl::RustlsAcceptor;
use actix_service::{service_fn, NewService};
use actix_http_test::{block_on, TestServer};
use actix_server::ssl::OpensslAcceptor;
use actix_service::{pipeline_factory, ServiceFactory};
use actix_web::http::Version;
use actix_web::{web, App, HttpResponse};
use futures::future::ok;
use open_ssl::ssl::{SslAcceptor, SslFiletype, SslMethod, SslVerifyMode};
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<RustlsAcceptor<T, ()>> {
use rustls::ServerConfig;
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
// load ssl keys
let mut config = ServerConfig::new(NoClientAuth::new());
let cert_file = &mut BufReader::new(File::open("../tests/cert.pem").unwrap());
let key_file = &mut BufReader::new(File::open("../tests/key.pem").unwrap());
let cert_chain = certs(cert_file).unwrap();
let mut keys = pkcs8_private_keys(key_file).unwrap();
config.set_single_cert(cert_chain, keys.remove(0)).unwrap();
let protos = vec![b"h2".to_vec()];
config.set_protocols(&protos);
Ok(RustlsAcceptor::new(config))
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder.set_verify_callback(SslVerifyMode::NONE, |_, _| true);
builder
.set_private_key_file("../tests/key.pem", SslFiletype::PEM)
.unwrap();
builder
.set_certificate_chain_file("../tests/cert.pem")
.unwrap();
builder.set_alpn_select_callback(|_, protos| {
const H2: &[u8] = b"\x02h2";
if protos.windows(3).any(|window| window == H2) {
Ok(b"h2")
} else {
Err(open_ssl::ssl::AlpnError::NOACK)
}
});
builder.set_alpn_protos(b"\x02h2")?;
Ok(actix_server::ssl::OpensslAcceptor::new(builder.build()))
}
mod danger {
pub struct NoCertificateVerification {}
impl rustls::ServerCertVerifier for NoCertificateVerification {
impl rust_tls::ServerCertVerifier for NoCertificateVerification {
fn verify_server_cert(
&self,
_roots: &rustls::RootCertStore,
_presented_certs: &[rustls::Certificate],
_roots: &rust_tls::RootCertStore,
_presented_certs: &[rust_tls::Certificate],
_dns_name: webpki::DNSNameRef<'_>,
_ocsp: &[u8],
) -> Result<rustls::ServerCertVerified, rustls::TLSError> {
Ok(rustls::ServerCertVerified::assertion())
) -> Result<rust_tls::ServerCertVerified, rust_tls::TLSError> {
Ok(rust_tls::ServerCertVerified::assertion())
}
}
}
#[test]
fn test_connection_reuse_h2() {
let rustls = ssl_acceptor().unwrap();
// #[test]
fn _test_connection_reuse_h2() {
block_on(async {
let openssl = ssl_acceptor().unwrap();
let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone();
let mut srv = TestServer::new(move || {
let srv = TestServer::start(move || {
let num2 = num2.clone();
service_fn(move |io| {
pipeline_factory(move |io| {
num2.fetch_add(1, Ordering::Relaxed);
Ok(io)
ok(io)
})
.and_then(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
.and_then(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.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(|_| ()),
)
});
@ -82,15 +94,16 @@ fn test_connection_reuse_h2() {
// req 1
let request = client.get(srv.surl("/")).send();
let response = srv.block_on(request).unwrap();
let response = request.await.unwrap();
assert!(response.status().is_success());
// req 2
let req = client.post(srv.surl("/"));
let response = srv.block_on_fn(move || req.send()).unwrap();
let response = req.send().await.unwrap();
assert!(response.status().is_success());
assert_eq!(response.version(), Version::HTTP_2);
// one connection
assert_eq!(num.load(Ordering::Relaxed), 1);
})
}

View File

@ -1,5 +1,5 @@
#![cfg(feature = "ssl")]
use openssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
#![cfg(feature = "openssl")]
use open_ssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
use std::io::Result;
use std::sync::atomic::{AtomicUsize, Ordering};
@ -7,11 +7,12 @@ use std::sync::Arc;
use actix_codec::{AsyncRead, AsyncWrite};
use actix_http::HttpService;
use actix_http_test::TestServer;
use actix_http_test::{block_on, TestServer};
use actix_server::ssl::OpensslAcceptor;
use actix_service::{service_fn, NewService};
use actix_service::{pipeline_factory, ServiceFactory};
use actix_web::http::Version;
use actix_web::{web, App, HttpResponse};
use futures::future::ok;
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
// load ssl keys
@ -27,7 +28,7 @@ fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
if protos.windows(3).any(|window| window == H2) {
Ok(b"h2")
} else {
Err(openssl::ssl::AlpnError::NOACK)
Err(open_ssl::ssl::AlpnError::NOACK)
}
});
builder.set_alpn_protos(b"\x02h2")?;
@ -36,15 +37,16 @@ fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
#[test]
fn test_connection_reuse_h2() {
block_on(async {
let openssl = ssl_acceptor().unwrap();
let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone();
let mut srv = TestServer::new(move || {
let srv = TestServer::start(move || {
let num2 = num2.clone();
service_fn(move |io| {
pipeline_factory(move |io| {
num2.fetch_add(1, Ordering::Relaxed);
Ok(io)
ok(io)
})
.and_then(
openssl
@ -53,8 +55,9 @@ 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(|_| ()),
)
});
@ -72,15 +75,16 @@ fn test_connection_reuse_h2() {
// req 1
let request = client.get(srv.surl("/")).send();
let response = srv.block_on(request).unwrap();
let response = request.await.unwrap();
assert!(response.status().is_success());
// req 2
let req = client.post(srv.surl("/"));
let response = srv.block_on_fn(move || req.send()).unwrap();
let response = req.send().await.unwrap();
assert!(response.status().is_success());
assert_eq!(response.version(), Version::HTTP_2);
// one connection
assert_eq!(num.load(Ordering::Relaxed), 1);
})
}

View File

@ -2,81 +2,82 @@ use std::io;
use actix_codec::Framed;
use actix_http::{body::BodySize, h1, ws, Error, HttpService, Request, Response};
use actix_http_test::TestServer;
use actix_http_test::{block_on, TestServer};
use bytes::{Bytes, BytesMut};
use futures::future::ok;
use futures::{Future, Sink, Stream};
use futures::{SinkExt, StreamExt};
fn ws_service(req: ws::Frame) -> impl Future<Item = ws::Message, Error = io::Error> {
async fn ws_service(req: ws::Frame) -> Result<ws::Message, io::Error> {
match req {
ws::Frame::Ping(msg) => ok(ws::Message::Pong(msg)),
ws::Frame::Ping(msg) => Ok(ws::Message::Pong(msg)),
ws::Frame::Text(text) => {
let text = if let Some(pl) = text {
String::from_utf8(Vec::from(pl.as_ref())).unwrap()
} else {
String::new()
};
ok(ws::Message::Text(text))
Ok(ws::Message::Text(text))
}
ws::Frame::Binary(bin) => ok(ws::Message::Binary(
ws::Frame::Binary(bin) => Ok(ws::Message::Binary(
bin.map(|e| e.freeze())
.unwrap_or_else(|| Bytes::from(""))
.into(),
)),
ws::Frame::Close(reason) => ok(ws::Message::Close(reason)),
_ => ok(ws::Message::Close(None)),
ws::Frame::Close(reason) => Ok(ws::Message::Close(reason)),
_ => Ok(ws::Message::Close(None)),
}
}
#[test]
fn test_simple() {
let mut srv = TestServer::new(|| {
block_on(async {
let mut srv = TestServer::start(|| {
HttpService::build()
.upgrade(|(req, framed): (Request, Framed<_, _>)| {
.upgrade(|(req, mut framed): (Request, Framed<_, _>)| {
async move {
let res = ws::handshake_response(req.head()).finish();
// send handshake response
framed
.send(h1::Message::Item((res.drop_body(), BodySize::None)))
.map_err(|e: io::Error| e.into())
.and_then(|framed| {
.await?;
// start websocket service
let framed = framed.into_framed(ws::Codec::new());
ws::Transport::with(framed, ws_service)
})
ws::Transport::with(framed, ws_service).await
}
})
.finish(|_| ok::<_, Error>(Response::NotFound()))
});
// client service
let framed = srv.ws().unwrap();
let framed = srv
.block_on(framed.send(ws::Message::Text("text".to_string())))
let mut framed = srv.ws().await.unwrap();
framed
.send(ws::Message::Text("text".to_string()))
.await
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(item, Some(ws::Frame::Text(Some(BytesMut::from("text")))));
let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, ws::Frame::Text(Some(BytesMut::from("text"))));
let framed = srv
.block_on(framed.send(ws::Message::Binary("text".into())))
framed
.send(ws::Message::Binary("text".into()))
.await
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
let item = framed.next().await.unwrap().unwrap();
assert_eq!(
item,
Some(ws::Frame::Binary(Some(Bytes::from_static(b"text").into())))
ws::Frame::Binary(Some(Bytes::from_static(b"text").into()))
);
let framed = srv
.block_on(framed.send(ws::Message::Ping("text".into())))
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(item, Some(ws::Frame::Pong("text".to_string().into())));
framed.send(ws::Message::Ping("text".into())).await.unwrap();
let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, ws::Frame::Pong("text".to_string().into()));
let framed = srv
.block_on(framed.send(ws::Message::Close(Some(ws::CloseCode::Normal.into()))))
framed
.send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
.await
.unwrap();
let (item, _framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(
item,
Some(ws::Frame::Close(Some(ws::CloseCode::Normal.into())))
);
let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, ws::Frame::Close(Some(ws::CloseCode::Normal.into())));
})
}