mirror of
https://github.com/actix/actix-extras.git
synced 2024-11-30 18:34:36 +01:00
update awc tests
This commit is contained in:
parent
3127dd4db6
commit
b510527a9f
@ -14,7 +14,7 @@ categories = ["network-programming", "asynchronous",
|
|||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
# workspace = ".."
|
workspace = ".."
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "awc"
|
name = "awc"
|
||||||
@ -59,7 +59,7 @@ serde_json = "1.0"
|
|||||||
serde_urlencoded = "0.6.1"
|
serde_urlencoded = "0.6.1"
|
||||||
tokio-timer = "0.3.0-alpha.6"
|
tokio-timer = "0.3.0-alpha.6"
|
||||||
open-ssl = { version="0.10", package="openssl", optional = true }
|
open-ssl = { version="0.10", package="openssl", optional = true }
|
||||||
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]
|
[dev-dependencies]
|
||||||
actix-rt = "1.0.0-alpha.1"
|
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 = { version = "0.3.0-alpha.1", features=["openssl"] }
|
||||||
actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] }
|
actix-http-test = { version = "0.3.0-alpha.1", features=["openssl"] }
|
||||||
actix-utils = "0.5.0-alpha.1"
|
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" }
|
brotli2 = { version="0.3.2" }
|
||||||
flate2 = { version="1.0.2" }
|
flate2 = { version="1.0.2" }
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
rand = "0.7"
|
rand = "0.7"
|
||||||
tokio-tcp = "0.1"
|
tokio-tcp = "0.1"
|
||||||
webpki = { version = "0.21" }
|
webpki = { version = "0.21" }
|
||||||
rus-tls = { version = "0.16.0", package="rustls", features = ["dangerous_configuration"] }
|
|
||||||
|
@ -7,18 +7,18 @@
|
|||||||
//! use awc::Client;
|
//! use awc::Client;
|
||||||
//!
|
//!
|
||||||
//! fn main() {
|
//! fn main() {
|
||||||
//! System::new("test").block_on(lazy(|| {
|
//! System::new("test").block_on(async {
|
||||||
//! let mut client = Client::default();
|
//! let mut client = Client::default();
|
||||||
//!
|
//!
|
||||||
//! client.get("http://www.rust-lang.org") // <- Create request builder
|
//! client.get("http://www.rust-lang.org") // <- Create request builder
|
||||||
//! .header("User-Agent", "Actix-web")
|
//! .header("User-Agent", "Actix-web")
|
||||||
//! .send() // <- Send http request
|
//! .send() // <- Send http request
|
||||||
//! .map_err(|_| ())
|
//! .await
|
||||||
//! .and_then(|response| { // <- server http response
|
//! .and_then(|response| { // <- server http response
|
||||||
//! println!("Response: {:?}", response);
|
//! println!("Response: {:?}", response);
|
||||||
//! Ok(())
|
//! Ok(())
|
||||||
//! })
|
//! })
|
||||||
//! }));
|
//! });
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
@ -57,18 +57,18 @@ use self::connect::{Connect, ConnectorWrapper};
|
|||||||
/// use awc::Client;
|
/// use awc::Client;
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// System::new("test").block_on(lazy(|| {
|
/// System::new("test").block_on(async {
|
||||||
/// let mut client = Client::default();
|
/// let mut client = Client::default();
|
||||||
///
|
///
|
||||||
/// client.get("http://www.rust-lang.org") // <- Create request builder
|
/// client.get("http://www.rust-lang.org") // <- Create request builder
|
||||||
/// .header("User-Agent", "Actix-web")
|
/// .header("User-Agent", "Actix-web")
|
||||||
/// .send() // <- Send http request
|
/// .send() // <- Send http request
|
||||||
/// .map_err(|_| ())
|
/// .await
|
||||||
/// .and_then(|response| { // <- server http response
|
/// .and_then(|response| { // <- server http response
|
||||||
/// println!("Response: {:?}", response);
|
/// println!("Response: {:?}", response);
|
||||||
/// Ok(())
|
/// Ok(())
|
||||||
/// })
|
/// })
|
||||||
/// }));
|
/// });
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
|
@ -41,17 +41,18 @@ const HTTPS_ENCODING: &str = "gzip, deflate";
|
|||||||
/// use actix_rt::System;
|
/// use actix_rt::System;
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// System::new("test").block_on(lazy(|| {
|
/// System::new("test").block_on(async {
|
||||||
/// awc::Client::new()
|
/// let response = awc::Client::new()
|
||||||
/// .get("http://www.rust-lang.org") // <- Create request builder
|
/// .get("http://www.rust-lang.org") // <- Create request builder
|
||||||
/// .header("User-Agent", "Actix-web")
|
/// .header("User-Agent", "Actix-web")
|
||||||
/// .send() // <- Send http request
|
/// .send() // <- Send http request
|
||||||
/// .map_err(|_| ())
|
/// .await;
|
||||||
/// .and_then(|response| { // <- server http response
|
///
|
||||||
|
/// response.and_then(|response| { // <- server http response
|
||||||
/// println!("Response: {:?}", response);
|
/// println!("Response: {:?}", response);
|
||||||
/// Ok(())
|
/// Ok(())
|
||||||
/// })
|
/// })
|
||||||
/// }));
|
/// });
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub struct ClientRequest {
|
pub struct ClientRequest {
|
||||||
@ -158,7 +159,7 @@ impl ClientRequest {
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// fn main() {
|
/// 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()
|
/// let req = awc::Client::new()
|
||||||
/// .get("http://www.rust-lang.org")
|
/// .get("http://www.rust-lang.org")
|
||||||
/// .set(awc::http::header::Date::now())
|
/// .set(awc::http::header::Date::now())
|
||||||
@ -186,13 +187,13 @@ impl ClientRequest {
|
|||||||
/// use awc::{http, Client};
|
/// use awc::{http, Client};
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// # actix_rt::System::new("test").block_on(futures::future::lazy(|| {
|
/// # actix_rt::System::new("test").block_on(async {
|
||||||
/// let req = Client::new()
|
/// let req = Client::new()
|
||||||
/// .get("http://www.rust-lang.org")
|
/// .get("http://www.rust-lang.org")
|
||||||
/// .header("X-TEST", "value")
|
/// .header("X-TEST", "value")
|
||||||
/// .header(http::header::CONTENT_TYPE, "application/json");
|
/// .header(http::header::CONTENT_TYPE, "application/json");
|
||||||
/// # Ok::<_, ()>(())
|
/// # Ok::<_, ()>(())
|
||||||
/// # }));
|
/// # });
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn header<K, V>(mut self, key: K, value: V) -> Self
|
pub fn header<K, V>(mut self, key: K, value: V) -> Self
|
||||||
@ -311,7 +312,7 @@ impl ClientRequest {
|
|||||||
/// # use actix_rt::System;
|
/// # use actix_rt::System;
|
||||||
/// # use futures::future::{lazy, Future};
|
/// # use futures::future::{lazy, Future};
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// System::new("test").block_on(lazy(|| {
|
/// System::new("test").block_on(async {
|
||||||
/// awc::Client::new().get("https://www.rust-lang.org")
|
/// awc::Client::new().get("https://www.rust-lang.org")
|
||||||
/// .cookie(
|
/// .cookie(
|
||||||
/// awc::http::Cookie::build("name", "value")
|
/// awc::http::Cookie::build("name", "value")
|
||||||
@ -322,12 +323,12 @@ impl ClientRequest {
|
|||||||
/// .finish(),
|
/// .finish(),
|
||||||
/// )
|
/// )
|
||||||
/// .send()
|
/// .send()
|
||||||
/// .map_err(|_| ())
|
/// .await
|
||||||
/// .and_then(|response| {
|
/// .and_then(|response| {
|
||||||
/// println!("Response: {:?}", response);
|
/// println!("Response: {:?}", response);
|
||||||
/// Ok(())
|
/// Ok(())
|
||||||
/// })
|
/// })
|
||||||
/// }));
|
/// });
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
|
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
|
||||||
|
@ -359,22 +359,23 @@ where
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use actix_http_test::block_on;
|
use actix_http_test::block_on;
|
||||||
use futures::Async;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::{http::header, test::TestResponse};
|
use crate::{http::header, test::TestResponse};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_body() {
|
fn test_body() {
|
||||||
let mut req = TestResponse::with_header(header::CONTENT_LENGTH, "xxxx").finish();
|
block_on(async {
|
||||||
match req.body().poll().err().unwrap() {
|
let mut req =
|
||||||
|
TestResponse::with_header(header::CONTENT_LENGTH, "xxxx").finish();
|
||||||
|
match req.body().await.err().unwrap() {
|
||||||
PayloadError::UnknownLength => (),
|
PayloadError::UnknownLength => (),
|
||||||
_ => unreachable!("error"),
|
_ => unreachable!("error"),
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut req =
|
let mut req =
|
||||||
TestResponse::with_header(header::CONTENT_LENGTH, "1000000").finish();
|
TestResponse::with_header(header::CONTENT_LENGTH, "1000000").finish();
|
||||||
match req.body().poll().err().unwrap() {
|
match req.body().await.err().unwrap() {
|
||||||
PayloadError::Overflow => (),
|
PayloadError::Overflow => (),
|
||||||
_ => unreachable!("error"),
|
_ => unreachable!("error"),
|
||||||
}
|
}
|
||||||
@ -382,18 +383,16 @@ mod tests {
|
|||||||
let mut req = TestResponse::default()
|
let mut req = TestResponse::default()
|
||||||
.set_payload(Bytes::from_static(b"test"))
|
.set_payload(Bytes::from_static(b"test"))
|
||||||
.finish();
|
.finish();
|
||||||
match req.body().poll().ok().unwrap() {
|
assert_eq!(req.body().await.ok().unwrap(), Bytes::from_static(b"test"));
|
||||||
Async::Ready(bytes) => assert_eq!(bytes, Bytes::from_static(b"test")),
|
|
||||||
_ => unreachable!("error"),
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut req = TestResponse::default()
|
let mut req = TestResponse::default()
|
||||||
.set_payload(Bytes::from_static(b"11111111111111"))
|
.set_payload(Bytes::from_static(b"11111111111111"))
|
||||||
.finish();
|
.finish();
|
||||||
match req.body().limit(5).poll().err().unwrap() {
|
match req.body().limit(5).await.err().unwrap() {
|
||||||
PayloadError::Overflow => (),
|
PayloadError::Overflow => (),
|
||||||
_ => unreachable!("error"),
|
_ => unreachable!("error"),
|
||||||
}
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||||
@ -417,8 +416,9 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_json_body() {
|
fn test_json_body() {
|
||||||
|
block_on(async {
|
||||||
let mut req = TestResponse::default().finish();
|
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));
|
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
|
||||||
|
|
||||||
let mut req = TestResponse::default()
|
let mut req = TestResponse::default()
|
||||||
@ -427,7 +427,7 @@ mod tests {
|
|||||||
header::HeaderValue::from_static("application/text"),
|
header::HeaderValue::from_static("application/text"),
|
||||||
)
|
)
|
||||||
.finish();
|
.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));
|
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
|
||||||
|
|
||||||
let mut req = TestResponse::default()
|
let mut req = TestResponse::default()
|
||||||
@ -441,7 +441,7 @@ mod tests {
|
|||||||
)
|
)
|
||||||
.finish();
|
.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(
|
assert!(json_eq(
|
||||||
json.err().unwrap(),
|
json.err().unwrap(),
|
||||||
JsonPayloadError::Payload(PayloadError::Overflow)
|
JsonPayloadError::Payload(PayloadError::Overflow)
|
||||||
@ -459,12 +459,13 @@ mod tests {
|
|||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.finish();
|
.finish();
|
||||||
|
|
||||||
let json = block_on(JsonBody::<_, MyObject>::new(&mut req));
|
let json = JsonBody::<_, MyObject>::new(&mut req).await;
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
json.ok().unwrap(),
|
json.ok().unwrap(),
|
||||||
MyObject {
|
MyObject {
|
||||||
name: "test".to_owned()
|
name: "test".to_owned()
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -389,6 +389,8 @@ impl fmt::Debug for WebsocketsRequest {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
use actix_web::test::block_on;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::Client;
|
use crate::Client;
|
||||||
|
|
||||||
@ -463,6 +465,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn basics() {
|
fn basics() {
|
||||||
|
block_on(async {
|
||||||
let req = Client::new()
|
let req = Client::new()
|
||||||
.ws("http://localhost/")
|
.ws("http://localhost/")
|
||||||
.origin("test-origin")
|
.origin("test-origin")
|
||||||
@ -484,14 +487,11 @@ mod tests {
|
|||||||
header::HeaderValue::from_static("json")
|
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("/").connect().await.is_err());
|
||||||
assert!(Client::new().ws("http:///test").connect().poll().is_err());
|
assert!(Client::new().ws("http:///test").connect().await.is_err());
|
||||||
assert!(Client::new()
|
assert!(Client::new().ws("hmm://test.com/").connect().await.is_err());
|
||||||
.ws("hmm://test.com/")
|
})
|
||||||
.connect()
|
|
||||||
.poll()
|
|
||||||
.is_err());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,12 +9,12 @@ use bytes::Bytes;
|
|||||||
use flate2::read::GzDecoder;
|
use flate2::read::GzDecoder;
|
||||||
use flate2::write::GzEncoder;
|
use flate2::write::GzEncoder;
|
||||||
use flate2::Compression;
|
use flate2::Compression;
|
||||||
use futures::Future;
|
use futures::future::ok;
|
||||||
use rand::Rng;
|
use rand::Rng;
|
||||||
|
|
||||||
use actix_http::HttpService;
|
use actix_http::HttpService;
|
||||||
use actix_http_test::{bloxk_on, TestServer};
|
use actix_http_test::{block_on, TestServer};
|
||||||
use actix_service::{service_fn, ServiceFactory};
|
use actix_service::pipeline_factory;
|
||||||
use actix_web::http::Cookie;
|
use actix_web::http::Cookie;
|
||||||
use actix_web::middleware::{BodyEncoding, Compress};
|
use actix_web::middleware::{BodyEncoding, Compress};
|
||||||
use actix_web::{http::header, web, App, Error, HttpMessage, HttpRequest, HttpResponse};
|
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]
|
#[test]
|
||||||
fn test_simple() {
|
fn test_simple() {
|
||||||
block_on(async {
|
block_on(async {
|
||||||
let mut srv = TestServer::start(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(App::new().service(
|
HttpService::new(App::new().service(
|
||||||
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
|
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
|
||||||
))
|
))
|
||||||
});
|
});
|
||||||
|
|
||||||
let request = srv.get("/").header("x-test", "111").send();
|
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());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// read response
|
// 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()));
|
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());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// read response
|
// 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()));
|
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||||
|
|
||||||
// camel case
|
// 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());
|
assert!(response.status().is_success());
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -75,7 +75,7 @@ fn test_simple() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_json() {
|
fn test_json() {
|
||||||
block_on(async {
|
block_on(async {
|
||||||
let mut srv = TestServer::start(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(
|
HttpService::new(
|
||||||
App::new().service(
|
App::new().service(
|
||||||
web::resource("/")
|
web::resource("/")
|
||||||
@ -88,7 +88,7 @@ fn test_json() {
|
|||||||
.get("/")
|
.get("/")
|
||||||
.header("x-test", "111")
|
.header("x-test", "111")
|
||||||
.send_json(&"TEST".to_string());
|
.send_json(&"TEST".to_string());
|
||||||
let response = srv.block_on(request).unwrap();
|
let response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -96,7 +96,7 @@ fn test_json() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_form() {
|
fn test_form() {
|
||||||
block_on(async {
|
block_on(async {
|
||||||
let mut srv = TestServer::start(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(App::new().service(web::resource("/").route(web::to(
|
HttpService::new(App::new().service(web::resource("/").route(web::to(
|
||||||
|_: web::Form<HashMap<String, String>>| HttpResponse::Ok(),
|
|_: web::Form<HashMap<String, String>>| HttpResponse::Ok(),
|
||||||
))))
|
))))
|
||||||
@ -106,7 +106,7 @@ fn test_form() {
|
|||||||
let _ = data.insert("key".to_string(), "TEST".to_string());
|
let _ = data.insert("key".to_string(), "TEST".to_string());
|
||||||
|
|
||||||
let request = srv.get("/").header("x-test", "111").send_form(&data);
|
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());
|
assert!(response.status().is_success());
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -114,22 +114,22 @@ fn test_form() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_timeout() {
|
fn test_timeout() {
|
||||||
block_on(async {
|
block_on(async {
|
||||||
let mut srv = TestServer::start(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(App::new().service(web::resource("/").route(
|
HttpService::new(App::new().service(web::resource("/").route(
|
||||||
web::to_async(|| {
|
web::to_async(|| {
|
||||||
tokio_timer::sleep(Duration::from_millis(200))
|
async {
|
||||||
.then(|_| Ok::<_, Error>(HttpResponse::Ok().body(STR)))
|
tokio_timer::delay_for(Duration::from_millis(200)).await;
|
||||||
|
Ok::<_, Error>(HttpResponse::Ok().body(STR))
|
||||||
|
}
|
||||||
}),
|
}),
|
||||||
)))
|
)))
|
||||||
});
|
});
|
||||||
|
|
||||||
let client = srv.execute(|| {
|
let client = awc::Client::build()
|
||||||
awc::Client::build()
|
|
||||||
.timeout(Duration::from_millis(50))
|
.timeout(Duration::from_millis(50))
|
||||||
.finish()
|
.finish();
|
||||||
});
|
|
||||||
let request = client.get(srv.url("/")).send();
|
let request = client.get(srv.url("/")).send();
|
||||||
match srv.block_on(request) {
|
match request.await {
|
||||||
Err(SendRequestError::Timeout) => (),
|
Err(SendRequestError::Timeout) => (),
|
||||||
_ => panic!(),
|
_ => panic!(),
|
||||||
}
|
}
|
||||||
@ -139,11 +139,13 @@ fn test_timeout() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_timeout_override() {
|
fn test_timeout_override() {
|
||||||
block_on(async {
|
block_on(async {
|
||||||
let mut srv = TestServer::start(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(App::new().service(web::resource("/").route(
|
HttpService::new(App::new().service(web::resource("/").route(
|
||||||
web::to_async(|| {
|
web::to_async(|| {
|
||||||
tokio_timer::sleep(Duration::from_millis(200))
|
async {
|
||||||
.then(|_| Ok::<_, Error>(HttpResponse::Ok().body(STR)))
|
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("/"))
|
.get(srv.url("/"))
|
||||||
.timeout(Duration::from_millis(50))
|
.timeout(Duration::from_millis(50))
|
||||||
.send();
|
.send();
|
||||||
match srv.block_on(request) {
|
match request.await {
|
||||||
Err(SendRequestError::Timeout) => (),
|
Err(SendRequestError::Timeout) => (),
|
||||||
_ => panic!(),
|
_ => panic!(),
|
||||||
}
|
}
|
||||||
@ -168,11 +170,11 @@ fn test_connection_reuse() {
|
|||||||
let num = Arc::new(AtomicUsize::new(0));
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
let num2 = num.clone();
|
let num2 = num.clone();
|
||||||
|
|
||||||
let mut srv = TestServer::start(move || {
|
let srv = TestServer::start(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
service_fn(move |io| {
|
pipeline_factory(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
Ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
.and_then(HttpService::new(App::new().service(
|
.and_then(HttpService::new(App::new().service(
|
||||||
web::resource("/").route(web::to(|| HttpResponse::Ok())),
|
web::resource("/").route(web::to(|| HttpResponse::Ok())),
|
||||||
@ -183,12 +185,12 @@ fn test_connection_reuse() {
|
|||||||
|
|
||||||
// req 1
|
// req 1
|
||||||
let request = client.get(srv.url("/")).send();
|
let request = client.get(srv.url("/")).send();
|
||||||
let response = srv.block_on(request).unwrap();
|
let response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// req 2
|
// req 2
|
||||||
let req = client.post(srv.url("/"));
|
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());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// one connection
|
// one connection
|
||||||
@ -202,11 +204,11 @@ fn test_connection_force_close() {
|
|||||||
let num = Arc::new(AtomicUsize::new(0));
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
let num2 = num.clone();
|
let num2 = num.clone();
|
||||||
|
|
||||||
let mut srv = TestServer::new(move || {
|
let srv = TestServer::start(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
service_fn(move |io| {
|
pipeline_factory(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
Ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
.and_then(HttpService::new(App::new().service(
|
.and_then(HttpService::new(App::new().service(
|
||||||
web::resource("/").route(web::to(|| HttpResponse::Ok())),
|
web::resource("/").route(web::to(|| HttpResponse::Ok())),
|
||||||
@ -217,12 +219,12 @@ fn test_connection_force_close() {
|
|||||||
|
|
||||||
// req 1
|
// req 1
|
||||||
let request = client.get(srv.url("/")).force_close().send();
|
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());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// req 2
|
// req 2
|
||||||
let req = client.post(srv.url("/")).force_close();
|
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());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// two connection
|
// two connection
|
||||||
@ -236,11 +238,11 @@ fn test_connection_server_close() {
|
|||||||
let num = Arc::new(AtomicUsize::new(0));
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
let num2 = num.clone();
|
let num2 = num.clone();
|
||||||
|
|
||||||
let mut srv = TestServer::new(move || {
|
let srv = TestServer::start(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
service_fn(move |io| {
|
pipeline_factory(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
Ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
.and_then(HttpService::new(
|
.and_then(HttpService::new(
|
||||||
App::new().service(
|
App::new().service(
|
||||||
@ -254,12 +256,12 @@ fn test_connection_server_close() {
|
|||||||
|
|
||||||
// req 1
|
// req 1
|
||||||
let request = client.get(srv.url("/")).send();
|
let request = client.get(srv.url("/")).send();
|
||||||
let response = srv.block_on(request).unwrap();
|
let response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// req 2
|
// req 2
|
||||||
let req = client.post(srv.url("/"));
|
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());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// two connection
|
// two connection
|
||||||
@ -273,11 +275,11 @@ fn test_connection_wait_queue() {
|
|||||||
let num = Arc::new(AtomicUsize::new(0));
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
let num2 = num.clone();
|
let num2 = num.clone();
|
||||||
|
|
||||||
let mut srv = TestServer::new(move || {
|
let srv = TestServer::start(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
service_fn(move |io| {
|
pipeline_factory(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
Ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
.and_then(HttpService::new(App::new().service(
|
.and_then(HttpService::new(App::new().service(
|
||||||
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
|
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
|
||||||
@ -290,23 +292,19 @@ fn test_connection_wait_queue() {
|
|||||||
|
|
||||||
// req 1
|
// req 1
|
||||||
let request = client.get(srv.url("/")).send();
|
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());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// req 2
|
// req 2
|
||||||
let req2 = client.post(srv.url("/"));
|
let req2 = client.post(srv.url("/"));
|
||||||
let req2_fut = srv.execute(move || {
|
let req2_fut = req2.send();
|
||||||
let mut fut = req2.send();
|
|
||||||
assert!(fut.poll().unwrap().is_not_ready());
|
|
||||||
fut
|
|
||||||
});
|
|
||||||
|
|
||||||
// read response 1
|
// 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()));
|
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||||
|
|
||||||
// req 2
|
// req 2
|
||||||
let response = srv.block_on(req2_fut).unwrap();
|
let response = req2_fut.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// two connection
|
// two connection
|
||||||
@ -320,11 +318,11 @@ fn test_connection_wait_queue_force_close() {
|
|||||||
let num = Arc::new(AtomicUsize::new(0));
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
let num2 = num.clone();
|
let num2 = num.clone();
|
||||||
|
|
||||||
let mut srv = TestServer::new(move || {
|
let srv = TestServer::start(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
service_fn(move |io| {
|
pipeline_factory(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
Ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
.and_then(HttpService::new(
|
.and_then(HttpService::new(
|
||||||
App::new().service(
|
App::new().service(
|
||||||
@ -340,23 +338,19 @@ fn test_connection_wait_queue_force_close() {
|
|||||||
|
|
||||||
// req 1
|
// req 1
|
||||||
let request = client.get(srv.url("/")).send();
|
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());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// req 2
|
// req 2
|
||||||
let req2 = client.post(srv.url("/"));
|
let req2 = client.post(srv.url("/"));
|
||||||
let req2_fut = srv.execute(move || {
|
let req2_fut = req2.send();
|
||||||
let mut fut = req2.send();
|
|
||||||
assert!(fut.poll().unwrap().is_not_ready());
|
|
||||||
fut
|
|
||||||
});
|
|
||||||
|
|
||||||
// read response 1
|
// 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()));
|
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||||
|
|
||||||
// req 2
|
// req 2
|
||||||
let response = srv.block_on(req2_fut).unwrap();
|
let response = req2_fut.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// two connection
|
// two connection
|
||||||
@ -367,7 +361,7 @@ fn test_connection_wait_queue_force_close() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_with_query_parameter() {
|
fn test_with_query_parameter() {
|
||||||
block_on(async {
|
block_on(async {
|
||||||
let mut srv = TestServer::new(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(App::new().service(web::resource("/").to(
|
HttpService::new(App::new().service(web::resource("/").to(
|
||||||
|req: HttpRequest| {
|
|req: HttpRequest| {
|
||||||
if req.query_string().contains("qp") {
|
if req.query_string().contains("qp") {
|
||||||
@ -379,8 +373,10 @@ fn test_with_query_parameter() {
|
|||||||
)))
|
)))
|
||||||
});
|
});
|
||||||
|
|
||||||
let res = srv
|
let res = awc::Client::new()
|
||||||
.block_on(awc::Client::new().get(srv.url("/?qp=5")).send())
|
.get(srv.url("/?qp=5"))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(res.status().is_success());
|
assert!(res.status().is_success());
|
||||||
})
|
})
|
||||||
@ -389,7 +385,7 @@ fn test_with_query_parameter() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_no_decompress() {
|
fn test_no_decompress() {
|
||||||
block_on(async {
|
block_on(async {
|
||||||
let mut srv = TestServer::new(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(App::new().wrap(Compress::default()).service(
|
HttpService::new(App::new().wrap(Compress::default()).service(
|
||||||
web::resource("/").route(web::to(|| {
|
web::resource("/").route(web::to(|| {
|
||||||
let mut res = HttpResponse::Ok().body(STR);
|
let mut res = HttpResponse::Ok().body(STR);
|
||||||
@ -399,13 +395,16 @@ fn test_no_decompress() {
|
|||||||
))
|
))
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut res = srv
|
let mut res = awc::Client::new()
|
||||||
.block_on(awc::Client::new().get(srv.url("/")).no_decompress().send())
|
.get(srv.url("/"))
|
||||||
|
.no_decompress()
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(res.status().is_success());
|
assert!(res.status().is_success());
|
||||||
|
|
||||||
// read response
|
// read response
|
||||||
let bytes = srv.block_on(res.body()).unwrap();
|
let bytes = res.body().await.unwrap();
|
||||||
|
|
||||||
let mut e = GzDecoder::new(&bytes[..]);
|
let mut e = GzDecoder::new(&bytes[..]);
|
||||||
let mut dec = Vec::new();
|
let mut dec = Vec::new();
|
||||||
@ -413,12 +412,15 @@ fn test_no_decompress() {
|
|||||||
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
|
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
|
||||||
|
|
||||||
// POST
|
// POST
|
||||||
let mut res = srv
|
let mut res = awc::Client::new()
|
||||||
.block_on(awc::Client::new().post(srv.url("/")).no_decompress().send())
|
.post(srv.url("/"))
|
||||||
|
.no_decompress()
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(res.status().is_success());
|
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 e = GzDecoder::new(&bytes[..]);
|
||||||
let mut dec = Vec::new();
|
let mut dec = Vec::new();
|
||||||
e.read_to_end(&mut dec).unwrap();
|
e.read_to_end(&mut dec).unwrap();
|
||||||
@ -429,7 +431,7 @@ fn test_no_decompress() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_client_gzip_encoding() {
|
fn test_client_gzip_encoding() {
|
||||||
block_on(async {
|
block_on(async {
|
||||||
let mut srv = TestServer::new(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(App::new().service(web::resource("/").route(web::to(
|
HttpService::new(App::new().service(web::resource("/").route(web::to(
|
||||||
|| {
|
|| {
|
||||||
let mut e = GzEncoder::new(Vec::new(), Compression::default());
|
let mut e = GzEncoder::new(Vec::new(), Compression::default());
|
||||||
@ -444,11 +446,11 @@ fn test_client_gzip_encoding() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// client request
|
// 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());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// read response
|
// 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()));
|
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -456,7 +458,7 @@ fn test_client_gzip_encoding() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_client_gzip_encoding_large() {
|
fn test_client_gzip_encoding_large() {
|
||||||
block_on(async {
|
block_on(async {
|
||||||
let mut srv = TestServer::new(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(App::new().service(web::resource("/").route(web::to(
|
HttpService::new(App::new().service(web::resource("/").route(web::to(
|
||||||
|| {
|
|| {
|
||||||
let mut e = GzEncoder::new(Vec::new(), Compression::default());
|
let mut e = GzEncoder::new(Vec::new(), Compression::default());
|
||||||
@ -471,11 +473,11 @@ fn test_client_gzip_encoding_large() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// client request
|
// 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());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// read response
|
// read response
|
||||||
let bytes = srv.block_on(response.body()).unwrap();
|
let bytes = response.body().await.unwrap();
|
||||||
assert_eq!(bytes, Bytes::from(STR.repeat(10)));
|
assert_eq!(bytes, Bytes::from(STR.repeat(10)));
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -488,7 +490,7 @@ fn test_client_gzip_encoding_large_random() {
|
|||||||
.take(100_000)
|
.take(100_000)
|
||||||
.collect::<String>();
|
.collect::<String>();
|
||||||
|
|
||||||
let mut srv = TestServer::new(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(App::new().service(web::resource("/").route(web::to(
|
HttpService::new(App::new().service(web::resource("/").route(web::to(
|
||||||
|data: Bytes| {
|
|data: Bytes| {
|
||||||
let mut e = GzEncoder::new(Vec::new(), Compression::default());
|
let mut e = GzEncoder::new(Vec::new(), Compression::default());
|
||||||
@ -502,11 +504,11 @@ fn test_client_gzip_encoding_large_random() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// client request
|
// 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());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// read response
|
// read response
|
||||||
let bytes = srv.block_on(response.body()).unwrap();
|
let bytes = response.body().await.unwrap();
|
||||||
assert_eq!(bytes, Bytes::from(data));
|
assert_eq!(bytes, Bytes::from(data));
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -514,7 +516,7 @@ fn test_client_gzip_encoding_large_random() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_client_brotli_encoding() {
|
fn test_client_brotli_encoding() {
|
||||||
block_on(async {
|
block_on(async {
|
||||||
let mut srv = TestServer::new(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(App::new().service(web::resource("/").route(web::to(
|
HttpService::new(App::new().service(web::resource("/").route(web::to(
|
||||||
|data: Bytes| {
|
|data: Bytes| {
|
||||||
let mut e = BrotliEncoder::new(Vec::new(), 5);
|
let mut e = BrotliEncoder::new(Vec::new(), 5);
|
||||||
@ -528,11 +530,11 @@ fn test_client_brotli_encoding() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// client request
|
// 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());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// read response
|
// 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()));
|
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -544,7 +546,7 @@ fn test_client_brotli_encoding() {
|
|||||||
// .take(70_000)
|
// .take(70_000)
|
||||||
// .collect::<String>();
|
// .collect::<String>();
|
||||||
|
|
||||||
// let mut srv = test::TestServer::new(|app| {
|
// let srv = test::TestServer::start(|app| {
|
||||||
// app.handler(|req: &HttpRequest| {
|
// app.handler(|req: &HttpRequest| {
|
||||||
// req.body()
|
// req.body()
|
||||||
// .and_then(move |bytes: Bytes| {
|
// .and_then(move |bytes: Bytes| {
|
||||||
@ -562,11 +564,11 @@ fn test_client_brotli_encoding() {
|
|||||||
// .content_encoding(http::ContentEncoding::Br)
|
// .content_encoding(http::ContentEncoding::Br)
|
||||||
// .body(data.clone())
|
// .body(data.clone())
|
||||||
// .unwrap();
|
// .unwrap();
|
||||||
// let response = srv.execute(request.send()).unwrap();
|
// let response = request.send().await.unwrap();
|
||||||
// assert!(response.status().is_success());
|
// assert!(response.status().is_success());
|
||||||
|
|
||||||
// // read response
|
// // read response
|
||||||
// let bytes = srv.execute(response.body()).unwrap();
|
// let bytes = response.body().await.unwrap();
|
||||||
// assert_eq!(bytes.len(), data.len());
|
// assert_eq!(bytes.len(), data.len());
|
||||||
// assert_eq!(bytes, Bytes::from(data));
|
// assert_eq!(bytes, Bytes::from(data));
|
||||||
// }
|
// }
|
||||||
@ -574,7 +576,7 @@ fn test_client_brotli_encoding() {
|
|||||||
// #[cfg(feature = "brotli")]
|
// #[cfg(feature = "brotli")]
|
||||||
// #[test]
|
// #[test]
|
||||||
// fn test_client_deflate_encoding() {
|
// fn test_client_deflate_encoding() {
|
||||||
// let mut srv = test::TestServer::new(|app| {
|
// let srv = test::TestServer::start(|app| {
|
||||||
// app.handler(|req: &HttpRequest| {
|
// app.handler(|req: &HttpRequest| {
|
||||||
// req.body()
|
// req.body()
|
||||||
// .and_then(|bytes: Bytes| {
|
// .and_then(|bytes: Bytes| {
|
||||||
@ -607,7 +609,7 @@ fn test_client_brotli_encoding() {
|
|||||||
// .take(70_000)
|
// .take(70_000)
|
||||||
// .collect::<String>();
|
// .collect::<String>();
|
||||||
|
|
||||||
// let mut srv = test::TestServer::new(|app| {
|
// let srv = test::TestServer::start(|app| {
|
||||||
// app.handler(|req: &HttpRequest| {
|
// app.handler(|req: &HttpRequest| {
|
||||||
// req.body()
|
// req.body()
|
||||||
// .and_then(|bytes: Bytes| {
|
// .and_then(|bytes: Bytes| {
|
||||||
@ -635,7 +637,7 @@ fn test_client_brotli_encoding() {
|
|||||||
|
|
||||||
// #[test]
|
// #[test]
|
||||||
// fn test_client_streaming_explicit() {
|
// fn test_client_streaming_explicit() {
|
||||||
// let mut srv = test::TestServer::new(|app| {
|
// let srv = test::TestServer::start(|app| {
|
||||||
// app.handler(|req: &HttpRequest| {
|
// app.handler(|req: &HttpRequest| {
|
||||||
// req.body()
|
// req.body()
|
||||||
// .map_err(Error::from)
|
// .map_err(Error::from)
|
||||||
@ -662,7 +664,7 @@ fn test_client_brotli_encoding() {
|
|||||||
|
|
||||||
// #[test]
|
// #[test]
|
||||||
// fn test_body_streaming_implicit() {
|
// fn test_body_streaming_implicit() {
|
||||||
// let mut srv = test::TestServer::new(|app| {
|
// let srv = test::TestServer::start(|app| {
|
||||||
// app.handler(|_| {
|
// app.handler(|_| {
|
||||||
// let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
// let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||||
// HttpResponse::Ok()
|
// HttpResponse::Ok()
|
||||||
@ -699,7 +701,7 @@ fn test_client_cookie_handling() {
|
|||||||
let cookie1b = cookie1.clone();
|
let cookie1b = cookie1.clone();
|
||||||
let cookie2b = cookie2.clone();
|
let cookie2b = cookie2.clone();
|
||||||
|
|
||||||
let mut srv = TestServer::new(move || {
|
let srv = TestServer::start(move || {
|
||||||
let cookie1 = cookie1b.clone();
|
let cookie1 = cookie1b.clone();
|
||||||
let cookie2 = cookie2b.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 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());
|
assert!(response.status().is_success());
|
||||||
let c1 = response.cookie("cookie1").expect("Missing cookie1");
|
let c1 = response.cookie("cookie1").expect("Missing cookie1");
|
||||||
assert_eq!(c1, cookie1);
|
assert_eq!(c1, cookie1);
|
||||||
@ -767,18 +769,18 @@ fn test_client_cookie_handling() {
|
|||||||
// let req = client::ClientRequest::get(format!("http://{}/", addr).as_str())
|
// let req = client::ClientRequest::get(format!("http://{}/", addr).as_str())
|
||||||
// .finish()
|
// .finish()
|
||||||
// .unwrap();
|
// .unwrap();
|
||||||
// let response = sys.block_on(req.send()).unwrap();
|
// let response = req.send().await.unwrap();
|
||||||
// assert!(response.status().is_success());
|
// assert!(response.status().is_success());
|
||||||
|
|
||||||
// // read response
|
// // read response
|
||||||
// let bytes = sys.block_on(response.body()).unwrap();
|
// let bytes = response.body().await.unwrap();
|
||||||
// assert_eq!(bytes, Bytes::from_static(b"welcome!"));
|
// assert_eq!(bytes, Bytes::from_static(b"welcome!"));
|
||||||
// }
|
// }
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn client_basic_auth() {
|
fn client_basic_auth() {
|
||||||
block_on(async {
|
block_on(async {
|
||||||
let mut srv = TestServer::new(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(App::new().route(
|
HttpService::new(App::new().route(
|
||||||
"/",
|
"/",
|
||||||
web::to(|req: HttpRequest| {
|
web::to(|req: HttpRequest| {
|
||||||
@ -800,7 +802,7 @@ fn client_basic_auth() {
|
|||||||
|
|
||||||
// set authorization header to Basic <base64 encoded username:password>
|
// set authorization header to Basic <base64 encoded username:password>
|
||||||
let request = srv.get("/").basic_auth("username", Some("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());
|
assert!(response.status().is_success());
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -808,7 +810,7 @@ fn client_basic_auth() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn client_bearer_auth() {
|
fn client_bearer_auth() {
|
||||||
block_on(async {
|
block_on(async {
|
||||||
let mut srv = TestServer::new(|| {
|
let srv = TestServer::start(|| {
|
||||||
HttpService::new(App::new().route(
|
HttpService::new(App::new().route(
|
||||||
"/",
|
"/",
|
||||||
web::to(|req: HttpRequest| {
|
web::to(|req: HttpRequest| {
|
||||||
@ -830,7 +832,7 @@ fn client_bearer_auth() {
|
|||||||
|
|
||||||
// set authorization header to Bearer <token>
|
// set authorization header to Bearer <token>
|
||||||
let request = srv.get("/").bearer_auth("someS3cr3tAutht0k3n");
|
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());
|
assert!(response.status().is_success());
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -1,69 +1,81 @@
|
|||||||
#![cfg(feature = "rust-tls")]
|
#![cfg(feature = "rustls")]
|
||||||
use rustls::{
|
use rust_tls::ClientConfig;
|
||||||
internal::pemfile::{certs, pkcs8_private_keys},
|
|
||||||
ClientConfig, NoClientAuth,
|
|
||||||
};
|
|
||||||
|
|
||||||
use std::fs::File;
|
use std::io::Result;
|
||||||
use std::io::{BufReader, Result};
|
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_http::HttpService;
|
use actix_http::HttpService;
|
||||||
use actix_http_test::TestServer;
|
use actix_http_test::{block_on, TestServer};
|
||||||
use actix_server::ssl::RustlsAcceptor;
|
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::http::Version;
|
||||||
use actix_web::{web, App, HttpResponse};
|
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, ()>> {
|
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
|
||||||
use rustls::ServerConfig;
|
|
||||||
// load ssl keys
|
// load ssl keys
|
||||||
let mut config = ServerConfig::new(NoClientAuth::new());
|
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||||
let cert_file = &mut BufReader::new(File::open("../tests/cert.pem").unwrap());
|
builder.set_verify_callback(SslVerifyMode::NONE, |_, _| true);
|
||||||
let key_file = &mut BufReader::new(File::open("../tests/key.pem").unwrap());
|
builder
|
||||||
let cert_chain = certs(cert_file).unwrap();
|
.set_private_key_file("../tests/key.pem", SslFiletype::PEM)
|
||||||
let mut keys = pkcs8_private_keys(key_file).unwrap();
|
.unwrap();
|
||||||
config.set_single_cert(cert_chain, keys.remove(0)).unwrap();
|
builder
|
||||||
let protos = vec![b"h2".to_vec()];
|
.set_certificate_chain_file("../tests/cert.pem")
|
||||||
config.set_protocols(&protos);
|
.unwrap();
|
||||||
Ok(RustlsAcceptor::new(config))
|
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 {
|
mod danger {
|
||||||
pub struct NoCertificateVerification {}
|
pub struct NoCertificateVerification {}
|
||||||
|
|
||||||
impl rustls::ServerCertVerifier for NoCertificateVerification {
|
impl rust_tls::ServerCertVerifier for NoCertificateVerification {
|
||||||
fn verify_server_cert(
|
fn verify_server_cert(
|
||||||
&self,
|
&self,
|
||||||
_roots: &rustls::RootCertStore,
|
_roots: &rust_tls::RootCertStore,
|
||||||
_presented_certs: &[rustls::Certificate],
|
_presented_certs: &[rust_tls::Certificate],
|
||||||
_dns_name: webpki::DNSNameRef<'_>,
|
_dns_name: webpki::DNSNameRef<'_>,
|
||||||
_ocsp: &[u8],
|
_ocsp: &[u8],
|
||||||
) -> Result<rustls::ServerCertVerified, rustls::TLSError> {
|
) -> Result<rust_tls::ServerCertVerified, rust_tls::TLSError> {
|
||||||
Ok(rustls::ServerCertVerified::assertion())
|
Ok(rust_tls::ServerCertVerified::assertion())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
// #[test]
|
||||||
fn test_connection_reuse_h2() {
|
fn _test_connection_reuse_h2() {
|
||||||
let rustls = ssl_acceptor().unwrap();
|
block_on(async {
|
||||||
|
let openssl = ssl_acceptor().unwrap();
|
||||||
let num = Arc::new(AtomicUsize::new(0));
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
let num2 = num.clone();
|
let num2 = num.clone();
|
||||||
|
|
||||||
let mut srv = TestServer::new(move || {
|
let srv = TestServer::start(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
service_fn(move |io| {
|
pipeline_factory(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
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(
|
.and_then(
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(App::new()
|
.h2(App::new().service(
|
||||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
|
web::resource("/").route(web::to(|| HttpResponse::Ok())),
|
||||||
|
))
|
||||||
.map_err(|_| ()),
|
.map_err(|_| ()),
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
@ -82,15 +94,16 @@ fn test_connection_reuse_h2() {
|
|||||||
|
|
||||||
// req 1
|
// req 1
|
||||||
let request = client.get(srv.surl("/")).send();
|
let request = client.get(srv.surl("/")).send();
|
||||||
let response = srv.block_on(request).unwrap();
|
let response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// req 2
|
// req 2
|
||||||
let req = client.post(srv.surl("/"));
|
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!(response.status().is_success());
|
||||||
assert_eq!(response.version(), Version::HTTP_2);
|
assert_eq!(response.version(), Version::HTTP_2);
|
||||||
|
|
||||||
// one connection
|
// one connection
|
||||||
assert_eq!(num.load(Ordering::Relaxed), 1);
|
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
#![cfg(feature = "ssl")]
|
#![cfg(feature = "openssl")]
|
||||||
use openssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
|
use open_ssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
|
||||||
|
|
||||||
use std::io::Result;
|
use std::io::Result;
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
@ -7,11 +7,12 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_http::HttpService;
|
use actix_http::HttpService;
|
||||||
use actix_http_test::TestServer;
|
use actix_http_test::{block_on, TestServer};
|
||||||
use actix_server::ssl::OpensslAcceptor;
|
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::http::Version;
|
||||||
use actix_web::{web, App, HttpResponse};
|
use actix_web::{web, App, HttpResponse};
|
||||||
|
use futures::future::ok;
|
||||||
|
|
||||||
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
|
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
|
||||||
// load ssl keys
|
// load ssl keys
|
||||||
@ -27,7 +28,7 @@ fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
|
|||||||
if protos.windows(3).any(|window| window == H2) {
|
if protos.windows(3).any(|window| window == H2) {
|
||||||
Ok(b"h2")
|
Ok(b"h2")
|
||||||
} else {
|
} else {
|
||||||
Err(openssl::ssl::AlpnError::NOACK)
|
Err(open_ssl::ssl::AlpnError::NOACK)
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
builder.set_alpn_protos(b"\x02h2")?;
|
builder.set_alpn_protos(b"\x02h2")?;
|
||||||
@ -36,15 +37,16 @@ fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_connection_reuse_h2() {
|
fn test_connection_reuse_h2() {
|
||||||
|
block_on(async {
|
||||||
let openssl = ssl_acceptor().unwrap();
|
let openssl = ssl_acceptor().unwrap();
|
||||||
let num = Arc::new(AtomicUsize::new(0));
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
let num2 = num.clone();
|
let num2 = num.clone();
|
||||||
|
|
||||||
let mut srv = TestServer::new(move || {
|
let srv = TestServer::start(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
service_fn(move |io| {
|
pipeline_factory(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
Ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
.and_then(
|
.and_then(
|
||||||
openssl
|
openssl
|
||||||
@ -53,8 +55,9 @@ fn test_connection_reuse_h2() {
|
|||||||
)
|
)
|
||||||
.and_then(
|
.and_then(
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(App::new()
|
.h2(App::new().service(
|
||||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
|
web::resource("/").route(web::to(|| HttpResponse::Ok())),
|
||||||
|
))
|
||||||
.map_err(|_| ()),
|
.map_err(|_| ()),
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
@ -72,15 +75,16 @@ fn test_connection_reuse_h2() {
|
|||||||
|
|
||||||
// req 1
|
// req 1
|
||||||
let request = client.get(srv.surl("/")).send();
|
let request = client.get(srv.surl("/")).send();
|
||||||
let response = srv.block_on(request).unwrap();
|
let response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// req 2
|
// req 2
|
||||||
let req = client.post(srv.surl("/"));
|
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!(response.status().is_success());
|
||||||
assert_eq!(response.version(), Version::HTTP_2);
|
assert_eq!(response.version(), Version::HTTP_2);
|
||||||
|
|
||||||
// one connection
|
// one connection
|
||||||
assert_eq!(num.load(Ordering::Relaxed), 1);
|
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
@ -2,81 +2,82 @@ use std::io;
|
|||||||
|
|
||||||
use actix_codec::Framed;
|
use actix_codec::Framed;
|
||||||
use actix_http::{body::BodySize, h1, ws, Error, HttpService, Request, Response};
|
use actix_http::{body::BodySize, h1, ws, Error, HttpService, Request, Response};
|
||||||
use actix_http_test::TestServer;
|
use actix_http_test::{block_on, TestServer};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures::future::ok;
|
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 {
|
match req {
|
||||||
ws::Frame::Ping(msg) => ok(ws::Message::Pong(msg)),
|
ws::Frame::Ping(msg) => Ok(ws::Message::Pong(msg)),
|
||||||
ws::Frame::Text(text) => {
|
ws::Frame::Text(text) => {
|
||||||
let text = if let Some(pl) = text {
|
let text = if let Some(pl) = text {
|
||||||
String::from_utf8(Vec::from(pl.as_ref())).unwrap()
|
String::from_utf8(Vec::from(pl.as_ref())).unwrap()
|
||||||
} else {
|
} else {
|
||||||
String::new()
|
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())
|
bin.map(|e| e.freeze())
|
||||||
.unwrap_or_else(|| Bytes::from(""))
|
.unwrap_or_else(|| Bytes::from(""))
|
||||||
.into(),
|
.into(),
|
||||||
)),
|
)),
|
||||||
ws::Frame::Close(reason) => ok(ws::Message::Close(reason)),
|
ws::Frame::Close(reason) => Ok(ws::Message::Close(reason)),
|
||||||
_ => ok(ws::Message::Close(None)),
|
_ => Ok(ws::Message::Close(None)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_simple() {
|
fn test_simple() {
|
||||||
let mut srv = TestServer::new(|| {
|
block_on(async {
|
||||||
|
let mut srv = TestServer::start(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.upgrade(|(req, framed): (Request, Framed<_, _>)| {
|
.upgrade(|(req, mut framed): (Request, Framed<_, _>)| {
|
||||||
|
async move {
|
||||||
let res = ws::handshake_response(req.head()).finish();
|
let res = ws::handshake_response(req.head()).finish();
|
||||||
// send handshake response
|
// send handshake response
|
||||||
framed
|
framed
|
||||||
.send(h1::Message::Item((res.drop_body(), BodySize::None)))
|
.send(h1::Message::Item((res.drop_body(), BodySize::None)))
|
||||||
.map_err(|e: io::Error| e.into())
|
.await?;
|
||||||
.and_then(|framed| {
|
|
||||||
// start websocket service
|
// start websocket service
|
||||||
let framed = framed.into_framed(ws::Codec::new());
|
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()))
|
.finish(|_| ok::<_, Error>(Response::NotFound()))
|
||||||
});
|
});
|
||||||
|
|
||||||
// client service
|
// client service
|
||||||
let framed = srv.ws().unwrap();
|
let mut framed = srv.ws().await.unwrap();
|
||||||
let framed = srv
|
framed
|
||||||
.block_on(framed.send(ws::Message::Text("text".to_string())))
|
.send(ws::Message::Text("text".to_string()))
|
||||||
|
.await
|
||||||
.unwrap();
|
.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::Text(Some(BytesMut::from("text")))));
|
assert_eq!(item, ws::Frame::Text(Some(BytesMut::from("text"))));
|
||||||
|
|
||||||
let framed = srv
|
framed
|
||||||
.block_on(framed.send(ws::Message::Binary("text".into())))
|
.send(ws::Message::Binary("text".into()))
|
||||||
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
item,
|
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
|
framed.send(ws::Message::Ping("text".into())).await.unwrap();
|
||||||
.block_on(framed.send(ws::Message::Ping("text".into())))
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
.unwrap();
|
assert_eq!(item, ws::Frame::Pong("text".to_string().into()));
|
||||||
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
|
|
||||||
assert_eq!(item, Some(ws::Frame::Pong("text".to_string().into())));
|
|
||||||
|
|
||||||
let framed = srv
|
framed
|
||||||
.block_on(framed.send(ws::Message::Close(Some(ws::CloseCode::Normal.into()))))
|
.send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
|
||||||
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let (item, _framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
assert_eq!(
|
assert_eq!(item, ws::Frame::Close(Some(ws::CloseCode::Normal.into())));
|
||||||
item,
|
})
|
||||||
Some(ws::Frame::Close(Some(ws::CloseCode::Normal.into())))
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user