Skip to main content

waft_test/
http.rs

1//! HTTP in memory: a client that answers the responses a test configured, keeps each request it
2//! was given, and streams a response's body a chunk at a time so progress can be watched. Every
3//! clone is the same client.
4
5use std::cell::RefCell;
6use std::rc::Rc;
7
8use http::{HeaderMap, Method, Request, Response, StatusCode, Uri};
9use waft_embedder::{
10    Body, BodyReadFuture, BodyStream, BodyTrailersFuture, HttpClient, HttpError, HttpFuture,
11    SendOptions,
12};
13
14/// A client that answers what the test configured. A request for a URL with no answer fails as a
15/// connection that found nothing.
16#[derive(Clone, Default)]
17pub struct MockHttpClient(Rc<ClientState>);
18
19#[derive(Default)]
20struct ClientState {
21    responses: RefCell<Vec<(String, MockResponse)>>,
22    asked: RefCell<Vec<SentRequest>>,
23}
24
25/// One response a [`MockHttpClient`] answers.
26#[derive(Clone, Debug, Default, PartialEq)]
27pub struct MockResponse {
28    pub status: StatusCode,
29    pub headers: HeaderMap,
30    /// The body in the pieces it arrives in, one per read.
31    pub chunks: Vec<Vec<u8>>,
32    /// Fields that come after the body.
33    pub trailers: Option<HeaderMap>,
34    /// The length the sender claims; the sum of the chunks when not given.
35    pub length: Option<u64>,
36    /// Why the body stopped short instead of ending.
37    pub error: Option<HttpError>,
38}
39
40/// A request the app sent, as the client kept it.
41#[derive(Clone, Debug, PartialEq)]
42pub struct SentRequest {
43    pub method: Method,
44    pub uri: Uri,
45    pub headers: HeaderMap,
46    pub body: Vec<u8>,
47    /// The fields the request was made to send after its body, which a test's client has
48    /// nowhere to send and so keeps.
49    pub trailers: Option<HeaderMap>,
50    pub options: SendOptions,
51}
52
53impl MockHttpClient {
54    pub fn new() -> MockHttpClient {
55        MockHttpClient::default()
56    }
57
58    /// Answers every request for `url` with `response`. The last answer for a URL is the one
59    /// used.
60    pub fn answering(self, url: impl Into<String>, response: MockResponse) -> MockHttpClient {
61        self.0.responses.borrow_mut().push((url.into(), response));
62        self
63    }
64
65    /// Every request the client was given, in order.
66    pub fn asked(&self) -> Vec<SentRequest> {
67        self.0.asked.borrow().clone()
68    }
69
70    fn response_for(&self, uri: &Uri) -> Option<MockResponse> {
71        self.0
72            .responses
73            .borrow()
74            .iter()
75            .rev()
76            .find(|(url, _)| url == &uri.to_string())
77            .map(|(_, response)| response.clone())
78    }
79
80    fn keep(&self, request: SentRequest) {
81        self.0.asked.borrow_mut().push(request);
82    }
83}
84
85impl MockResponse {
86    /// An `OK` response with no body.
87    pub fn new() -> MockResponse {
88        MockResponse {
89            status: StatusCode::OK,
90            ..MockResponse::default()
91        }
92    }
93
94    pub fn status(mut self, status: StatusCode) -> MockResponse {
95        self.status = status;
96        self
97    }
98
99    pub fn header(mut self, name: &str, value: &str) -> MockResponse {
100        self.headers.append(
101            name.parse::<http::HeaderName>().expect("a header name"),
102            value.parse().expect("a header value"),
103        );
104        self
105    }
106
107    /// A body that arrives as one piece.
108    pub fn body(mut self, bytes: impl Into<Vec<u8>>) -> MockResponse {
109        self.chunks.push(bytes.into());
110        self
111    }
112
113    /// A body that arrives in `chunks`, one per read.
114    pub fn chunks(mut self, chunks: Vec<Vec<u8>>) -> MockResponse {
115        self.chunks = chunks;
116        self
117    }
118
119    pub fn trailers(mut self, trailers: HeaderMap) -> MockResponse {
120        self.trailers = Some(trailers);
121        self
122    }
123
124    /// A length other than the bytes actually sent, as a compressed body reports.
125    pub fn length(mut self, length: u64) -> MockResponse {
126        self.length = Some(length);
127        self
128    }
129
130    /// The body fails after the chunks it was given, with `error`.
131    pub fn error(mut self, error: HttpError) -> MockResponse {
132        self.error = Some(error);
133        self
134    }
135}
136
137impl HttpClient for MockHttpClient {
138    fn send(&self, request: Request<Body>, options: SendOptions) -> HttpFuture {
139        let mut request = request;
140        let response = self.response_for(request.uri());
141        let kept = self.clone();
142        let method = request.method().clone();
143        let uri = request.uri().clone();
144        let headers = request.headers().clone();
145        Box::pin(async move {
146            let body = request.body_mut();
147            let bytes = body.read_all().await?;
148            let trailers = body.trailers().await?;
149            kept.keep(SentRequest {
150                method,
151                uri: uri.clone(),
152                headers,
153                body: bytes,
154                trailers,
155                options,
156            });
157            let response = response.ok_or_else(|| {
158                HttpError::Internal(Some(format!("no response is configured for {uri}")))
159            })?;
160            let mut answer = Response::builder().status(response.status);
161            for (name, value) in &response.headers {
162                answer = answer.header(name, value);
163            }
164            let body = Body::from_stream(MockBodyStream::new(response));
165            answer.body(body).map_err(|_| HttpError::HttpProtocolError)
166        })
167    }
168}
169
170/// A configured response's body, read one chunk per read.
171struct MockBodyStream {
172    chunks: std::vec::IntoIter<Vec<u8>>,
173    current: Vec<u8>,
174    read: usize,
175    trailers: Option<HeaderMap>,
176    length: Option<u64>,
177    error: Option<HttpError>,
178}
179
180impl MockBodyStream {
181    fn new(response: MockResponse) -> MockBodyStream {
182        let length = response
183            .length
184            .or_else(|| Some(response.chunks.iter().map(Vec::len).sum::<usize>() as u64));
185        MockBodyStream {
186            chunks: response.chunks.into_iter(),
187            current: Vec::new(),
188            read: 0,
189            trailers: response.trailers,
190            length,
191            error: response.error,
192        }
193    }
194}
195
196impl BodyStream for MockBodyStream {
197    fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
198        if self.read == self.current.len() {
199            match self.chunks.next() {
200                Some(chunk) => {
201                    self.current = chunk;
202                    self.read = 0;
203                }
204                None => {
205                    let answer = match self.error.take() {
206                        Some(error) => Err(error),
207                        None => Ok(0),
208                    };
209                    return Box::pin(std::future::ready(answer));
210                }
211            }
212        }
213        let read = (self.current.len() - self.read).min(buf.len());
214        buf[..read].copy_from_slice(&self.current[self.read..self.read + read]);
215        self.read += read;
216        Box::pin(std::future::ready(Ok(read)))
217    }
218
219    fn trailers(&mut self) -> BodyTrailersFuture<'_> {
220        Box::pin(std::future::ready(Ok(self.trailers.clone())))
221    }
222
223    fn length(&self) -> Option<u64> {
224        self.length
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use std::future::Future;
232    use std::task::Poll;
233
234    fn now<T>(future: impl Future<Output = T>) -> T {
235        let mut future = std::pin::pin!(future);
236        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
237        loop {
238            if let Poll::Ready(value) = future.as_mut().poll(&mut context) {
239                return value;
240            }
241        }
242    }
243
244    #[test]
245    fn a_configured_response_answers_with_its_head_and_streams_its_body() {
246        let client = MockHttpClient::new().answering(
247            "https://example.test/photo.png",
248            MockResponse::new()
249                .header("content-type", "image/png")
250                .chunks(vec![b"one".to_vec(), b"two".to_vec()])
251                .trailers(HeaderMap::new()),
252        );
253        let request = Request::builder()
254            .uri("https://example.test/photo.png")
255            .body(Body::empty())
256            .unwrap();
257        let mut response = now(client.send(request, SendOptions::default())).unwrap();
258        assert_eq!(response.status(), StatusCode::OK);
259        assert_eq!(response.headers()["content-type"], "image/png");
260        assert_eq!(
261            now(response.body_mut().read_all()).unwrap(),
262            b"onetwo".to_vec()
263        );
264        assert_eq!(client.asked().len(), 1);
265        assert_eq!(
266            client.asked()[0].uri,
267            "https://example.test/photo.png".parse::<Uri>().unwrap()
268        );
269    }
270
271    #[test]
272    fn a_responses_trailers_answer_again_the_same() {
273        let mut trailers = HeaderMap::new();
274        trailers.insert("x-checksum", 7u32.into());
275        let client = MockHttpClient::new().answering(
276            "https://example.test/chunked",
277            MockResponse::new()
278                .body(b"the bytes".to_vec())
279                .trailers(trailers.clone()),
280        );
281        let request = Request::builder()
282            .uri("https://example.test/chunked")
283            .body(Body::empty())
284            .unwrap();
285        let mut response = now(client.send(request, SendOptions::default())).unwrap();
286        assert_eq!(
287            now(response.body_mut().read_all()).unwrap(),
288            b"the bytes".to_vec()
289        );
290        assert_eq!(
291            now(response.body_mut().trailers()).unwrap(),
292            Some(trailers.clone())
293        );
294        assert_eq!(
295            now(response.body_mut().trailers()).unwrap(),
296            Some(trailers),
297            "a second asking answers the same fields"
298        );
299    }
300
301    #[test]
302    fn a_request_with_trailers_is_kept_with_them() {
303        let client =
304            MockHttpClient::new().answering("https://example.test/put", MockResponse::new());
305        let mut trailers = HeaderMap::new();
306        trailers.insert("x-checksum", 7u32.into());
307        let request = Request::builder()
308            .method("PUT")
309            .uri("https://example.test/put")
310            .body(Body::from(b"the bytes".to_vec()).with_trailers(trailers.clone()))
311            .unwrap();
312        let mut response = now(client.send(request, SendOptions::default())).unwrap();
313        now(response.body_mut().read_all()).unwrap();
314        assert_eq!(client.asked()[0].body, b"the bytes".to_vec());
315        assert_eq!(client.asked()[0].trailers, Some(trailers));
316    }
317
318    #[test]
319    fn a_url_with_no_answer_fails_as_a_connection_that_found_nothing() {
320        let client = MockHttpClient::new();
321        let request = Request::builder()
322            .uri("https://example.test/missing")
323            .body(Body::empty())
324            .unwrap();
325        let error = now(client.send(request, SendOptions::default())).unwrap_err();
326        assert!(matches!(error, HttpError::Internal(_)));
327    }
328}