Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor mock support #540

Merged
merged 7 commits into from
Dec 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 0 additions & 98 deletions sdk/core/src/bytes_response.rs

This file was deleted.

26 changes: 0 additions & 26 deletions sdk/core/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,32 +217,6 @@ pub enum TraversingError {
ParsingError(#[from] ParsingError),
}

/// An error relating to the mock transport framework.
#[cfg(feature = "mock_transport_framework")]
#[derive(Debug, thiserror::Error)]
pub enum MockFrameworkError {
#[error("the mock testing framework has not been initialized")]
UninitializedTransaction,
#[error("{0}: {1}")]
IOError(String, std::io::Error),
#[error("{0}")]
TransactionStorageError(String),
#[error("{0}")]
MissingTransaction(String),
#[error("mismatched request uri. Actual '{0}', Expected: '{1}'")]
MismatchedRequestUri(String, String),
#[error("received request have header {0} but it was not present in the read request")]
MissingRequestHeader(String),
#[error("different number of headers in request. Actual: {0}, Expected: {1}")]
MismatchedRequestHeadersCount(usize, usize),
#[error("request header {0} value is different. Actual: {1}, Expected: {2}")]
MismatchedRequestHeader(String, String, String),
#[error("mismatched HTTP request method. Actual: {0}, Expected: {1}")]
MismatchedRequestHTTPMethod(http::Method, http::Method),
#[error("mismatched request body. Actual: {0:?}, Expected: {1:?}")]
MismatchedRequestBody(Vec<u8>, Vec<u8>),
}

/// Extract the headers and body from a `hyper` HTTP response.
#[cfg(feature = "enable_hyper")]
#[inline]
Expand Down
5 changes: 1 addition & 4 deletions sdk/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ extern crate serde_derive;
#[macro_use]
mod macros;

mod bytes_response;
mod bytes_stream;
mod constants;
mod context;
Expand All @@ -33,7 +32,7 @@ mod sleep;
pub mod auth;
pub mod headers;
#[cfg(feature = "mock_transport_framework")]
mod mock_transaction;
pub mod mock;
pub mod parsing;
pub mod prelude;
pub mod util;
Expand All @@ -48,8 +47,6 @@ pub use errors::*;
#[doc(inline)]
pub use headers::AddAsHeader;
pub use http_client::{new_http_client, to_json, HttpClient};
#[cfg(feature = "mock_transport_framework")]
pub use mock_transaction::constants::*;
pub use models::*;
pub use options::*;
pub use pipeline::Pipeline;
Expand Down
145 changes: 145 additions & 0 deletions sdk/core/src/mock/mock_request.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
use crate::{Body, Request};
use http::{HeaderMap, Method, Uri};
use serde::de::Visitor;
use serde::ser::{Serialize, SerializeStruct, Serializer};
use serde::{Deserialize, Deserializer};
use std::collections::HashMap;
use std::str::FromStr;

const FIELDS: &[&str] = &["uri", "method", "headers", "body"];

impl Request {
fn new(uri: Uri, method: Method, headers: HeaderMap, body: Body) -> Self {
Self {
uri,
method,
headers,
body,
}
}
}

impl<'de> Deserialize<'de> for Request {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_struct("Request", FIELDS, RequestVisitor)
}
}

struct RequestVisitor;

impl<'de> Visitor<'de> for RequestVisitor {
type Value = Request;

fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("struct Request")
}

fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: serde::de::MapAccess<'de>,
{
let uri: (&str, &str) = match map.next_entry()? {
Some((a, b)) => (a, b),
None => return Err(serde::de::Error::custom("missing uri")),
};

if uri.0 != FIELDS[0] {
return Err(serde::de::Error::custom(format!(
"unexpected field {}, expected {}",
uri.0, FIELDS[0]
)));
}

let method: (&str, &str) = match map.next_entry()? {
Some((a, b)) => (a, b),
None => return Err(serde::de::Error::custom("missing method")),
};

if method.0 != FIELDS[1] {
return Err(serde::de::Error::custom(format!(
"unexpected field {}, expected {}",
method.0, FIELDS[1]
)));
}

let headers: (&str, HashMap<&str, String>) = match map.next_entry()? {
Some((a, b)) => (a, b),
None => return Err(serde::de::Error::custom("missing header map")),
};
if headers.0 != FIELDS[2] {
return Err(serde::de::Error::custom(format!(
"unexpected field {}, expected {}",
headers.0, FIELDS[2]
)));
}

let body: (&str, String) = match map.next_entry()? {
Some((a, b)) => (a, b),
None => return Err(serde::de::Error::custom("missing body")),
};
if body.0 != FIELDS[3] {
return Err(serde::de::Error::custom(format!(
"unexpected field {}, expected {}",
body.0, FIELDS[3]
)));
}

let body = base64::decode(&body.1).map_err(serde::de::Error::custom)?;

let mut hm = HeaderMap::new();
for (k, v) in headers.1.into_iter() {
hm.append(
http::header::HeaderName::from_lowercase(k.as_bytes())
.map_err(serde::de::Error::custom)?,
http::HeaderValue::from_str(&v).map_err(serde::de::Error::custom)?,
);
}

Ok(Self::Value::new(
Uri::from_str(uri.1).expect("expected a valid uri"),
Method::from_str(method.1).expect("expected a valid HTTP method"),
hm,
bytes::Bytes::from(body).into(),
))
}
}

impl Serialize for Request {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut hm = std::collections::BTreeMap::new();
for (h, v) in self.headers().iter() {
if h.as_str().to_lowercase() == "authorization" {
hm.insert(h.to_string(), "<<STRIPPED>>");
} else {
hm.insert(h.to_string(), v.to_str().unwrap());
}
}

let mut state = serializer.serialize_struct("Request", 4)?;
state.serialize_field(
FIELDS[0],
&self
.uri
.path_and_query()
.map(|p| p.to_string())
.unwrap_or_else(String::new),
)?;
state.serialize_field(FIELDS[1], &self.method.to_string())?;
state.serialize_field(FIELDS[2], &hm)?;
state.serialize_field(
FIELDS[3],
&match &self.body {
Body::Bytes(bytes) => base64::encode(bytes as &[u8]),
Body::SeekableStream(_) => unimplemented!(),
},
)?;

state.end()
}
}
Loading