Compare commits
3 commits
73a9ca3be9
...
a844db5fe4
Author | SHA1 | Date | |
---|---|---|---|
a844db5fe4 | |||
e25531df61 | |||
d58ec0eba2 |
8 changed files with 484 additions and 136 deletions
|
@ -14,6 +14,7 @@ unexpected_cfgs = { level = "warn", check-cfg = ['cfg(tarpaulin_include)'] }
|
|||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
bytes = "1.8"
|
||||
derive_more = { version = "1.0", features = [
|
||||
"constructor",
|
||||
"display",
|
||||
|
|
|
@ -61,10 +61,6 @@ async fn download_and_save_to_file(
|
|||
) -> kxio::Result<()> {
|
||||
println!("fetching: {url}");
|
||||
|
||||
// Uses the network abstraction to create a perfectly normal `reqwest::ResponseBuilder`.
|
||||
// `kxio::net::RequestBuilder` is an alias.
|
||||
let request: kxio::net::RequestBuilder = net.client().get(url);
|
||||
|
||||
// Rather than calling `.build().send()?` on the request, pass it to the `net`
|
||||
// This allows the `net` to either make the network request as normal, or, if we are
|
||||
// under test, to handle the request as the test dictates.
|
||||
|
@ -72,7 +68,13 @@ async fn download_and_save_to_file(
|
|||
// a real network request being made, even under test conditions. Only ever use the
|
||||
// `net.send(...)` function to keep your code testable.
|
||||
// `kxio::net::Response` is an alias for `reqwest::Response`.
|
||||
let response: kxio::net::Response = net.send(request).await?;
|
||||
let response: kxio::net::Response = net.get(url).header("key", "value").send().await?;
|
||||
// Other options:
|
||||
// Uses the network abstraction to create a perfectly normal `reqwest::ResponseBuilder`.
|
||||
// `kxio::net::RequestBuilder` is an alias.
|
||||
// let response = net.send(net.client().get(url)).await?;
|
||||
//
|
||||
// let response = net.post(url).body("{}").send().await?;
|
||||
|
||||
let body = response.text().await?;
|
||||
println!("fetched {} bytes", body.bytes().len());
|
||||
|
@ -102,6 +104,8 @@ fn delete_file(file_path: &Path, fs: &kxio::fs::FileSystem) -> kxio::Result<()>
|
|||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use http::StatusCode;
|
||||
|
||||
use super::*;
|
||||
|
||||
// This test demonstrates how to use the `kxio` to test your program.
|
||||
|
@ -116,8 +120,12 @@ mod tests {
|
|||
let url = "http://localhost:8080";
|
||||
|
||||
// declare what response should be made for a given request
|
||||
let response = mock_net.response().body("contents").expect("response body");
|
||||
mock_net.on().get(url).respond(response);
|
||||
mock_net
|
||||
.on()
|
||||
.get(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("contents")
|
||||
.expect("valid mock");
|
||||
|
||||
// Create a temporary directory that will be deleted with `fs` goes out of scope
|
||||
let fs = kxio::fs::temp().expect("temp fs");
|
||||
|
|
|
@ -21,6 +21,11 @@ impl TempFileSystem {
|
|||
_temp_dir: temp_dir,
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a clone of the wrapped [FileSystem].
|
||||
pub fn as_real(&self) -> FileSystem {
|
||||
self.real.clone()
|
||||
}
|
||||
}
|
||||
impl std::ops::Deref for TempFileSystem {
|
||||
type Target = FileSystem;
|
||||
|
|
|
@ -79,15 +79,14 @@
|
|||
//!
|
||||
//! ```rust
|
||||
//! use kxio::net;
|
||||
//! use kxio::net::StatusCode;
|
||||
//! # #[tokio::main]
|
||||
//! # async fn main() -> net::Result<()> {
|
||||
//! # let mock_net = net::mock();
|
||||
//! mock_net.on()
|
||||
//! .get("https://example.com")
|
||||
//! .respond(mock_net.response().status(200).body("")?);
|
||||
//! mock_net.on()
|
||||
//! .get("https://example.com/foo")
|
||||
//! .respond(mock_net.response().status(500).body("Mocked response")?);
|
||||
//! mock_net.on().get("https://example.com")
|
||||
//! .respond(StatusCode::OK).body("");
|
||||
//! mock_net.on().get("https://example.com/foo")
|
||||
//! .respond(StatusCode::INTERNAL_SERVER_ERROR).body("Mocked response");
|
||||
//! # mock_net.reset();
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
|
@ -151,7 +150,9 @@ pub use system::{MockNet, Net};
|
|||
|
||||
pub use http::HeaderMap;
|
||||
pub use http::Method;
|
||||
pub use http::StatusCode;
|
||||
pub use reqwest::Client;
|
||||
pub use reqwest::Error as RequestError;
|
||||
pub use reqwest::Request;
|
||||
pub use reqwest::RequestBuilder;
|
||||
pub use reqwest::Response;
|
||||
|
|
|
@ -3,6 +3,8 @@ use derive_more::derive::From;
|
|||
|
||||
use crate::net::Request;
|
||||
|
||||
use super::system::MockError;
|
||||
|
||||
/// The Errors that may occur within [kxio::net][crate::net].
|
||||
#[derive(Debug, From, derive_more::Display)]
|
||||
pub enum Error {
|
||||
|
@ -32,6 +34,14 @@ pub enum Error {
|
|||
|
||||
/// Attempted to extract a [MockNet][super::MockNet] from a [Net][super::Net] that does not contain one.
|
||||
NetIsNotAMock,
|
||||
|
||||
InvalidMock(MockError),
|
||||
|
||||
/// The returned response is has an error status code (i.e. 4xx or 5xx)
|
||||
#[display("response error: {}", response.status())]
|
||||
ResponseError {
|
||||
response: reqwest::Response,
|
||||
},
|
||||
}
|
||||
impl std::error::Error for Error {}
|
||||
impl Clone for Error {
|
||||
|
|
|
@ -1,14 +1,23 @@
|
|||
//
|
||||
|
||||
use std::{cell::RefCell, ops::Deref, rc::Rc, sync::Arc};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::HashMap,
|
||||
fmt::{Debug, Display},
|
||||
marker::PhantomData,
|
||||
ops::Deref,
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use bytes::Bytes;
|
||||
use derive_more::derive::{Display, From};
|
||||
use http::Method;
|
||||
use reqwest::{Body, Client};
|
||||
use http::StatusCode;
|
||||
use reqwest::{Client, RequestBuilder};
|
||||
use tokio::sync::Mutex;
|
||||
use url::Url;
|
||||
|
||||
use crate::net::{Request, RequestBuilder, Response};
|
||||
use crate::net::{Request, Response};
|
||||
|
||||
use super::{Error, Result};
|
||||
|
||||
|
@ -21,12 +30,12 @@ type Plans = Vec<Plan>;
|
|||
#[derive(Debug)]
|
||||
struct Plan {
|
||||
match_request: Vec<MatchRequest>,
|
||||
response: Response,
|
||||
response: reqwest::Response,
|
||||
}
|
||||
impl Plan {
|
||||
fn matches(&self, request: &Request) -> bool {
|
||||
self.match_request.iter().all(|criteria| match criteria {
|
||||
MatchRequest::Method(method) => request.method() == method,
|
||||
MatchRequest::Method(method) => request.method() == http::Method::from(method),
|
||||
MatchRequest::Url(uri) => request.url() == uri,
|
||||
MatchRequest::Header { name, value } => {
|
||||
request
|
||||
|
@ -40,11 +49,19 @@ impl Plan {
|
|||
})
|
||||
}
|
||||
MatchRequest::Body(body) => {
|
||||
request.body().and_then(Body::as_bytes) == Some(body.as_bytes())
|
||||
request.body().and_then(reqwest::Body::as_bytes) == Some(body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Display for Plan {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
for m in &self.match_request {
|
||||
write!(f, " {m}")?;
|
||||
}
|
||||
writeln!(f, " => {:?}", self.response)
|
||||
}
|
||||
}
|
||||
|
||||
/// An abstraction for the network
|
||||
#[derive(Debug, Clone, Default)]
|
||||
|
@ -68,6 +85,7 @@ impl Net {
|
|||
/// let client = net.client();
|
||||
/// let request = client.get("https://hyper.rs");
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn client(&self) -> Client {
|
||||
Default::default()
|
||||
}
|
||||
|
@ -75,10 +93,16 @@ impl Net {
|
|||
/// Constructs the Request and sends it to the target URL, returning a
|
||||
/// future Response.
|
||||
///
|
||||
/// However, if this request is from a [Net] that was created from a [MockNet],
|
||||
/// then the request will be matched and any stored response returned, or an
|
||||
/// error if no matched request was found.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails if there was an error while sending request,
|
||||
/// redirect loop was detected or redirect limit was exhausted.
|
||||
/// If the response has a Status Code of `4xx` or `5xx` then the
|
||||
/// response will be returned as an [Error::ResponseError].
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
|
@ -96,6 +120,12 @@ impl Net {
|
|||
return request.into().send().await.map_err(Error::from);
|
||||
};
|
||||
let request = request.into().build()?;
|
||||
eprintln!(
|
||||
"? {} {} {:?}",
|
||||
request.method(),
|
||||
request.url(),
|
||||
request.headers()
|
||||
);
|
||||
let index = plans
|
||||
.lock()
|
||||
.await
|
||||
|
@ -105,12 +135,54 @@ impl Net {
|
|||
.position(|plan| plan.matches(&request));
|
||||
match index {
|
||||
Some(i) => {
|
||||
let response = plans.lock().await.borrow_mut().remove(i).response;
|
||||
Ok(response)
|
||||
let plan = plans.lock().await.borrow_mut().remove(i);
|
||||
eprintln!("- matched: {plan}");
|
||||
let response = plan.response;
|
||||
if response.status().is_success() {
|
||||
Ok(response)
|
||||
} else {
|
||||
Err(crate::net::Error::ResponseError { response })
|
||||
}
|
||||
}
|
||||
None => Err(Error::UnexpectedMockRequest(request)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts building an http DELETE request for the URL.
|
||||
#[must_use]
|
||||
pub fn delete(&self, url: impl Into<String>) -> ReqBuilder {
|
||||
ReqBuilder::new(self, NetMethod::Delete, url)
|
||||
}
|
||||
|
||||
/// Starts building an http GET request for the URL.
|
||||
#[must_use]
|
||||
pub fn get(&self, url: impl Into<String>) -> ReqBuilder {
|
||||
ReqBuilder::new(self, NetMethod::Get, url)
|
||||
}
|
||||
|
||||
/// Starts building an http HEAD request for the URL.
|
||||
#[must_use]
|
||||
pub fn head(&self, url: impl Into<String>) -> ReqBuilder {
|
||||
ReqBuilder::new(self, NetMethod::Head, url)
|
||||
}
|
||||
|
||||
/// Starts building an http PATCH request for the URL.
|
||||
#[must_use]
|
||||
pub fn patch(&self, url: impl Into<String>) -> ReqBuilder {
|
||||
ReqBuilder::new(self, NetMethod::Patch, url)
|
||||
}
|
||||
|
||||
/// Starts building an http POST request for the URL.
|
||||
#[must_use]
|
||||
pub fn post(&self, url: impl Into<String>) -> ReqBuilder {
|
||||
ReqBuilder::new(self, NetMethod::Post, url)
|
||||
}
|
||||
|
||||
/// Starts building an http PUT request for the URL.
|
||||
#[must_use]
|
||||
pub fn put(&self, url: impl Into<String>) -> ReqBuilder {
|
||||
ReqBuilder::new(self, NetMethod::Put, url)
|
||||
}
|
||||
}
|
||||
impl MockNet {
|
||||
pub async fn try_from(net: Net) -> std::result::Result<Self, super::Error> {
|
||||
|
@ -123,6 +195,120 @@ impl MockNet {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Display, PartialEq, Eq)]
|
||||
pub enum NetMethod {
|
||||
Delete,
|
||||
Get,
|
||||
Head,
|
||||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
}
|
||||
impl From<&NetMethod> for http::Method {
|
||||
fn from(value: &NetMethod) -> Self {
|
||||
match value {
|
||||
NetMethod::Delete => http::Method::DELETE,
|
||||
NetMethod::Get => http::Method::GET,
|
||||
NetMethod::Head => http::Method::HEAD,
|
||||
NetMethod::Patch => http::Method::PATCH,
|
||||
NetMethod::Post => http::Method::POST,
|
||||
NetMethod::Put => http::Method::PUT,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A builder for an http request.
|
||||
pub struct ReqBuilder<'net> {
|
||||
net: &'net Net,
|
||||
url: String,
|
||||
method: NetMethod,
|
||||
headers: Vec<(String, String)>,
|
||||
body: Option<Bytes>,
|
||||
}
|
||||
impl<'net> ReqBuilder<'net> {
|
||||
#[must_use]
|
||||
fn new(net: &'net Net, method: NetMethod, url: impl Into<String>) -> Self {
|
||||
Self {
|
||||
net,
|
||||
url: url.into(),
|
||||
method,
|
||||
headers: vec![],
|
||||
body: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs the Request and sends it to the target URL, returning a
|
||||
/// future Response.
|
||||
///
|
||||
/// However, if this request is from a [Net] that was created from a [MockNet],
|
||||
/// then the request will be matched and any stored response returned, or an
|
||||
/// error if no matched request was found.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails if there was an error while sending request,
|
||||
/// redirect loop was detected or redirect limit was exhausted.
|
||||
/// If the response has a Status Code of `4xx` or `5xx` then the
|
||||
/// response will be returned as an [Error::ResponseError].
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use kxio::net::Result;
|
||||
/// # async fn run() -> Result<()> {
|
||||
/// let net = kxio::net::new();
|
||||
/// let response = net.get("https://hyper.rs")
|
||||
/// .header("foo", "bar")
|
||||
/// .body("{}")
|
||||
/// .send().await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn send(self) -> Result<Response> {
|
||||
let client = self.net.client();
|
||||
// Method
|
||||
let mut req = match self.method {
|
||||
NetMethod::Delete => client.delete(self.url),
|
||||
NetMethod::Get => client.get(self.url),
|
||||
NetMethod::Head => client.head(self.url),
|
||||
NetMethod::Patch => client.patch(self.url),
|
||||
NetMethod::Post => client.post(self.url),
|
||||
NetMethod::Put => client.put(self.url),
|
||||
};
|
||||
// Headers
|
||||
for (name, value) in self.headers.into_iter() {
|
||||
req = req.header(name, value);
|
||||
}
|
||||
// Body
|
||||
if let Some(bytes) = self.body {
|
||||
req = req.body(bytes);
|
||||
}
|
||||
|
||||
self.net.send(req).await
|
||||
}
|
||||
|
||||
/// Adds the header and value to the request.
|
||||
#[must_use]
|
||||
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
self.headers.push((name.into(), value.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds the headers to the request.
|
||||
#[must_use]
|
||||
pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
|
||||
self.headers.extend(headers);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the request body.
|
||||
#[must_use]
|
||||
pub fn body(mut self, bytes: impl Into<Bytes>) -> Self {
|
||||
self.body = Some(bytes.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A struct for defining the expected requests and their responses that should be made
|
||||
/// during a test.
|
||||
///
|
||||
|
@ -133,14 +319,14 @@ impl MockNet {
|
|||
///
|
||||
/// ```rust
|
||||
/// # use kxio::net::Result;
|
||||
/// use kxio::net::StatusCode;
|
||||
/// # #[tokio::main]
|
||||
/// # async fn run() -> Result<()> {
|
||||
/// let mock_net = kxio::net::mock();
|
||||
/// let client = mock_net.client();
|
||||
/// // define an expected requet, and the response that should be returned
|
||||
/// mock_net.on()
|
||||
/// .get("https://hyper.rs")
|
||||
/// .respond(mock_net.response().status(200).body("Ok")?);
|
||||
/// mock_net.on().get("https://hyper.rs")
|
||||
/// .respond(StatusCode::OK).body("Ok");
|
||||
/// let net: kxio::net::Net = mock_net.into();
|
||||
/// // use 'net' in your program, by passing it as a reference
|
||||
///
|
||||
|
@ -174,17 +360,18 @@ impl MockNet {
|
|||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use kxio::net::StatusCode;
|
||||
/// # use kxio::net::Result;
|
||||
/// # fn run() -> Result<()> {
|
||||
/// let mock_net = kxio::net::mock();
|
||||
/// let client = mock_net.client();
|
||||
/// mock_net.on()
|
||||
/// .get("https://hyper.rs")
|
||||
/// .respond(mock_net.response().status(200).body("Ok")?);
|
||||
/// mock_net.on().get("https://hyper.rs")
|
||||
/// .respond(StatusCode::OK).body("Ok");
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn on(&self) -> WhenRequest {
|
||||
#[must_use]
|
||||
pub fn on(&self) -> WhenRequest<WhenBuildRequest> {
|
||||
WhenRequest::new(self)
|
||||
}
|
||||
|
||||
|
@ -192,11 +379,6 @@ impl MockNet {
|
|||
self.plans.borrow_mut().push(plan);
|
||||
}
|
||||
|
||||
/// Creates a [http::response::Builder] to be extended and returned by a mocked network request.
|
||||
pub fn response(&self) -> http::response::Builder {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Clears all the expected requests and responses from the [MockNet].
|
||||
///
|
||||
/// When the [MockNet] goes out of scope it will assert that all expected requests and
|
||||
|
@ -237,62 +419,135 @@ impl Drop for MockNet {
|
|||
impl Drop for Net {
|
||||
fn drop(&mut self) {
|
||||
if let Some(plans) = &self.plans {
|
||||
assert!(plans.try_lock().expect("lock plans").take().is_empty())
|
||||
let unused = plans.try_lock().expect("lock plans").take();
|
||||
if unused.is_empty() {
|
||||
return; // all good
|
||||
}
|
||||
eprintln!("These requests were expected, but not made:");
|
||||
for plan in unused {
|
||||
eprintln!("-{plan}");
|
||||
}
|
||||
panic!("There were expected requests that were not made.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MatchRequest {
|
||||
Method(Method),
|
||||
Method(NetMethod),
|
||||
Url(Url),
|
||||
Header { name: String, value: String },
|
||||
Body(String),
|
||||
Body(bytes::Bytes),
|
||||
}
|
||||
impl Display for MatchRequest {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Method(method) => write!(f, "{method}"),
|
||||
Self::Url(url) => write!(f, "{url}"),
|
||||
Self::Header { name, value } => write!(f, "({name}: {value})"),
|
||||
Self::Body(body) => write!(f, "Body: {body:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RespondWith {
|
||||
Status(StatusCode),
|
||||
Header { name: String, value: String },
|
||||
Body(bytes::Bytes),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Display, From)]
|
||||
enum MockError {
|
||||
pub enum MockError {
|
||||
#[display("url parse: {}", 0)]
|
||||
UrlParse(#[from] url::ParseError),
|
||||
}
|
||||
impl std::error::Error for MockError {}
|
||||
|
||||
pub trait WhenState {}
|
||||
|
||||
pub struct WhenBuildRequest;
|
||||
impl WhenState for WhenBuildRequest {}
|
||||
|
||||
pub struct WhenBuildResponse;
|
||||
impl WhenState for WhenBuildResponse {}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WhenRequest<'net> {
|
||||
pub struct WhenRequest<'net, State>
|
||||
where
|
||||
State: WhenState,
|
||||
{
|
||||
_state: PhantomData<State>,
|
||||
net: &'net MockNet,
|
||||
match_on: Vec<MatchRequest>,
|
||||
errors: Vec<MockError>,
|
||||
respond_with: Vec<RespondWith>,
|
||||
error: Option<MockError>,
|
||||
}
|
||||
|
||||
impl<'net> WhenRequest<'net> {
|
||||
pub fn get(self, url: impl Into<String>) -> Self {
|
||||
self._url(Method::GET, url)
|
||||
}
|
||||
pub fn post(self, url: impl Into<String>) -> Self {
|
||||
self._url(Method::POST, url)
|
||||
}
|
||||
pub fn put(self, url: impl Into<String>) -> Self {
|
||||
self._url(Method::PUT, url)
|
||||
}
|
||||
pub fn delete(self, url: impl Into<String>) -> Self {
|
||||
self._url(Method::DELETE, url)
|
||||
}
|
||||
pub fn head(self, url: impl Into<String>) -> Self {
|
||||
self._url(Method::HEAD, url)
|
||||
}
|
||||
pub fn patch(self, url: impl Into<String>) -> Self {
|
||||
self._url(Method::PATCH, url)
|
||||
impl<'net> WhenRequest<'net, WhenBuildRequest> {
|
||||
fn new(net: &'net MockNet) -> Self {
|
||||
Self {
|
||||
_state: PhantomData,
|
||||
net,
|
||||
match_on: vec![],
|
||||
respond_with: vec![],
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn _url(mut self, method: http::Method, url: impl Into<String>) -> Self {
|
||||
/// Starts mocking a GET http request.
|
||||
#[must_use]
|
||||
pub fn get(self, url: impl Into<String>) -> Self {
|
||||
self._url(NetMethod::Get, url)
|
||||
}
|
||||
|
||||
/// Starts mocking a POST http request.
|
||||
#[must_use]
|
||||
pub fn post(self, url: impl Into<String>) -> Self {
|
||||
self._url(NetMethod::Post, url)
|
||||
}
|
||||
|
||||
/// Starts mocking a PUT http request.
|
||||
#[must_use]
|
||||
pub fn put(self, url: impl Into<String>) -> Self {
|
||||
self._url(NetMethod::Put, url)
|
||||
}
|
||||
|
||||
/// Starts mocking a DELETE http request.
|
||||
#[must_use]
|
||||
pub fn delete(self, url: impl Into<String>) -> Self {
|
||||
self._url(NetMethod::Delete, url)
|
||||
}
|
||||
|
||||
/// Starts mocking a HEAD http request.
|
||||
#[must_use]
|
||||
pub fn head(self, url: impl Into<String>) -> Self {
|
||||
self._url(NetMethod::Head, url)
|
||||
}
|
||||
|
||||
/// Starts mocking a PATCH http request.
|
||||
#[must_use]
|
||||
pub fn patch(self, url: impl Into<String>) -> Self {
|
||||
self._url(NetMethod::Patch, url)
|
||||
}
|
||||
|
||||
fn _url(mut self, method: NetMethod, url: impl Into<String>) -> Self {
|
||||
self.match_on.push(MatchRequest::Method(method));
|
||||
match Url::parse(&url.into()) {
|
||||
Ok(url) => {
|
||||
self.match_on.push(MatchRequest::Url(url));
|
||||
}
|
||||
Err(err) => self.errors.push(err.into()),
|
||||
Err(err) => {
|
||||
self.error.replace(err.into());
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Specifies a header that the mock will match against.
|
||||
///
|
||||
/// Any request that does not have this header will not match the mock.
|
||||
#[must_use]
|
||||
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
self.match_on.push(MatchRequest::Header {
|
||||
name: name.into(),
|
||||
|
@ -300,26 +555,90 @@ impl<'net> WhenRequest<'net> {
|
|||
});
|
||||
self
|
||||
}
|
||||
pub fn body(mut self, body: impl Into<String>) -> Self {
|
||||
|
||||
/// Specifies headers that the mock will match against.
|
||||
///
|
||||
/// Any request that does not have this header will not match the mock.
|
||||
#[must_use]
|
||||
pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
|
||||
for (name, value) in headers {
|
||||
self.match_on.push(MatchRequest::Header { name, value });
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Specifies the body that the mock will match against.
|
||||
///
|
||||
/// Any request that does not have this body will not match the mock.
|
||||
#[must_use]
|
||||
pub fn body(mut self, body: impl Into<bytes::Bytes>) -> Self {
|
||||
self.match_on.push(MatchRequest::Body(body.into()));
|
||||
self
|
||||
}
|
||||
pub fn respond<T>(self, response: http::Response<T>)
|
||||
where
|
||||
T: Into<reqwest::Body>,
|
||||
{
|
||||
|
||||
/// Specifies the http Status Code that will be returned for the matching request.
|
||||
#[must_use]
|
||||
pub fn respond(self, status: StatusCode) -> WhenRequest<'net, WhenBuildResponse> {
|
||||
WhenRequest::<WhenBuildResponse> {
|
||||
_state: PhantomData,
|
||||
net: self.net,
|
||||
match_on: self.match_on,
|
||||
respond_with: vec![RespondWith::Status(status)],
|
||||
error: self.error,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<'net> WhenRequest<'net, WhenBuildResponse> {
|
||||
/// Specifies a header that will be on the response sent for the matching request.
|
||||
#[must_use]
|
||||
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
let name = name.into();
|
||||
let value = value.into();
|
||||
self.respond_with.push(RespondWith::Header { name, value });
|
||||
self
|
||||
}
|
||||
|
||||
/// Specifies headers that will be on the response sent for the matching request.
|
||||
#[must_use]
|
||||
pub fn headers(mut self, headers: impl Into<HashMap<String, String>>) -> Self {
|
||||
let h: HashMap<String, String> = headers.into();
|
||||
for (name, value) in h.into_iter() {
|
||||
self.respond_with.push(RespondWith::Header { name, value });
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Specifies the body of the response sent for the matching request.
|
||||
pub fn body(mut self, body: impl Into<bytes::Bytes>) -> Result<()> {
|
||||
self.respond_with.push(RespondWith::Body(body.into()));
|
||||
self.mock()
|
||||
}
|
||||
|
||||
/// Marks a response that has no body as complete.
|
||||
pub fn mock(self) -> Result<()> {
|
||||
if let Some(error) = self.error {
|
||||
return Err(crate::net::Error::InvalidMock(error));
|
||||
}
|
||||
let mut builder = http::response::Builder::default();
|
||||
let mut response_body = None;
|
||||
for part in self.respond_with {
|
||||
builder = match part {
|
||||
RespondWith::Status(status) => builder.status(status),
|
||||
RespondWith::Header { name, value } => builder.header(name, value),
|
||||
RespondWith::Body(body) => {
|
||||
response_body.replace(body);
|
||||
builder
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let body = response_body.unwrap_or_default();
|
||||
let response = builder.body(body)?;
|
||||
self.net._when(Plan {
|
||||
match_request: self.match_on,
|
||||
response: response.into(),
|
||||
});
|
||||
}
|
||||
|
||||
fn new(net: &'net MockNet) -> Self {
|
||||
Self {
|
||||
net,
|
||||
match_on: vec![],
|
||||
errors: vec![],
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -9,6 +9,13 @@ mod path {
|
|||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn temp_as_real() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
let read = fs.as_real();
|
||||
|
||||
assert_eq!(read.base(), fs.base());
|
||||
}
|
||||
mod is_link {
|
||||
use super::*;
|
||||
|
||||
|
|
123
tests/net.rs
123
tests/net.rs
|
@ -1,3 +1,6 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
use http::StatusCode;
|
||||
//
|
||||
use kxio::net::{Error, MockNet, Net};
|
||||
|
||||
|
@ -7,25 +10,20 @@ use assert2::let_assert;
|
|||
async fn test_get_url() {
|
||||
//given
|
||||
let mock_net = kxio::net::mock();
|
||||
let client = mock_net.client();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
let my_response = mock_net
|
||||
.response()
|
||||
.status(200)
|
||||
.body("Get OK")
|
||||
.expect("body");
|
||||
|
||||
mock_net
|
||||
.on()
|
||||
.get("https://www.example.com")
|
||||
.respond(my_response);
|
||||
.get(url)
|
||||
.respond(StatusCode::OK)
|
||||
.header("foo", "bar")
|
||||
.headers(HashMap::new())
|
||||
.body("Get OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(mock_net)
|
||||
.send(client.get(url))
|
||||
.await
|
||||
.expect("response");
|
||||
let response = Net::from(mock_net).get(url).send().await.expect("response");
|
||||
|
||||
//then
|
||||
assert_eq!(response.status(), http::StatusCode::OK);
|
||||
|
@ -42,7 +40,9 @@ async fn test_post_url() {
|
|||
|
||||
net.on()
|
||||
.post(url)
|
||||
.respond(net.response().status(200).body("post OK").expect("body"));
|
||||
.respond(StatusCode::OK)
|
||||
.body("post OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
|
@ -65,7 +65,9 @@ async fn test_put_url() {
|
|||
|
||||
net.on()
|
||||
.put(url)
|
||||
.respond(net.response().status(200).body("put OK").expect("body"));
|
||||
.respond(StatusCode::OK)
|
||||
.body("put OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net).send(client.put(url)).await.expect("reponse");
|
||||
|
@ -85,7 +87,9 @@ async fn test_delete_url() {
|
|||
|
||||
net.on()
|
||||
.delete(url)
|
||||
.respond(net.response().status(200).body("delete OK").expect("body"));
|
||||
.respond(StatusCode::OK)
|
||||
.body("delete OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
|
@ -108,7 +112,9 @@ async fn test_head_url() {
|
|||
|
||||
net.on()
|
||||
.head(url)
|
||||
.respond(net.response().status(200).body("head OK").expect("body"));
|
||||
.respond(StatusCode::OK)
|
||||
.body("head OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
|
@ -131,7 +137,9 @@ async fn test_patch_url() {
|
|||
|
||||
net.on()
|
||||
.patch(url)
|
||||
.respond(net.response().status(200).body("patch OK").expect("body"));
|
||||
.respond(StatusCode::OK)
|
||||
.body("patch OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
|
@ -147,19 +155,18 @@ async fn test_patch_url() {
|
|||
#[tokio::test]
|
||||
async fn test_get_wrong_url() {
|
||||
//given
|
||||
let mock_net = kxio::net::mock();
|
||||
let client = mock_net.client();
|
||||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
let my_response = mock_net
|
||||
.response()
|
||||
.status(200)
|
||||
|
||||
net.on()
|
||||
.get(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("Get OK")
|
||||
.expect("body");
|
||||
.expect("mock");
|
||||
|
||||
mock_net.on().get(url).respond(my_response);
|
||||
|
||||
let net = Net::from(mock_net);
|
||||
let net = Net::from(net);
|
||||
|
||||
//when
|
||||
let_assert!(
|
||||
|
@ -181,11 +188,8 @@ async fn test_post_by_method() {
|
|||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let my_response = net.response().status(200).body("").expect("response body");
|
||||
|
||||
net.on()
|
||||
// NOTE: No URL specified - so should match any URL
|
||||
.respond(my_response);
|
||||
// NOTE: No URL specified - so should match any URL
|
||||
net.on().respond(StatusCode::OK).body("").expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
|
@ -204,16 +208,12 @@ async fn test_post_by_body() {
|
|||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let my_response = net
|
||||
.response()
|
||||
.status(200)
|
||||
.body("response body")
|
||||
.expect("body");
|
||||
|
||||
// No URL - so any POST with a matching body
|
||||
net.on()
|
||||
// No URL - so any POST with a matching body
|
||||
.body("match on body")
|
||||
.respond(my_response);
|
||||
.respond(StatusCode::OK)
|
||||
.body("response body")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
|
@ -235,13 +235,11 @@ async fn test_post_by_header() {
|
|||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let my_response = net
|
||||
.response()
|
||||
.status(200)
|
||||
net.on()
|
||||
.header("test", "match")
|
||||
.respond(StatusCode::OK)
|
||||
.body("response body")
|
||||
.expect("body");
|
||||
|
||||
net.on().header("test", "match").respond(my_response);
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
|
@ -268,13 +266,12 @@ async fn test_post_by_header_wrong_value() {
|
|||
let mock_net = kxio::net::mock();
|
||||
let client = mock_net.client();
|
||||
|
||||
let my_response = mock_net
|
||||
.response()
|
||||
.status(200)
|
||||
mock_net
|
||||
.on()
|
||||
.header("test", "match")
|
||||
.respond(StatusCode::OK)
|
||||
.body("response body")
|
||||
.expect("body");
|
||||
|
||||
mock_net.on().header("test", "match").respond(my_response);
|
||||
.expect("mock");
|
||||
let net = Net::from(mock_net);
|
||||
|
||||
//when
|
||||
|
@ -300,13 +297,13 @@ async fn test_unused_post_as_net() {
|
|||
let mock_net = kxio::net::mock();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
let my_response = mock_net
|
||||
.response()
|
||||
.status(200)
|
||||
.body("Post OK")
|
||||
.expect("body");
|
||||
|
||||
mock_net.on().post(url).respond(my_response);
|
||||
mock_net
|
||||
.on()
|
||||
.post(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("Post OK")
|
||||
.expect("mock");
|
||||
|
||||
let _net = Net::from(mock_net);
|
||||
|
||||
|
@ -325,13 +322,13 @@ async fn test_unused_post_as_mocknet() {
|
|||
let mock_net = kxio::net::mock();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
let my_response = mock_net
|
||||
.response()
|
||||
.status(200)
|
||||
.body("Post OK")
|
||||
.expect("body");
|
||||
|
||||
mock_net.on().post(url).respond(my_response);
|
||||
mock_net
|
||||
.on()
|
||||
.post(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("Post OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
// don't send the planned request
|
||||
|
|
Loading…
Reference in a new issue