kxio/src/net/system.rs

304 lines
8.6 KiB
Rust
Raw Normal View History

//
2024-11-11 07:44:43 +00:00
use std::cell::RefCell;
use reqwest::{Body, Client};
use crate::net::{Method, Request, RequestBuilder, Response, Url};
use super::{Error, Result};
2024-11-09 21:07:43 +00:00
/// A list of planned requests and responses
type Plans = Vec<Plan>;
2024-11-09 21:07:43 +00:00
/// The different ways to match a request.
#[derive(Debug, PartialEq, Eq)]
pub enum MatchOn {
2024-11-09 21:07:43 +00:00
/// The request must have a specific HTTP Request Method.
Method,
2024-11-09 21:07:43 +00:00
/// The request must have a specific URL.
Url,
2024-11-09 21:07:43 +00:00
/// The request must have a specify HTTP Body.
Body,
2024-11-09 21:07:43 +00:00
/// The request must have a specific set of HTTP Headers.
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.
struct Plan {
match_request: Vec<MatchRequest>,
response: Response,
}
impl Plan {
fn matches(&self, request: &Request) -> bool {
self.match_request.iter().all(|criteria| match criteria {
MatchRequest::Method(method) => request.method() == method,
MatchRequest::Url(uri) => request.url() == uri,
MatchRequest::Header { name, value } => {
request
.headers()
.iter()
.any(|(request_header_name, request_header_value)| {
let Ok(request_header_value) = request_header_value.to_str() else {
return false;
};
request_header_name.as_str() == name && request_header_value == value
})
}
MatchRequest::Body(body) => {
request.body().and_then(Body::as_bytes) == Some(body.as_bytes())
}
})
}
}
2024-11-10 17:11:54 +00:00
/// An abstraction for the network
pub struct Net {
2024-11-11 07:44:43 +00:00
plans: Option<RefCell<Plans>>,
}
impl Net {
2024-11-09 21:07:43 +00:00
/// Creates a new unmocked [Net] for creating real network requests.
pub(super) const fn new() -> Self {
2024-11-11 07:44:43 +00:00
Self { plans: None }
}
2024-11-09 21:07:43 +00:00
/// Creats a new [MockNet] for use in tests.
pub(super) const fn mock() -> MockNet {
MockNet {
2024-11-11 07:44:43 +00:00
plans: RefCell::new(vec![]),
}
}
}
impl Net {
/// Helper to create a default [Client].
2024-11-09 21:07:43 +00:00
///
/// # Example
///
/// ```rust
/// # use kxio::net::Result;
/// let net = kxio::net::new();
/// let client = net.client();
/// let request = client.get("https://hyper.rs");
/// ```
pub fn client(&self) -> Client {
Default::default()
}
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(())
/// # }
/// ```
pub async fn send(&self, request: impl Into<RequestBuilder>) -> Result<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| plan.matches(&request));
2024-11-11 07:44:43 +00:00
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
}
}
}
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()),
}),
None => Err(Self::Error::NetIsNotAMock),
}
}
}
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::{Method, Url};
2024-11-09 21:07:43 +00:00
/// # 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(Method::GET)
/// .url(Url::parse("https://hyper.rs")?)
/// .respond(mock_net.response().status(200).body("Ok")?);
2024-11-09 21:07:43 +00:00
/// 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(())
/// # }
/// ```
pub struct MockNet {
2024-11-11 07:44:43 +00:00
plans: RefCell<Plans>,
}
impl MockNet {
/// Helper to create a default [Client].
2024-11-09 21:07:43 +00:00
///
/// # Example
///
/// ```rust
/// let mock_net = kxio::net::mock();
/// let client = mock_net.client();
/// let request = client.get("https://hyper.rs");
/// ```
pub fn client(&self) -> Client {
Default::default()
}
2024-11-09 21:07:43 +00:00
/// Specify an expected request.
///
/// # Example
///
/// ```rust
/// use kxio::net::{Method, Url};
2024-11-09 21:07:43 +00:00
/// # use kxio::net::Result;
/// # fn run() -> Result<()> {
/// let mock_net = kxio::net::mock();
/// let client = mock_net.client();
/// mock_net.on(Method::GET)
/// .url(Url::parse("https://hyper.rs")?)
/// .respond(mock_net.response().status(200).body("Ok")?);
2024-11-09 21:07:43 +00:00
/// # Ok(())
/// # }
/// ```
pub fn on(&self, method: impl Into<Method>) -> WhenRequest {
WhenRequest::new(self, method)
2024-11-11 07:44:43 +00:00
}
fn _when(&self, plan: Plan) {
self.plans.borrow_mut().push(plan);
}
2024-11-09 21:07:43 +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();
}
}
impl From<MockNet> for Net {
fn from(mock_net: MockNet) -> Self {
Self {
// 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-11 07:44:43 +00:00
impl Drop for MockNet {
fn drop(&mut self) {
assert!(self.plans.borrow().is_empty())
}
}
2024-11-11 07:44:43 +00:00
impl Drop for Net {
fn drop(&mut self) {
2024-11-11 07:44:43 +00:00
if let Some(plans) = &self.plans {
assert!(plans.borrow().is_empty())
}
}
}
pub enum MatchRequest {
Method(Method),
Url(Url),
Header { name: String, value: String },
Body(String),
}
2024-11-09 21:07:43 +00:00
pub struct WhenRequest<'net> {
net: &'net MockNet,
match_on: Vec<MatchRequest>,
}
2024-11-09 21:07:43 +00:00
impl<'net> WhenRequest<'net> {
pub fn url(mut self, url: impl Into<Url>) -> Self {
self.match_on.push(MatchRequest::Url(url.into()));
self
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.match_on.push(MatchRequest::Header {
name: name.into(),
value: value.into(),
});
self
}
pub fn body(mut self, body: impl Into<String>) -> Self {
self.match_on.push(MatchRequest::Body(body.into()));
self
}
pub fn respond<T>(self, response: http::Response<T>)
2024-11-10 17:11:54 +00:00
where
T: Into<reqwest::Body>,
{
self.net._when(Plan {
match_request: self.match_on,
response: response.into(),
});
}
fn new(net: &'net MockNet, method: impl Into<Method>) -> Self {
Self {
net,
match_on: vec![MatchRequest::Method(method.into())],
2024-11-10 17:11:54 +00:00
}
}
}