Skip to content

Commit

Permalink
update awc tests
Browse files Browse the repository at this point in the history
  • Loading branch information
fafhrd91 committed Nov 21, 2019
1 parent 3127dd4 commit b510527
Show file tree
Hide file tree
Showing 9 changed files with 410 additions and 389 deletions.
7 changes: 3 additions & 4 deletions awc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -59,19 +59,18 @@ 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"
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"] }
12 changes: 6 additions & 6 deletions awc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)]
Expand Down
27 changes: 14 additions & 13 deletions awc/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
/// println!("Response: {:?}", response);
/// Ok(())
/// .await;
///
/// response.and_then(|response| { // <- server http response
/// println!("Response: {:?}", response);
/// Ok(())
/// })
/// }));
/// });
/// }
/// ```
pub struct ClientRequest {
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand All @@ -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 {
Expand Down
153 changes: 77 additions & 76 deletions awc/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -359,41 +359,40 @@ 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() {
PayloadError::UnknownLength => (),
_ => unreachable!("error"),
}

let mut req =
TestResponse::with_header(header::CONTENT_LENGTH, "1000000").finish();
match req.body().poll().err().unwrap() {
PayloadError::Overflow => (),
_ => unreachable!("error"),
}
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::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"),
}
let mut req =
TestResponse::with_header(header::CONTENT_LENGTH, "1000000").finish();
match req.body().await.err().unwrap() {
PayloadError::Overflow => (),
_ => unreachable!("error"),
}

let mut req = TestResponse::default()
.set_payload(Bytes::from_static(b"11111111111111"))
.finish();
match req.body().limit(5).poll().err().unwrap() {
PayloadError::Overflow => (),
_ => unreachable!("error"),
}
let mut req = TestResponse::default()
.set_payload(Bytes::from_static(b"test"))
.finish();
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).await.err().unwrap() {
PayloadError::Overflow => (),
_ => unreachable!("error"),
}
})
}

#[derive(Serialize, Deserialize, PartialEq, Debug)]
Expand All @@ -417,54 +416,56 @@ mod tests {

#[test]
fn test_json_body() {
let mut req = TestResponse::default().finish();
let json = block_on(JsonBody::<_, MyObject>::new(&mut req));
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));

let mut req = TestResponse::default()
.header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/text"),
)
.finish();
let json = block_on(JsonBody::<_, MyObject>::new(&mut req));
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));

let mut req = TestResponse::default()
.header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
)
.header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("10000"),
)
.finish();

let json = block_on(JsonBody::<_, MyObject>::new(&mut req).limit(100));
assert!(json_eq(
json.err().unwrap(),
JsonPayloadError::Payload(PayloadError::Overflow)
));

let mut req = TestResponse::default()
.header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
)
.header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.finish();

let json = block_on(JsonBody::<_, MyObject>::new(&mut req));
assert_eq!(
json.ok().unwrap(),
MyObject {
name: "test".to_owned()
}
);
block_on(async {
let mut req = TestResponse::default().finish();
let json = JsonBody::<_, MyObject>::new(&mut req).await;
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));

let mut req = TestResponse::default()
.header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/text"),
)
.finish();
let json = JsonBody::<_, MyObject>::new(&mut req).await;
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));

let mut req = TestResponse::default()
.header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
)
.header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("10000"),
)
.finish();

let json = JsonBody::<_, MyObject>::new(&mut req).limit(100).await;
assert!(json_eq(
json.err().unwrap(),
JsonPayloadError::Payload(PayloadError::Overflow)
));

let mut req = TestResponse::default()
.header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
)
.header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.finish();

let json = JsonBody::<_, MyObject>::new(&mut req).await;
assert_eq!(
json.ok().unwrap(),
MyObject {
name: "test".to_owned()
}
);
})
}
}
56 changes: 28 additions & 28 deletions awc/src/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,8 @@ impl fmt::Debug for WebsocketsRequest {

#[cfg(test)]
mod tests {
use actix_web::test::block_on;

use super::*;
use crate::Client;

Expand Down Expand Up @@ -463,35 +465,33 @@ mod tests {

#[test]
fn basics() {
let req = Client::new()
.ws("http://localhost/")
.origin("test-origin")
.max_frame_size(100)
.server_mode()
.protocols(&["v1", "v2"])
.set_header_if_none(header::CONTENT_TYPE, "json")
.set_header_if_none(header::CONTENT_TYPE, "text")
.cookie(Cookie::build("cookie1", "value1").finish());
assert_eq!(
req.origin.as_ref().unwrap().to_str().unwrap(),
"test-origin"
);
assert_eq!(req.max_size, 100);
assert_eq!(req.server_mode, true);
assert_eq!(req.protocols, Some("v1,v2".to_string()));
assert_eq!(
req.head.headers.get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("json")
);
block_on(async {
let req = Client::new()
.ws("http://localhost/")
.origin("test-origin")
.max_frame_size(100)
.server_mode()
.protocols(&["v1", "v2"])
.set_header_if_none(header::CONTENT_TYPE, "json")
.set_header_if_none(header::CONTENT_TYPE, "text")
.cookie(Cookie::build("cookie1", "value1").finish());
assert_eq!(
req.origin.as_ref().unwrap().to_str().unwrap(),
"test-origin"
);
assert_eq!(req.max_size, 100);
assert_eq!(req.server_mode, true);
assert_eq!(req.protocols, Some("v1,v2".to_string()));
assert_eq!(
req.head.headers.get(header::CONTENT_TYPE).unwrap(),
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());
})
}
}
Loading

0 comments on commit b510527

Please sign in to comment.