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
Generated
+322 -9
View File
@@ -16,7 +16,7 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"cpufeatures 0.2.17",
]
[[package]]
@@ -273,6 +273,12 @@ version = "0.21.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64"
version = "0.23.1"
@@ -556,6 +562,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"rand_core 0.10.1",
]
[[package]]
name = "chrono"
version = "0.4.45"
@@ -658,6 +675,15 @@ dependencies = [
"libc",
]
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crc"
version = "3.4.0"
@@ -1431,8 +1457,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"wasi",
"wasm-bindgen",
]
[[package]]
@@ -1454,8 +1482,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 6.0.0",
"rand_core 0.10.1",
"wasm-bindgen",
]
[[package]]
@@ -1772,6 +1803,22 @@ dependencies = [
"want",
]
[[package]]
name = "hyper-rustls"
version = "0.27.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
dependencies = [
"http",
"hyper",
"hyper-util",
"rustls",
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots",
]
[[package]]
name = "hyper-util"
version = "0.1.21"
@@ -2316,6 +2363,12 @@ version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "lru-slab"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]]
name = "markup5ever"
version = "0.39.0"
@@ -2358,6 +2411,16 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mime_guess"
version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
dependencies = [
"mime",
"unicase",
]
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -3150,6 +3213,62 @@ dependencies = [
"memchr",
]
[[package]]
name = "quinn"
version = "0.11.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"
dependencies = [
"bytes",
"cfg_aliases",
"pin-project-lite",
"quinn-proto",
"quinn-udp",
"rustc-hash",
"rustls",
"socket2",
"thiserror 2.0.21",
"tokio",
"tracing",
"web-time",
]
[[package]]
name = "quinn-proto"
version = "0.11.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"
dependencies = [
"bytes",
"getrandom 0.4.3",
"lru-slab",
"rand 0.10.3",
"rand_pcg",
"ring",
"rustc-hash",
"rustls",
"rustls-pki-types",
"slab",
"thiserror 2.0.21",
"tinyvec",
"tracing",
"web-time",
]
[[package]]
name = "quinn-udp"
version = "0.5.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"
dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
]
[[package]]
name = "quote"
version = "1.0.47"
@@ -3179,7 +3298,18 @@ checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
"rand_core 0.6.4",
]
[[package]]
name = "rand"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
"chacha20",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
[[package]]
@@ -3189,7 +3319,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
"rand_core 0.6.4",
]
[[package]]
@@ -3201,6 +3331,21 @@ dependencies = [
"getrandom 0.2.17",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_pcg"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -3232,16 +3377,19 @@ dependencies = [
name = "recorder-core"
version = "0.1.0"
dependencies = [
"async-trait",
"chrono",
"flacenc",
"hound",
"keyring",
"reqwest 0.12.28",
"rubato",
"rusqlite",
"serde",
"serde_json",
"tempfile",
"thiserror 1.0.69",
"tokio",
]
[[package]]
@@ -3312,6 +3460,48 @@ version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "reqwest"
version = "0.12.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64 0.22.1",
"bytes",
"futures-core",
"futures-util",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-util",
"js-sys",
"log",
"mime_guess",
"percent-encoding",
"pin-project-lite",
"quinn",
"rustls",
"rustls-pki-types",
"serde",
"serde_json",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tokio-rustls",
"tokio-util",
"tower",
"tower-http",
"tower-service",
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-streams 0.4.2",
"web-sys",
"webpki-roots",
]
[[package]]
name = "reqwest"
version = "0.13.5"
@@ -3342,10 +3532,24 @@ dependencies = [
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-streams",
"wasm-streams 0.5.0",
"web-sys",
]
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rubato"
version = "0.15.0"
@@ -3414,12 +3618,53 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"web-time",
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "rustversion"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "same-file"
version = "1.0.6"
@@ -3499,7 +3744,7 @@ dependencies = [
"hkdf",
"num",
"once_cell",
"rand",
"rand 0.8.8",
"serde",
"sha2",
"zbus 4.4.0",
@@ -3635,6 +3880,18 @@ dependencies = [
"serde_core",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "serde_with"
version = "3.24.0"
@@ -3706,7 +3963,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures",
"cpufeatures 0.2.17",
"digest",
]
@@ -3717,7 +3974,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"cpufeatures 0.2.17",
"digest",
]
@@ -4054,7 +4311,7 @@ dependencies = [
"percent-encoding",
"plist",
"raw-window-handle",
"reqwest",
"reqwest 0.13.5",
"serde",
"serde_json",
"serde_repr",
@@ -4426,9 +4683,31 @@ dependencies = [
"mio",
"pin-project-lite",
"socket2",
"tokio-macros",
"windows-sys 0.61.2",
]
[[package]]
name = "tokio-macros"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "tokio-rustls"
version = "0.26.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"
dependencies = [
"rustls",
"tokio",
]
[[package]]
name = "tokio-util"
version = "0.7.20"
@@ -4675,6 +4954,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "unicase"
version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"
[[package]]
name = "unicode-ident"
version = "1.0.27"
@@ -4687,6 +4972,12 @@ version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.8"
@@ -4879,6 +5170,19 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "wasm-streams"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"
dependencies = [
"futures-util",
"js-sys",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
]
[[package]]
name = "wasm-streams"
version = "0.5.0"
@@ -4968,6 +5272,15 @@ dependencies = [
"system-deps",
]
[[package]]
name = "webpki-roots"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "webview2-com"
version = "0.39.1"
@@ -5565,7 +5878,7 @@ dependencies = [
"hex",
"nix 0.29.0",
"ordered-stream",
"rand",
"rand 0.8.8",
"serde",
"serde_repr",
"sha1",
+6
View File
@@ -7,6 +7,9 @@ edition = "2021"
name = "recorder_core"
path = "src/lib.rs"
[features]
test-util = []
[dependencies]
rusqlite = { version = "0.31", features = ["bundled"] }
serde = { version = "1.0", features = ["derive"] }
@@ -17,6 +20,9 @@ rubato = "0.15"
flacenc = "0.5"
hound = "3.5"
keyring = { version = "3", features = ["windows-native", "sync-secret-service", "crypto-rust"] }
async-trait = "0.1"
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "multipart", "json", "stream"] }
tokio = { version = "1", features = ["rt", "fs", "time", "macros"] }
[dev-dependencies]
tempfile = "3"
+282
View File
@@ -0,0 +1,282 @@
//! The HTTP transport seam: every outgoing request the DeepScript and Claude
//! clients (Tasks 12/13) make goes through [`HttpTransport`], so unit tests
//! can swap in [`crate::testing::FakeTransport`] and run with the network
//! unplugged. [`ReqwestTransport`] is the real implementation, exercised only
//! by the live integration suite (`crates/core/tests/live_api.rs`).
use std::path::PathBuf;
use std::time::Duration;
use async_trait::async_trait;
use serde::de::DeserializeOwned;
use thiserror::Error;
/// HTTP method a [`HttpRequest`] is sent with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Method {
Get,
Post,
Delete,
}
/// One field of a `multipart/form-data` body.
#[derive(Debug, Clone, PartialEq)]
pub enum Part {
Text {
name: String,
value: String,
},
/// Streamed from disk by [`ReqwestTransport`]; never read fully into
/// memory (recordings can be tens of megabytes).
File {
name: String,
file_name: String,
path: PathBuf,
mime: String,
},
}
/// Body of a [`HttpRequest`].
#[derive(Debug, Clone, PartialEq)]
pub enum HttpBody {
Empty,
Json(serde_json::Value),
Multipart(Vec<Part>),
}
/// A request to send through a [`HttpTransport`].
#[derive(Debug, Clone, PartialEq)]
pub struct HttpRequest {
pub method: Method,
pub url: String,
pub headers: Vec<(String, String)>,
pub body: HttpBody,
}
impl HttpRequest {
/// The value of the first header matching `name`, case-insensitively.
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
}
/// A response as returned by a [`HttpTransport`]. Non-2xx statuses are not an
/// error at this layer: callers inspect `status` themselves.
#[derive(Debug, Clone, PartialEq)]
pub struct HttpResponse {
pub status: u16,
pub body: Vec<u8>,
}
impl HttpResponse {
/// Decodes the body as JSON.
pub fn json<T: DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
serde_json::from_slice(&self.body)
}
}
/// Transport-level failure: a request that could not be sent or whose
/// response could not be read at all. A non-2xx status is *not* one of
/// these; it comes back as an ordinary [`HttpResponse`].
#[derive(Debug, Error)]
pub enum TransportError {
#[error("E/A-Fehler: {0}")]
Io(String),
#[error("Netzwerkfehler: {0}")]
Network(String),
#[error("Zeitüberschreitung")]
Timeout,
}
/// Seam between the API clients and the network. Implemented by
/// [`ReqwestTransport`] for real traffic and by
/// [`crate::testing::FakeTransport`] for unit tests.
#[async_trait]
pub trait HttpTransport: Send + Sync {
async fn send(&self, req: HttpRequest) -> Result<HttpResponse, TransportError>;
}
/// Live `HttpTransport` backed by `reqwest` (rustls). Shares one
/// `reqwest::Client` (connection pooling) with a 10 minute request timeout
/// and a 30 second connect timeout, matching the Claude/DeepScript clients'
/// worst-case wait.
pub struct ReqwestTransport {
client: reqwest::Client,
}
impl ReqwestTransport {
pub fn new() -> Self {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(10 * 60))
.connect_timeout(Duration::from_secs(30))
.build()
.expect("failed to build reqwest client");
ReqwestTransport { client }
}
}
impl Default for ReqwestTransport {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl HttpTransport for ReqwestTransport {
async fn send(&self, req: HttpRequest) -> Result<HttpResponse, TransportError> {
let mut builder = match req.method {
Method::Get => self.client.get(&req.url),
Method::Post => self.client.post(&req.url),
Method::Delete => self.client.delete(&req.url),
};
for (name, value) in &req.headers {
builder = builder.header(name, value);
}
builder = match &req.body {
HttpBody::Empty => builder,
HttpBody::Json(value) => builder.json(value),
HttpBody::Multipart(parts) => {
let form = build_multipart(parts).await?;
builder.multipart(form)
}
};
let response = builder.send().await.map_err(map_reqwest_error)?;
let status = response.status().as_u16();
let body = response.bytes().await.map_err(map_reqwest_error)?.to_vec();
Ok(HttpResponse { status, body })
}
}
/// Builds a `reqwest` multipart form, streaming any [`Part::File`] from disk
/// rather than reading it into memory.
async fn build_multipart(parts: &[Part]) -> Result<reqwest::multipart::Form, TransportError> {
let mut form = reqwest::multipart::Form::new();
for part in parts {
form = match part {
Part::Text { name, value } => form.text(name.clone(), value.clone()),
Part::File {
name,
file_name,
path,
mime,
} => {
let file = tokio::fs::File::open(path)
.await
.map_err(|e| TransportError::Io(format!("{}: {e}", path.display())))?;
let len = file.metadata().await.ok().map(|m| m.len());
let body = reqwest::Body::from(file);
let mut field = match len {
Some(len) => reqwest::multipart::Part::stream_with_length(body, len),
None => reqwest::multipart::Part::stream(body),
};
field = field.file_name(file_name.clone());
field = field
.mime_str(mime)
.map_err(|e| TransportError::Io(format!("ungültiger MIME-Typ {mime}: {e}")))?;
form.part(name.clone(), field)
}
};
}
Ok(form)
}
fn map_reqwest_error(e: reqwest::Error) -> TransportError {
if e.is_timeout() {
TransportError::Timeout
} else {
TransportError::Network(e.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::FakeTransport;
fn get(url: &str) -> HttpRequest {
HttpRequest {
method: Method::Get,
url: url.to_string(),
headers: vec![],
body: HttpBody::Empty,
}
}
#[tokio::test]
async fn fake_transport_returns_scripted_responses_in_order() {
let transport = FakeTransport::new();
transport.expect(Method::Get, "https://api.example.com/a", 200, "first");
transport.expect(Method::Post, "https://api.example.com/b?x=1", 201, "second");
let first = transport
.send(get("https://api.example.com/a"))
.await
.unwrap();
assert_eq!(first.status, 200);
assert_eq!(first.body, b"first");
let second = transport
.send(HttpRequest {
method: Method::Post,
url: "https://api.example.com/b?x=1".to_string(),
headers: vec![("x-test".to_string(), "1".to_string())],
body: HttpBody::Empty,
})
.await
.unwrap();
assert_eq!(second.status, 201);
assert_eq!(second.body, b"second");
let requests = transport.requests();
assert_eq!(requests.len(), 2);
assert_eq!(requests[0].url, "https://api.example.com/a");
assert_eq!(requests[1].url, "https://api.example.com/b?x=1");
assert_eq!(requests[1].header("x-test"), Some("1"));
transport.assert_done();
}
#[tokio::test]
#[should_panic(expected = "FakeTransport")]
async fn fake_transport_panics_on_unexpected_url() {
let transport = FakeTransport::new();
transport.expect(Method::Get, "https://api.example.com/a", 200, "body");
let _ = transport.send(get("https://api.example.com/wrong")).await;
}
#[test]
#[should_panic(expected = "FakeTransport")]
fn fake_transport_assert_done_detects_missing_calls() {
let transport = FakeTransport::new();
transport.expect(Method::Get, "https://api.example.com/a", 200, "body");
transport.assert_done();
}
#[test]
fn http_request_header_lookup_is_case_insensitive() {
let req = HttpRequest {
method: Method::Get,
url: "https://api.example.com".to_string(),
headers: vec![("Authorization".to_string(), "Bearer xyz".to_string())],
body: HttpBody::Empty,
};
assert_eq!(req.header("authorization"), Some("Bearer xyz"));
assert_eq!(req.header("missing"), None);
}
#[test]
fn http_response_json_decodes_body() {
let resp = HttpResponse {
status: 200,
body: br#"{"ok":true}"#.to_vec(),
};
let value: serde_json::Value = resp.json().unwrap();
assert_eq!(value["ok"], serde_json::json!(true));
}
}
+4
View File
@@ -7,6 +7,7 @@
pub mod audio;
pub mod capture;
pub mod detect;
pub mod http;
pub mod merge;
pub mod model;
pub mod recorder;
@@ -15,6 +16,9 @@ pub mod secrets;
pub mod settings;
pub mod store;
#[cfg(any(test, feature = "test-util"))]
pub mod testing;
#[cfg(test)]
mod tests {
#[test]
+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,
})
}
}