kxio/src/net/system.rs

150 lines
3.6 KiB
Rust
Raw Normal View History

//
use std::marker::PhantomData;
use super::{Error, Result};
pub trait NetType {}
pub struct Mocked;
impl NetType for Mocked {}
pub struct Unmocked;
impl NetType for Unmocked {}
type Plans = Vec<Plan>;
#[derive(Debug, PartialEq, Eq)]
pub enum MatchOn {
Method,
Url,
Body,
Headers,
}
#[derive(Debug)]
pub struct Plan {
request: reqwest::Request,
response: reqwest::Response,
match_on: Vec<MatchOn>,
}
pub struct Net<T: NetType> {
_type: PhantomData<T>,
plans: Plans,
}
impl Net<Unmocked> {
pub(crate) const fn new() -> Self {
Self {
_type: PhantomData,
plans: vec![],
}
}
pub async fn send(&mut self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> {
request.send().await.map_err(Error::from)
}
}
impl<T: NetType> Net<T> {
pub fn client(&self) -> reqwest::Client {
Default::default()
}
}
impl Net<Mocked> {
pub(crate) const fn new() -> Self {
Self {
_type: PhantomData,
plans: vec![],
}
}
pub async fn send(&mut self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> {
let request = request.build()?;
let index = self.plans.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) => Ok(self.plans.remove(i).response),
None => Err(Error::UnexpectedMockRequest(request)),
}
}
/// Creates a [ResponseBuilder] to be extended and returned by a mocked network request.
pub fn response(&self) -> http::response::Builder {
Default::default()
}
pub fn on(&mut self, request: reqwest::Request) -> OnRequest {
OnRequest {
net: self,
request,
match_on: vec![MatchOn::Method, MatchOn::Url],
}
}
fn _on(
&mut self,
request: reqwest::Request,
response: reqwest::Response,
match_on: Vec<MatchOn>,
) {
self.plans.push(Plan {
request,
response,
match_on,
})
}
pub fn reset(&mut self) {
self.plans = vec![];
}
}
impl<T: NetType> Drop for Net<T> {
fn drop(&mut self) {
assert!(self.plans.is_empty())
}
}
pub struct OnRequest<'net> {
net: &'net mut Net<Mocked>,
request: reqwest::Request,
match_on: Vec<MatchOn>,
}
impl<'net> OnRequest<'net> {
pub fn match_on(self, match_on: Vec<MatchOn>) -> Self {
Self {
net: self.net,
request: self.request,
match_on,
}
}
pub fn respond(self, response: reqwest::Response) {
self.net._on(self.request, response, self.match_on)
}
}