//! Test doubles shared across `recorder-core`'s unit tests, and usable from //! other crates/integration tests via the `test-util` feature. use std::sync::Mutex; use async_trait::async_trait; use crate::http::{HttpRequest, HttpResponse, HttpTransport, Method, TransportError}; struct Expectation { method: Method, url: String, response: Result, } /// Scripted [`HttpTransport`]: queue expected requests in order with /// [`FakeTransport::expect`], run the code under test against it, then call /// [`FakeTransport::assert_done`] to confirm every expectation was consumed. /// /// Matching is exact (method and full URL, including query string) and /// strictly FIFO. Uses interior mutability so `send` works through /// `&self`, as required behind `Arc`. pub struct FakeTransport { expectations: Mutex>, requests: Mutex>, } impl FakeTransport { pub fn new() -> Self { FakeTransport { expectations: Mutex::new(Vec::new()), requests: Mutex::new(Vec::new()), } } /// Queues the next expected request and the response to return for it. pub fn expect(&self, method: Method, url: &str, status: u16, body: impl Into>) { let response = HttpResponse { status, body: body.into(), }; self.push(method, url, Ok(response)); } /// Queues the next expected request and the transport error it fails /// with (e.g. the server is unreachable). pub fn fail(&self, method: Method, url: &str, error: TransportError) { self.push(method, url, Err(error)); } fn push(&self, method: Method, url: &str, response: Result) { self.expectations.lock().unwrap().push(Expectation { method, url: url.to_string(), response, }); } /// Every request sent through this transport so far, in order. pub fn requests(&self) -> Vec { self.requests.lock().unwrap().clone() } /// Panics listing any scripted expectation that was never sent. pub fn assert_done(&self) { let remaining = self.expectations.lock().unwrap(); if !remaining.is_empty() { let pending: Vec = remaining .iter() .map(|e| format!("{:?} {}", e.method, e.url)) .collect(); panic!( "FakeTransport: {} expectation(s) never called: {}", pending.len(), pending.join(", ") ); } } } impl Default for FakeTransport { fn default() -> Self { Self::new() } } #[async_trait] impl HttpTransport for FakeTransport { async fn send(&self, req: HttpRequest) -> Result { let expectation = { let mut expectations = self.expectations.lock().unwrap(); if expectations.is_empty() { panic!( "FakeTransport: unexpected {:?} {} (no expectations remain)", req.method, req.url ); } expectations.remove(0) }; if expectation.method != req.method || expectation.url != req.url { panic!( "FakeTransport: expected {:?} {}, got {:?} {}", expectation.method, expectation.url, req.method, req.url ); } self.requests.lock().unwrap().push(req); expectation.response } }