Compare commits
5 commits
edf5af2e63
...
7dc87860c3
Author | SHA1 | Date | |
---|---|---|---|
7dc87860c3 | |||
3890a6cc4d | |||
cd4d25d125 | |||
4bd3d5a91d | |||
c82e6575ef |
1 changed files with 77 additions and 0 deletions
77
src/net/mock.rs
Normal file
77
src/net/mock.rs
Normal file
|
@ -0,0 +1,77 @@
|
||||||
|
//
|
||||||
|
use super::{Error, Net, Result};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Plan {
|
||||||
|
request: reqwest::Request,
|
||||||
|
response: reqwest::Response,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug)]
|
||||||
|
pub struct MockNet {
|
||||||
|
plans: Vec<Plan>,
|
||||||
|
}
|
||||||
|
impl MockNet {
|
||||||
|
pub(crate) fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn into_net(self) -> Net {
|
||||||
|
Net::mock(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn client(&self) -> reqwest::Client {
|
||||||
|
reqwest::Client::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn response(&self) -> http::response::Builder {
|
||||||
|
http::Response::builder()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn on(&mut self, request: reqwest::Request) -> OnRequest {
|
||||||
|
OnRequest {
|
||||||
|
mock: self,
|
||||||
|
request,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn _on(&mut self, request: reqwest::Request, response: reqwest::Response) {
|
||||||
|
self.plans.push(Plan { request, response })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn send(
|
||||||
|
&mut self,
|
||||||
|
request: reqwest::RequestBuilder,
|
||||||
|
) -> Result<reqwest::Response> {
|
||||||
|
let request = request.build()?;
|
||||||
|
let index = self.plans.iter().position(|plan| {
|
||||||
|
// TODO: add support or only matching on selected criteria
|
||||||
|
plan.request.method() == request.method()
|
||||||
|
&& plan.request.url() == request.url()
|
||||||
|
&& match (plan.request.body(), request.body()) {
|
||||||
|
(None, None) => true,
|
||||||
|
(Some(plan), Some(request)) => plan.as_bytes() == request.as_bytes(),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
&& plan.request.headers() == request.headers()
|
||||||
|
});
|
||||||
|
match index {
|
||||||
|
Some(i) => Ok(self.plans.remove(i).response),
|
||||||
|
None => Err(Error::UnexpectedMockRequest(request)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn assert(&self) -> Result<()> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct OnRequest<'mock> {
|
||||||
|
mock: &'mock mut MockNet,
|
||||||
|
request: reqwest::Request,
|
||||||
|
}
|
||||||
|
impl<'mock> OnRequest<'mock> {
|
||||||
|
pub fn response(self, response: reqwest::Response) {
|
||||||
|
self.mock._on(self.request, response)
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue