2024-11-04 10:22:31 +00:00
|
|
|
//
|
2024-11-11 07:44:43 +00:00
|
|
|
use std::cell::RefCell;
|
2024-11-10 09:44:30 +00:00
|
|
|
|
|
|
|
use reqwest::Client;
|
2024-11-04 10:22:31 +00:00
|
|
|
|
|
|
|
use super::{Error, Result};
|
|
|
|
|
2024-11-09 21:07:43 +00:00
|
|
|
/// A list of planned requests and responses
|
2024-11-04 10:22:31 +00:00
|
|
|
type Plans = Vec<Plan>;
|
|
|
|
|
2024-11-09 21:07:43 +00:00
|
|
|
/// The different ways to match a request.
|
2024-11-04 10:22:31 +00:00
|
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
|
|
pub enum MatchOn {
|
2024-11-09 21:07:43 +00:00
|
|
|
/// The request must have a specific HTTP Request Method.
|
2024-11-04 10:22:31 +00:00
|
|
|
Method,
|
2024-11-09 21:07:43 +00:00
|
|
|
|
|
|
|
/// The request must have a specific URL.
|
2024-11-04 10:22:31 +00:00
|
|
|
Url,
|
2024-11-09 21:07:43 +00:00
|
|
|
|
|
|
|
/// The request must have a specify HTTP Body.
|
2024-11-04 10:22:31 +00:00
|
|
|
Body,
|
2024-11-09 21:07:43 +00:00
|
|
|
|
|
|
|
/// The request must have a specific set of HTTP Headers.
|
2024-11-04 10:22:31 +00:00
|
|
|
Headers,
|
|
|
|
}
|
|
|
|
|
2024-11-09 21:07:43 +00:00
|
|
|
/// A planned request and the response to return
|
|
|
|
///
|
|
|
|
/// Contains a list of the criteria that a request must meet before being considered a match.
|
2024-11-04 10:22:31 +00:00
|
|
|
#[derive(Debug)]
|
2024-11-09 12:12:11 +00:00
|
|
|
struct Plan {
|
2024-11-04 10:22:31 +00:00
|
|
|
request: reqwest::Request,
|
|
|
|
response: reqwest::Response,
|
|
|
|
match_on: Vec<MatchOn>,
|
|
|
|
}
|
|
|
|
|
2024-11-10 17:11:54 +00:00
|
|
|
/// An abstraction for the network
|
2024-11-09 12:12:11 +00:00
|
|
|
pub struct Net {
|
2024-11-11 07:44:43 +00:00
|
|
|
plans: Option<RefCell<Plans>>,
|
2024-11-09 12:12:11 +00:00
|
|
|
}
|
|
|
|
impl Net {
|
2024-11-09 21:07:43 +00:00
|
|
|
/// Creates a new unmocked [Net] for creating real network requests.
|
2024-11-09 12:12:11 +00:00
|
|
|
pub(super) const fn new() -> Self {
|
2024-11-11 07:44:43 +00:00
|
|
|
Self { plans: None }
|
2024-11-09 12:12:11 +00:00
|
|
|
}
|
|
|
|
|
2024-11-09 21:07:43 +00:00
|
|
|
/// Creats a new [MockNet] for use in tests.
|
2024-11-09 12:12:11 +00:00
|
|
|
pub(super) const fn mock() -> MockNet {
|
|
|
|
MockNet {
|
2024-11-11 07:44:43 +00:00
|
|
|
plans: RefCell::new(vec![]),
|
2024-11-09 12:12:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
impl Net {
|
2024-11-09 21:07:43 +00:00
|
|
|
/// Helper to create a default [reqwest::Client].
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use kxio::net::Result;
|
|
|
|
/// let net = kxio::net::new();
|
|
|
|
/// let client = net.client();
|
|
|
|
/// let request = client.get("https://hyper.rs");
|
|
|
|
/// ```
|
2024-11-09 12:12:11 +00:00
|
|
|
pub fn client(&self) -> reqwest::Client {
|
2024-11-09 17:19:42 +00:00
|
|
|
Default::default()
|
2024-11-09 12:12:11 +00:00
|
|
|
}
|
|
|
|
|
2024-11-09 21:07:43 +00:00
|
|
|
/// Constructs the Request and sends it to the target URL, returning a
|
|
|
|
/// future Response.
|
|
|
|
///
|
|
|
|
/// # Errors
|
|
|
|
///
|
|
|
|
/// This method fails if there was an error while sending request,
|
|
|
|
/// redirect loop was detected or redirect limit was exhausted.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```no_run
|
|
|
|
/// # use kxio::net::Result;
|
|
|
|
/// # async fn run() -> Result<()> {
|
|
|
|
/// let net = kxio::net::new();
|
|
|
|
/// let request = net.client().get("https://hyper.rs");
|
|
|
|
/// let response = net.send(request).await?;
|
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2024-11-10 09:44:30 +00:00
|
|
|
pub async fn send(
|
|
|
|
&self,
|
|
|
|
request: impl Into<reqwest::RequestBuilder>,
|
|
|
|
) -> Result<reqwest::Response> {
|
2024-11-11 07:44:43 +00:00
|
|
|
let Some(plans) = &self.plans else {
|
|
|
|
return request.into().send().await.map_err(Error::from);
|
|
|
|
};
|
|
|
|
let request = request.into().build()?;
|
|
|
|
let index = plans.borrow().iter().position(|plan| {
|
|
|
|
// METHOD
|
|
|
|
(if plan.match_on.contains(&MatchOn::Method) {
|
|
|
|
plan.request.method() == request.method()
|
|
|
|
} else {
|
|
|
|
true
|
|
|
|
})
|
|
|
|
// URL
|
|
|
|
&& (if plan.match_on.contains(&MatchOn::Url) {
|
|
|
|
plan.request.url() == request.url()
|
|
|
|
} else {
|
|
|
|
true
|
|
|
|
})
|
|
|
|
// BODY
|
|
|
|
&& (if plan.match_on.contains(&MatchOn::Body) {
|
|
|
|
match (plan.request.body(), request.body()) {
|
|
|
|
(None, None) => true,
|
|
|
|
(Some(plan), Some(req)) => plan.as_bytes().eq(&req.as_bytes()),
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
true
|
|
|
|
})
|
|
|
|
// HEADERS
|
|
|
|
&& (if plan.match_on.contains(&MatchOn::Headers) {
|
|
|
|
plan.request.headers() == request.headers()
|
|
|
|
} else {
|
|
|
|
true
|
|
|
|
})
|
|
|
|
});
|
|
|
|
match index {
|
|
|
|
Some(i) => {
|
|
|
|
let response = plans.borrow_mut().remove(i).response;
|
|
|
|
Ok(response)
|
|
|
|
}
|
|
|
|
None => Err(Error::UnexpectedMockRequest(request)),
|
2024-11-10 17:11:54 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-11-10 09:44:30 +00:00
|
|
|
impl TryFrom<Net> for MockNet {
|
|
|
|
type Error = super::Error;
|
|
|
|
|
|
|
|
fn try_from(net: Net) -> std::result::Result<Self, Self::Error> {
|
2024-11-11 07:44:43 +00:00
|
|
|
match &net.plans {
|
|
|
|
Some(plans) => Ok(MockNet {
|
|
|
|
plans: RefCell::new(plans.take()),
|
|
|
|
}),
|
2024-11-10 09:44:30 +00:00
|
|
|
None => Err(Self::Error::NetIsNotAMock),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-11-09 12:12:11 +00:00
|
|
|
|
2024-11-09 21:07:43 +00:00
|
|
|
/// A struct for defining the expected requests and their responses that should be made
|
|
|
|
/// during a test.
|
|
|
|
///
|
|
|
|
/// When the [MockNet] goes out of scope it will verify that all expected requests were consumed,
|
|
|
|
/// otherwise it will `panic`.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use kxio::net::Result;
|
|
|
|
/// # 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(client.get("https://hyper.rs"))
|
|
|
|
/// .respond_with_body(mock_net.response().status(200).body("Ok"))?;
|
|
|
|
/// let net: kxio::net::Net = mock_net.into();
|
|
|
|
/// // use 'net' in your program, by passing it as a reference
|
|
|
|
///
|
|
|
|
/// // In some rare cases you don't want to assert that all expected requests were made.
|
|
|
|
/// // You should recover the `MockNet` from the `Net` and `MockNet::reset` it.
|
|
|
|
/// let mock_net = kxio::net::MockNet::try_from(net)?;
|
|
|
|
/// mock_net.reset(); // only if explicitly needed
|
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2024-11-09 12:12:11 +00:00
|
|
|
pub struct MockNet {
|
2024-11-11 07:44:43 +00:00
|
|
|
plans: RefCell<Plans>,
|
2024-11-09 12:12:11 +00:00
|
|
|
}
|
2024-11-10 09:44:30 +00:00
|
|
|
impl MockNet {
|
2024-11-09 21:07:43 +00:00
|
|
|
/// Helper to create a default [reqwest::Client].
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// let mock_net = kxio::net::mock();
|
|
|
|
/// let client = mock_net.client();
|
|
|
|
/// let request = client.get("https://hyper.rs");
|
|
|
|
/// ```
|
2024-11-10 09:44:30 +00:00
|
|
|
pub fn client(&self) -> Client {
|
|
|
|
Default::default()
|
|
|
|
}
|
2024-11-09 21:07:43 +00:00
|
|
|
|
|
|
|
/// Specify an expected request.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use kxio::net::Result;
|
|
|
|
/// # fn run() -> Result<()> {
|
|
|
|
/// let mock_net = kxio::net::mock();
|
|
|
|
/// let client = mock_net.client();
|
|
|
|
/// mock_net.on(client.get("https://hyper.rs"))
|
|
|
|
/// .respond_with_body(mock_net.response().status(200).body("Ok"))?;
|
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2024-11-11 07:44:43 +00:00
|
|
|
pub fn on(&self, request_builder: impl Into<reqwest::RequestBuilder>) -> OnRequest {
|
|
|
|
match request_builder.into().build() {
|
|
|
|
Ok(request) => OnRequest::Valid {
|
|
|
|
net: self,
|
|
|
|
request,
|
|
|
|
match_on: vec![MatchOn::Method, MatchOn::Url],
|
|
|
|
},
|
|
|
|
Err(err) => OnRequest::Error(err.into()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn _on(
|
|
|
|
&self,
|
|
|
|
request: reqwest::Request,
|
|
|
|
response: reqwest::Response,
|
|
|
|
match_on: Vec<MatchOn>,
|
|
|
|
) -> Result<()> {
|
|
|
|
self.plans.borrow_mut().push(Plan {
|
|
|
|
request,
|
|
|
|
response,
|
|
|
|
match_on,
|
|
|
|
});
|
|
|
|
Ok(())
|
2024-11-10 09:44:30 +00:00
|
|
|
}
|
2024-11-09 21:07:43 +00:00
|
|
|
|
2024-11-10 09:44:30 +00:00
|
|
|
/// Creates a [http::response::Builder] to be extended and returned by a mocked network request.
|
|
|
|
pub fn response(&self) -> http::response::Builder {
|
|
|
|
Default::default()
|
|
|
|
}
|
2024-11-09 21:07:43 +00:00
|
|
|
|
|
|
|
/// 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
|
|
|
|
/// responses were consumed. If there are any left unconsumed, then it will `panic`.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use kxio::net::Result;
|
|
|
|
/// # fn run() -> Result<()> {
|
|
|
|
/// # let mock_net = kxio::net::mock();
|
|
|
|
/// # let net: kxio::net::Net = mock_net.into();
|
|
|
|
/// let mock_net = kxio::net::MockNet::try_from(net)?;
|
|
|
|
/// mock_net.reset(); // only if explicitly needed
|
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2024-11-11 07:44:43 +00:00
|
|
|
pub fn reset(&self) {
|
|
|
|
self.plans.take();
|
2024-11-09 12:12:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
impl From<MockNet> for Net {
|
|
|
|
fn from(mock_net: MockNet) -> Self {
|
|
|
|
Self {
|
2024-11-10 09:44:30 +00:00
|
|
|
// keep the original `inner` around to allow it's Drop impelmentation to run when we go
|
|
|
|
// out of scope at the end of the test
|
2024-11-11 07:44:43 +00:00
|
|
|
plans: Some(RefCell::new(mock_net.plans.take())),
|
2024-11-09 12:12:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-11 07:44:43 +00:00
|
|
|
impl Drop for MockNet {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
assert!(self.plans.borrow().is_empty())
|
2024-11-04 10:22:31 +00:00
|
|
|
}
|
|
|
|
}
|
2024-11-11 07:44:43 +00:00
|
|
|
impl Drop for Net {
|
2024-11-04 10:22:31 +00:00
|
|
|
fn drop(&mut self) {
|
2024-11-11 07:44:43 +00:00
|
|
|
if let Some(plans) = &self.plans {
|
|
|
|
assert!(plans.borrow().is_empty())
|
|
|
|
}
|
2024-11-04 10:22:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-09 21:07:43 +00:00
|
|
|
/// Intermediate struct used while declaring an expected request and its response.
|
2024-11-10 17:11:54 +00:00
|
|
|
pub enum OnRequest<'net> {
|
|
|
|
Valid {
|
2024-11-11 07:44:43 +00:00
|
|
|
net: &'net MockNet,
|
2024-11-10 17:11:54 +00:00
|
|
|
request: reqwest::Request,
|
|
|
|
match_on: Vec<MatchOn>,
|
|
|
|
},
|
|
|
|
Error(super::Error),
|
2024-11-04 10:22:31 +00:00
|
|
|
}
|
|
|
|
impl<'net> OnRequest<'net> {
|
2024-11-09 21:07:43 +00:00
|
|
|
/// Specify the criteria that a request should be compared against.
|
|
|
|
///
|
|
|
|
/// Given an candidate request, it will be matched against the current request if it has the
|
|
|
|
/// same HTTP Method and Url by default. i.e. if this method is not called.
|
|
|
|
///
|
|
|
|
/// All criteria must be met for the match to be made.
|
|
|
|
///
|
|
|
|
/// Calling this method replaces the default criteria with the new criteria.
|
2024-11-04 10:22:31 +00:00
|
|
|
pub fn match_on(self, match_on: Vec<MatchOn>) -> Self {
|
2024-11-10 17:11:54 +00:00
|
|
|
if let OnRequest::Valid {
|
|
|
|
net,
|
|
|
|
request,
|
|
|
|
match_on: _,
|
|
|
|
} = self
|
|
|
|
{
|
|
|
|
Self::Valid {
|
|
|
|
net,
|
|
|
|
request,
|
|
|
|
match_on,
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
2024-11-09 21:07:43 +00:00
|
|
|
|
|
|
|
/// Constructs the response to be returned when a request matched the criteria.
|
|
|
|
///
|
|
|
|
/// The response will have an empty HTTP Body.
|
|
|
|
///
|
|
|
|
/// Each request and response can only be matched once each.
|
2024-11-10 17:11:54 +00:00
|
|
|
pub fn respond(self, response: impl Into<http::response::Builder>) -> Result<()> {
|
|
|
|
match self {
|
|
|
|
OnRequest::Valid {
|
|
|
|
net: _,
|
|
|
|
request: _,
|
|
|
|
match_on: _,
|
|
|
|
} => self.respond_with_body(response.into().body("")),
|
|
|
|
OnRequest::Error(error) => Err(error),
|
2024-11-04 10:22:31 +00:00
|
|
|
}
|
|
|
|
}
|
2024-11-09 21:07:43 +00:00
|
|
|
|
|
|
|
/// Constructs the response to be returned when a request matched the criteria.
|
|
|
|
///
|
|
|
|
/// Each request and response can only be matched once each.
|
2024-11-10 17:11:54 +00:00
|
|
|
pub fn respond_with_body<T>(
|
|
|
|
self,
|
|
|
|
body_result: std::result::Result<http::Response<T>, http::Error>,
|
|
|
|
) -> Result<()>
|
|
|
|
where
|
|
|
|
T: Into<reqwest::Body>,
|
|
|
|
{
|
|
|
|
match body_result {
|
|
|
|
Ok(response) => match self {
|
|
|
|
OnRequest::Valid {
|
|
|
|
net,
|
|
|
|
request,
|
|
|
|
match_on,
|
|
|
|
} => net._on(request, response.into(), match_on),
|
|
|
|
OnRequest::Error(error) => Err(error),
|
|
|
|
},
|
|
|
|
Err(err) => Err(err.into()),
|
|
|
|
}
|
2024-11-04 10:22:31 +00:00
|
|
|
}
|
|
|
|
}
|