feat #14740: http transport seam

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
hauke
2026-11-05 16:05:51 +01:00
co-authored by Claude Sonnet 5
parent 3dfa693c4e
commit 3facefeeed
5 changed files with 714 additions and 9 deletions
+100
View File
@@ -0,0 +1,100 @@
//! 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,
status: u16,
body: Vec<u8>,
}
/// 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<dyn HttpTransport>`.
pub struct FakeTransport {
expectations: Mutex<Vec<Expectation>>,
requests: Mutex<Vec<HttpRequest>>,
}
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<Vec<u8>>) {
self.expectations.lock().unwrap().push(Expectation {
method,
url: url.to_string(),
status,
body: body.into(),
});
}
/// Every request sent through this transport so far, in order.
pub fn requests(&self) -> Vec<HttpRequest> {
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<String> = 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<HttpResponse, TransportError> {
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);
Ok(HttpResponse {
status: expectation.status,
body: expectation.body,
})
}
}