Skip to main content

rig_http/
test_utils.rs

1//! HTTP client doubles for tests of code that sends through an
2//! [`HttpClientExt`].
3
4use std::{
5    collections::VecDeque,
6    future::{self, Future},
7    sync::{Arc, Mutex, MutexGuard, PoisonError},
8};
9
10use bytes::Bytes;
11
12use crate::{
13    http_client::{
14        self, HttpClientExt, LazyBody, MultipartForm, Request, Response, StreamingResponse,
15    },
16    wasm_compat::WasmCompatSend,
17};
18
19/// The reply a double gives on a surface it does not script: the request
20/// reached a transport that has no answer for it.
21fn not_implemented() -> http_client::Error {
22    http_client::Error::non_success_with_details(
23        http::StatusCode::NOT_IMPLEMENTED,
24        http::HeaderMap::new(),
25        String::new(),
26    )
27}
28
29/// `mutex`'s value, also after a panic poisoned it.
30fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
31    mutex.lock().unwrap_or_else(PoisonError::into_inner)
32}
33
34/// The unary half of a streaming-only double.
35///
36/// Four doubles below script `send_streaming` and nothing else; that they
37/// have no unary surface is one fact about streaming-only doubles, so it is
38/// written here once and each impl states it by name.
39macro_rules! no_unary_surface {
40    () => {
41        fn send(
42            &self,
43            _req: Request<Bytes>,
44        ) -> impl Future<Output = http_client::Result<Response<LazyBody>>>
45        + WasmCompatSend
46        + 'static {
47            future::ready(Err(not_implemented()))
48        }
49
50        fn send_multipart(
51            &self,
52            _req: Request<MultipartForm>,
53        ) -> impl Future<Output = http_client::Result<Response<LazyBody>>>
54        + WasmCompatSend
55        + 'static {
56            future::ready(Err(not_implemented()))
57        }
58    };
59}
60
61/// Request data captured by [`RecordingHttpClient`].
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct CapturedHttpRequest {
64    /// Request URI.
65    pub uri: String,
66    /// Request headers.
67    pub headers: http::HeaderMap,
68    /// Request body bytes.
69    pub body: Bytes,
70}
71
72/// Response scripted for [`RecordingHttpClient`].
73#[derive(Clone, Debug)]
74pub enum MockHttpResponse {
75    /// Return this body with a successful HTTP status and no headers.
76    Success(Bytes),
77    /// Return this body with a successful HTTP status and these headers —
78    /// the reply whose `Content-Type` decides how it may be framed.
79    SuccessWithHeaders(Bytes, http::HeaderMap),
80    /// Return an HTTP response with the given (typically non-success) status
81    /// and body, instead of a transport-level error.
82    ErrorResponse(http::StatusCode, Bytes),
83    /// Return a status-code error that preserved the failed response's
84    /// headers, exactly as the bundled reqwest transport does (rig#2210).
85    ErrorWithHeaders(http::StatusCode, String, http::HeaderMap),
86    /// Return an HTTP response with the given (typically non-success) status,
87    /// body, and response headers, instead of a transport-level error.
88    ErrorResponseWithHeaders(http::StatusCode, Bytes, http::HeaderMap),
89}
90
91impl MockHttpResponse {
92    /// Create a successful response from bytes.
93    pub fn success(body: impl Into<Bytes>) -> Self {
94        Self::Success(body.into())
95    }
96
97    /// Create a successful response carrying `content_type`.
98    pub fn success_typed(body: impl Into<Bytes>, content_type: &'static str) -> Self {
99        let mut headers = http::HeaderMap::new();
100        headers.insert(
101            http::header::CONTENT_TYPE,
102            http::HeaderValue::from_static(content_type),
103        );
104        Self::SuccessWithHeaders(body.into(), headers)
105    }
106
107    /// Create a transport-level status error whose reply carried no headers
108    /// of interest: the same shape as [`Self::error_with_headers`] with an
109    /// empty map, since a rejection always comes with its headers.
110    pub fn error(status: http::StatusCode, message: impl Into<String>) -> Self {
111        Self::error_with_headers(status, message, http::HeaderMap::new())
112    }
113
114    /// Create a transport-level status error that preserved the failed
115    /// response's headers, as the bundled reqwest transport does.
116    pub fn error_with_headers(
117        status: http::StatusCode,
118        message: impl Into<String>,
119        headers: http::HeaderMap,
120    ) -> Self {
121        Self::ErrorWithHeaders(status, message.into(), headers)
122    }
123}
124
125impl MockHttpResponse {
126    /// The status, body and headers this reply has, or the transport error
127    /// it is.
128    fn into_parts(self) -> http_client::Result<(http::StatusCode, Bytes, Option<http::HeaderMap>)> {
129        Ok(match self {
130            Self::Success(body) => (http::StatusCode::OK, body, None),
131            Self::SuccessWithHeaders(body, headers) => (http::StatusCode::OK, body, Some(headers)),
132            Self::ErrorWithHeaders(status, body, headers) => {
133                return Err(http_client::Error::InvalidStatusCodeWithDetails {
134                    status,
135                    body,
136                    headers,
137                });
138            }
139            Self::ErrorResponse(status, body) => (status, body, None),
140            Self::ErrorResponseWithHeaders(status, body, headers) => (status, body, Some(headers)),
141        })
142    }
143}
144
145impl Default for MockHttpResponse {
146    fn default() -> Self {
147        Self::Success(Bytes::new())
148    }
149}
150
151/// An [`HttpClientExt`] implementation that records unary requests and returns
152/// a fixed response.
153#[derive(Clone, Debug, Default)]
154pub struct RecordingHttpClient {
155    requests: Arc<Mutex<Vec<CapturedHttpRequest>>>,
156    response: Arc<Mutex<MockHttpResponse>>,
157}
158
159impl RecordingHttpClient {
160    /// A client that answers every unary request with `response`.
161    fn scripted(response: MockHttpResponse) -> Self {
162        Self {
163            requests: Arc::default(),
164            response: Arc::new(Mutex::new(response)),
165        }
166    }
167
168    /// Create a client that returns `response_body` for unary requests.
169    pub fn new(response_body: impl Into<Bytes>) -> Self {
170        Self::scripted(MockHttpResponse::success(response_body))
171    }
172
173    /// Create a client that returns an HTTP status error for unary requests.
174    pub fn with_error(status: http::StatusCode, message: impl Into<String>) -> Self {
175        Self::scripted(MockHttpResponse::error(status, message))
176    }
177
178    /// Create a client whose transport reports a non-success status *and*
179    /// preserves the failed response's headers, as the bundled reqwest client
180    /// does (rig#2210).
181    pub fn with_error_headers(
182        status: http::StatusCode,
183        message: impl Into<String>,
184        headers: http::HeaderMap,
185    ) -> Self {
186        Self::scripted(MockHttpResponse::error_with_headers(
187            status, message, headers,
188        ))
189    }
190
191    /// Create a client that hands back a non-success HTTP response carrying
192    /// `headers`, instead of a transport-level error.
193    pub fn with_error_response_headers(
194        status: http::StatusCode,
195        body: impl Into<Bytes>,
196        headers: http::HeaderMap,
197    ) -> Self {
198        Self::scripted(MockHttpResponse::ErrorResponseWithHeaders(
199            status,
200            body.into(),
201            headers,
202        ))
203    }
204
205    /// Return the requests captured so far.
206    pub fn requests(&self) -> Vec<CapturedHttpRequest> {
207        lock(&self.requests).clone()
208    }
209
210    fn record_request(&self, uri: String, headers: http::HeaderMap, body: Bytes) {
211        lock(&self.requests).push(CapturedHttpRequest { uri, headers, body });
212    }
213
214    fn build_unary_response(response: MockHttpResponse) -> http_client::Result<Response<LazyBody>> {
215        let (status, response_body, response_headers) = response.into_parts()?;
216        let body: LazyBody = Box::pin(async move { Ok(response_body) });
217        let mut builder = Response::builder().status(status);
218        if let Some(headers) = response_headers
219            && let Some(slot) = builder.headers_mut()
220        {
221            *slot = headers;
222        }
223        builder.body(body).map_err(http_client::Error::Protocol)
224    }
225}
226
227impl HttpClientExt for RecordingHttpClient {
228    fn send(
229        &self,
230        req: Request<Bytes>,
231    ) -> impl Future<Output = http_client::Result<Response<LazyBody>>> + WasmCompatSend + 'static
232    {
233        let response = lock(&self.response).clone();
234        let (parts, body) = req.into_parts();
235        self.record_request(parts.uri.to_string(), parts.headers, body);
236
237        async move { Self::build_unary_response(response) }
238    }
239
240    fn send_multipart(
241        &self,
242        req: Request<MultipartForm>,
243    ) -> impl Future<Output = http_client::Result<Response<LazyBody>>> + WasmCompatSend + 'static
244    {
245        let response = lock(&self.response).clone();
246        let (parts, body) = req.into_parts();
247        let (_, body) = body.boundary("recording-http-client").encode();
248        self.record_request(parts.uri.to_string(), parts.headers, body);
249
250        async move { Self::build_unary_response(response) }
251    }
252
253    fn send_streaming(
254        &self,
255        _req: Request<Bytes>,
256    ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
257        future::ready(Err(not_implemented()))
258    }
259}
260
261/// An [`HttpClientExt`] implementation that records requests and returns one
262/// scripted response per request. A streamed request's reply body arrives as
263/// one chunk.
264///
265/// This is useful for testing retry and recovery paths through real provider
266/// request/response conversion without live credentials.
267#[derive(Clone, Debug, Default)]
268pub struct SequencedHttpClient {
269    requests: Arc<Mutex<Vec<CapturedHttpRequest>>>,
270    responses: Arc<Mutex<VecDeque<MockHttpResponse>>>,
271}
272
273impl SequencedHttpClient {
274    /// Create a client that returns the supplied responses in order.
275    pub fn new(responses: impl IntoIterator<Item = MockHttpResponse>) -> Self {
276        Self {
277            requests: Arc::new(Mutex::new(Vec::new())),
278            responses: Arc::new(Mutex::new(responses.into_iter().collect())),
279        }
280    }
281
282    /// Return the requests captured so far.
283    pub fn requests(&self) -> Vec<CapturedHttpRequest> {
284        lock(&self.requests).clone()
285    }
286
287    /// Return the number of scripted responses that have not been consumed.
288    pub fn remaining_responses(&self) -> usize {
289        lock(&self.responses).len()
290    }
291
292    /// Records the request `parts` and `body` and takes the next scripted
293    /// reply.
294    fn answer(&self, parts: http::request::Parts, body: Bytes) -> Option<MockHttpResponse> {
295        lock(&self.requests).push(CapturedHttpRequest {
296            uri: parts.uri.to_string(),
297            headers: parts.headers,
298            body,
299        });
300        lock(&self.responses).pop_front()
301    }
302}
303
304impl HttpClientExt for SequencedHttpClient {
305    fn send(
306        &self,
307        req: Request<Bytes>,
308    ) -> impl Future<Output = http_client::Result<Response<LazyBody>>> + WasmCompatSend + 'static
309    {
310        let (parts, body) = req.into_parts();
311        let response = self.answer(parts, body);
312        async move { RecordingHttpClient::build_unary_response(response.ok_or_else(not_implemented)?) }
313    }
314
315    fn send_multipart(
316        &self,
317        req: Request<MultipartForm>,
318    ) -> impl Future<Output = http_client::Result<Response<LazyBody>>> + WasmCompatSend + 'static
319    {
320        let (parts, _body) = req.into_parts();
321        let response = self.answer(parts, Bytes::new());
322        async move { RecordingHttpClient::build_unary_response(response.ok_or_else(not_implemented)?) }
323    }
324
325    fn send_streaming(
326        &self,
327        req: Request<Bytes>,
328    ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
329        let (parts, body) = req.into_parts();
330        let response = self.answer(parts, body);
331        future::ready(
332            response
333                .ok_or_else(not_implemented)
334                .and_then(streaming_response),
335        )
336    }
337}
338
339/// `response` as a streamed reply whose body is one chunk.
340fn streaming_response(response: MockHttpResponse) -> http_client::Result<StreamingResponse> {
341    let (status, body, headers) = response.into_parts()?;
342    let chunks: http_client::BoxedStream = Box::pin(futures::stream::iter([Ok::<
343        Bytes,
344        http_client::Error,
345    >(body)]));
346    let mut response = Response::builder()
347        .status(status)
348        .body(chunks)
349        .map_err(http_client::Error::Protocol)?;
350    if let Some(headers) = headers {
351        *response.headers_mut() = headers;
352    }
353    Ok(response)
354}
355
356/// A mock HTTP client that returns pre-built SSE bytes from `send_streaming`.
357///
358/// `send` and `send_multipart` always return `NOT_IMPLEMENTED`.
359#[derive(Clone, Debug, Default)]
360pub struct MockStreamingClient {
361    /// Bytes returned as a single streaming response chunk.
362    pub sse_bytes: Bytes,
363}
364
365impl HttpClientExt for MockStreamingClient {
366    no_unary_surface!();
367
368    fn send_streaming(
369        &self,
370        _req: Request<Bytes>,
371    ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
372        let sse_bytes = self.sse_bytes.clone();
373        async move {
374            let byte_stream =
375                futures::stream::iter(vec![Ok::<Bytes, http_client::Error>(sse_bytes)]);
376            let boxed_stream: http_client::BoxedStream = Box::pin(byte_stream);
377
378            Response::builder()
379                .status(http::StatusCode::OK)
380                .header(http::header::CONTENT_TYPE, "text/event-stream")
381                .body(boxed_stream)
382                .map_err(http_client::Error::Protocol)
383        }
384    }
385}
386
387/// A mock HTTP client whose `send_streaming` never answers, as a provider
388/// that accepts a request and then sends nothing.
389#[derive(Clone, Debug, Default)]
390pub struct SilentStreamingClient;
391
392impl HttpClientExt for SilentStreamingClient {
393    no_unary_surface!();
394
395    fn send_streaming(
396        &self,
397        _req: Request<Bytes>,
398    ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
399        std::future::pending()
400    }
401}
402
403/// A mock HTTP client whose `send_streaming` answers at once, then sends
404/// each of `chunks` `gap` after the last, then holds the body open.
405#[derive(Clone, Debug, Default)]
406pub struct PacedStreamingClient {
407    /// The body's chunks, in order.
408    pub chunks: Vec<&'static str>,
409    /// The wait before each chunk.
410    pub gap: std::time::Duration,
411}
412
413impl HttpClientExt for PacedStreamingClient {
414    no_unary_surface!();
415
416    fn send_streaming(
417        &self,
418        _req: Request<Bytes>,
419    ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
420        let (chunks, gap) = (self.chunks.clone(), self.gap);
421        async move {
422            let byte_stream =
423                futures::StreamExt::then(futures::stream::iter(chunks), move |chunk| async move {
424                    crate::wasm_compat::sleep(gap).await;
425                    Ok::<Bytes, http_client::Error>(Bytes::from_static(chunk.as_bytes()))
426                });
427            let byte_stream = futures::StreamExt::chain(byte_stream, futures::stream::pending());
428            let boxed_stream: http_client::BoxedStream = Box::pin(byte_stream);
429            Response::builder()
430                .status(http::StatusCode::OK)
431                .header(http::header::CONTENT_TYPE, "text/event-stream")
432                .body(boxed_stream)
433                .map_err(http_client::Error::Protocol)
434        }
435    }
436}
437
438/// An [`HttpClientExt`] implementation whose `send_streaming` fails immediately
439/// with a non-success HTTP status and response body.
440#[derive(Debug, Clone)]
441pub struct HttpErrorStreamingClient {
442    pub status: http::StatusCode,
443    pub body: String,
444}
445
446impl HttpErrorStreamingClient {
447    /// Create a streaming client that fails `send_streaming` with the given status and body.
448    pub fn new(status: http::StatusCode, body: impl Into<String>) -> Self {
449        Self {
450            status,
451            body: body.into(),
452        }
453    }
454}
455
456impl Default for HttpErrorStreamingClient {
457    /// The completion-model client bound requires `H: Default`; this lets the
458    /// streaming error client back a real model in tests.
459    fn default() -> Self {
460        Self::new(http::StatusCode::INTERNAL_SERVER_ERROR, String::new())
461    }
462}
463
464impl HttpClientExt for HttpErrorStreamingClient {
465    no_unary_surface!();
466
467    fn send_streaming(
468        &self,
469        _req: Request<Bytes>,
470    ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
471        let status = self.status;
472        let body = self.body.clone();
473        async move {
474            Err(http_client::Error::non_success_with_details(
475                status,
476                http::HeaderMap::new(),
477                body,
478            ))
479        }
480    }
481}
482
483/// An [`HttpClientExt`] whose `send_streaming` hands a non-success reply back
484/// as an `Ok` response — the fourth non-success cell: a custom transport that
485/// does not reject on status, so the driver must.
486#[derive(Debug, Clone)]
487pub struct NonSuccessStreamingClient {
488    pub status: http::StatusCode,
489    pub headers: http::HeaderMap,
490    pub body: Bytes,
491}
492
493impl HttpClientExt for NonSuccessStreamingClient {
494    no_unary_surface!();
495
496    fn send_streaming(
497        &self,
498        _req: Request<Bytes>,
499    ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
500        let status = self.status;
501        let headers = self.headers.clone();
502        let body = self.body.clone();
503        async move {
504            let byte_stream = futures::stream::iter(vec![Ok::<Bytes, http_client::Error>(body)]);
505            let boxed_stream: http_client::BoxedStream = Box::pin(byte_stream);
506            let mut response = Response::builder()
507                .status(status)
508                .body(boxed_stream)
509                .map_err(http_client::Error::Protocol)?;
510            *response.headers_mut() = headers;
511            Ok(response)
512        }
513    }
514}
515
516/// An [`HttpClientExt`] implementation that returns one scripted stream of byte
517/// chunks from `send_streaming`.
518#[derive(Debug, Clone, Default)]
519pub struct SequencedStreamingHttpClient {
520    chunks: Arc<Mutex<Option<Vec<http_client::Result<Bytes>>>>>,
521}
522
523impl SequencedStreamingHttpClient {
524    /// Create a streaming client from the chunks it should yield.
525    pub fn new(chunks: Vec<http_client::Result<Bytes>>) -> Self {
526        Self {
527            chunks: Arc::new(Mutex::new(Some(chunks))),
528        }
529    }
530}
531
532impl HttpClientExt for SequencedStreamingHttpClient {
533    no_unary_surface!();
534
535    fn send_streaming(
536        &self,
537        _req: Request<Bytes>,
538    ) -> impl Future<Output = http_client::Result<StreamingResponse>> + WasmCompatSend {
539        let chunks = lock(&self.chunks).take();
540
541        async move {
542            let Some(chunks) = chunks else {
543                return Err(http_client::Error::non_success_with_details(
544                    http::StatusCode::INTERNAL_SERVER_ERROR,
545                    http::HeaderMap::new(),
546                    "streaming chunks should only be consumed once".to_string(),
547                ));
548            };
549
550            let byte_stream = futures::stream::iter(chunks);
551            let boxed_stream: http_client::BoxedStream = Box::pin(byte_stream);
552
553            Response::builder()
554                .status(http::StatusCode::OK)
555                .header(http::header::CONTENT_TYPE, "text/event-stream")
556                .body(boxed_stream)
557                .map_err(http_client::Error::Protocol)
558        }
559    }
560}