serenade_http_client/
mock.rs1use std::future::ready;
4use std::sync::Mutex;
5
6use crate::{ClientMethod, ClientRequest, ClientResponse, HttpClient, HttpClientError};
7
8type Matcher = Box<dyn Fn(&ClientRequest) -> bool + Send + Sync>;
9
10struct Expectation {
11 matcher: Matcher,
12 response: ClientResponse,
13 remaining: Option<usize>,
14}
15
16#[derive(Default)]
18pub struct MockHttpClient {
19 expectations: Mutex<Vec<Expectation>>,
20}
21
22impl MockHttpClient {
23 #[must_use]
25 pub fn new() -> Self {
26 Self::default()
27 }
28
29 pub fn expect(
35 &self,
36 method: ClientMethod,
37 url: impl Into<String>,
38 response: ClientResponse,
39 times: Option<usize>,
40 ) -> &Self {
41 let url = url.into();
42 self.expectations
43 .lock()
44 .expect("mock lock")
45 .push(Expectation {
46 matcher: Box::new(move |request| {
47 request.method() == method && request.url() == url
48 }),
49 response,
50 remaining: times,
51 });
52 self
53 }
54
55 pub fn expect_where(
61 &self,
62 matcher: impl Fn(&ClientRequest) -> bool + Send + Sync + 'static,
63 response: ClientResponse,
64 times: Option<usize>,
65 ) -> &Self {
66 self.expectations
67 .lock()
68 .expect("mock lock")
69 .push(Expectation {
70 matcher: Box::new(matcher),
71 response,
72 remaining: times,
73 });
74 self
75 }
76
77 fn resolve(&self, request: &ClientRequest) -> Result<ClientResponse, HttpClientError> {
78 let mut expectations = self.expectations.lock().expect("mock lock");
79 let position = expectations.iter().position(|item| (item.matcher)(request));
80 let Some(index) = position else {
81 return Err(HttpClientError::MockMiss {
82 method: request.method().to_string(),
83 url: request.url().to_owned(),
84 });
85 };
86 let response = expectations[index].response.clone();
87 if let Some(left) = expectations[index].remaining {
88 if left <= 1 {
89 expectations.remove(index);
90 } else {
91 expectations[index].remaining = Some(left - 1);
92 }
93 }
94 drop(expectations);
95 Ok(response)
96 }
97}
98
99impl HttpClient for MockHttpClient {
100 fn send(
101 &self,
102 request: ClientRequest,
103 ) -> impl std::future::Future<Output = Result<ClientResponse, HttpClientError>> + Send {
104 ready(self.resolve(&request))
105 }
106}