Skip to content
This repository has been archived by the owner on May 18, 2023. It is now read-only.

Commit

Permalink
Merge branch 'master' into replay_mode
Browse files Browse the repository at this point in the history
  • Loading branch information
leoschwarz committed May 5, 2020
2 parents 6dada41 + 4ea202f commit eb58bb2
Show file tree
Hide file tree
Showing 9 changed files with 69 additions and 19 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
target/
/target
**/*.rs.bk
Cargo.lock
7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "reqwest_mock"
version = "0.6.0"
version = "0.7.0"
authors = ["Leo Schwarz <[email protected]>"]
license = "Apache-2.0"
description = "Provides a mockable reqwest-like HTTP client."
Expand All @@ -11,13 +11,14 @@ keywords = ["http", "request", "client"]
[dependencies]
base64 = "0.12.0"
error-chain = "0.12"
http = "0.1"
http = "0.2"
log = "0.4.0"
reqwest = "0.9"
reqwest = { version = "0.10", features = ["blocking", "gzip"] }
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
twox-hash = "1.1"
url = "2.1"

[dev-dependencies]
futures = "0.1"
Expand Down
4 changes: 2 additions & 2 deletions src/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ impl Body {
}
}

impl From<Body> for ::reqwest::Body {
fn from(b: Body) -> ::reqwest::Body {
impl From<Body> for ::reqwest::blocking::Body {
fn from(b: Body) -> ::reqwest::blocking::Body {
match b.value {
BodyValue::Bytes(b) => b.into(),
BodyValue::File(f) => f.into(),
Expand Down
4 changes: 2 additions & 2 deletions src/client/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ impl Client for DirectClient {
let config = config.unwrap_or_else(|| &self.config);

// Setup the client instance.
let mut client_builder = ::reqwest::Client::builder()
let mut client_builder = ::reqwest::blocking::Client::builder()
.gzip(config.gzip)
.redirect(config.redirect.clone().into())
.referer(config.referer);
Expand All @@ -46,7 +46,7 @@ impl Client for DirectClient {
// Build the request.
let mut builder = client.request(request.header.method, request.header.url);
if let Some(body) = request.body {
builder = builder.body(::reqwest::Body::from(body));
builder = builder.body(::reqwest::blocking::Body::from(body));
}

// Send the request.
Expand Down
2 changes: 2 additions & 0 deletions src/client/stub/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::io;
// TODO: impl Error

// TODO: Should be crate or module visible.
#[derive(Debug)]
pub struct FieldError {
/// The name of the missing field.
pub field_name: &'static str,
Expand All @@ -12,6 +13,7 @@ pub struct FieldError {
}

// TODO: Variants should be private.
#[derive(Debug)]
pub enum RegisterStubError {
// "Tried registering stub without `{}` even though `{}` requires its presence."
MissingField(FieldError),
Expand Down
6 changes: 3 additions & 3 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,11 @@ impl Default for RedirectPolicy {
}
}

impl From<RedirectPolicy> for ::reqwest::RedirectPolicy {
impl From<RedirectPolicy> for ::reqwest::redirect::Policy {
fn from(p: RedirectPolicy) -> Self {
match p {
RedirectPolicy::Limit(n) => ::reqwest::RedirectPolicy::limited(n),
RedirectPolicy::None => ::reqwest::RedirectPolicy::none(),
RedirectPolicy::Limit(n) => ::reqwest::redirect::Policy::limited(n),
RedirectPolicy::None => ::reqwest::redirect::Policy::none(),
}
}
}
4 changes: 3 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ extern crate serde;
extern crate serde_derive;
extern crate serde_json;
extern crate twox_hash;
extern crate url;

mod helper;

Expand All @@ -74,4 +75,5 @@ mod request_builder;
pub use self::client::*;
pub use self::error::Error;

pub use reqwest::{header, IntoUrl, Method, StatusCode, Url, UrlError};
pub use reqwest::{header, IntoUrl, Method, StatusCode, Url};
pub use url::ParseError as UrlError;
18 changes: 18 additions & 0 deletions src/request.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use body::Body;
use http::Request as HttpRequest;
use reqwest::header::HeaderMap;
use reqwest::{Method, Url};
use serde::de::Error as DeError;
Expand Down Expand Up @@ -33,6 +34,23 @@ impl Request {
}
}

impl<T> From<HttpRequest<T>> for Request where T: Into<Body> {
fn from(r: HttpRequest<T>) -> Self {
let header = RequestHeader {
// TODO: Handle error when converting.
// Potentially https://github.com/seanmonstar/reqwest/issues/668 would provide a solution in the future.
url: Url::parse(&format!("{}", r.uri())).unwrap(),
method: r.method().clone(),
headers: r.headers().clone(),
};

Request {
header,
body: Some(r.into_body().into()),
}
}
}

#[derive(Clone, Debug, PartialEq)]
pub struct RequestMem {
pub header: RequestHeader,
Expand Down
41 changes: 34 additions & 7 deletions src/response.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use base64;
use error::Error;
use http::HttpTryFrom;
use http::Response as HttpResponse;
use reqwest::header::HeaderMap;
use reqwest::{StatusCode, Url};
use serde::de::Error as DeError;
Expand Down Expand Up @@ -95,7 +95,7 @@ impl<'de> Visitor<'de> for ResponseVisitor {
return Err(DeError::duplicate_field(F_STATUS));
}
let s: u16 = map.next_value()?;
status = Some(StatusCode::try_from(s).map_err(|_| {
status = Some(StatusCode::from_u16(s).map_err(|_| {
DeError::invalid_value(Unexpected::Unsigned(s as u64), &"StatusCode")
})?);
}
Expand Down Expand Up @@ -126,6 +126,19 @@ impl<'de> Visitor<'de> for ResponseVisitor {
}
}

impl From<Response> for HttpResponse<Vec<u8>> {
fn from(r: Response) -> HttpResponse<Vec<u8>> {
let mut http_rsp = HttpResponse::builder().status(r.status);
let headers = http_rsp.headers_mut().unwrap();
for (key, value) in r.headers {
if let Some(k) = key {
headers.append(&k, value);
}
}
http_rsp.body(r.body).unwrap()
}
}

impl<'de> Deserialize<'de> for Response {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand All @@ -139,25 +152,39 @@ impl<'de> Deserialize<'de> for Response {
#[cfg(test)]
mod tests {
use super::*;
use reqwest::header::{CONTENT_LENGTH, USER_AGENT};

#[test]
fn serde() {
use reqwest::header::{CONTENT_LENGTH, USER_AGENT};
fn dummy_response() -> Response {

let mut headers = HeaderMap::new();
headers.insert(CONTENT_LENGTH, 2000.into());
headers.insert(USER_AGENT, "Testing Code".parse().unwrap());

let resp1 = Response {
Response {
url: Url::parse("http://example.com/index.html").unwrap(),
status: StatusCode::OK,
headers: headers,
body: vec![2, 4, 8, 16, 32, 64, 42],
};
}
}

#[test]
fn serde() {
let resp1 = dummy_response();
let json = ::serde_json::to_string(&resp1).unwrap();

let resp2 = ::serde_json::from_str(json.as_ref()).unwrap();
assert_eq!(resp1, resp2);
}

#[test]
fn http_response() {
let resp = dummy_response();
let http_resp = HttpResponse::<Vec<u8>>::from(resp);

assert_eq!(http_resp.status(), http::StatusCode::OK);
assert_eq!(http_resp.headers().get(CONTENT_LENGTH).unwrap().to_str().unwrap(), "2000");
assert_eq!(http_resp.headers().get(USER_AGENT).unwrap(), "Testing Code");
assert_eq!(http_resp.body(), &vec![2u8, 4, 8, 16, 32, 64, 42]);
}
}

0 comments on commit eb58bb2

Please sign in to comment.