Skip to main content

tpt_http_stub/
lib.rs

1//! Lightweight in-process HTTP stub server for tests.
2//!
3//! `tpt-http-stub` spins up a real TCP HTTP server on a random free port (reserved
4//! via `tpt-port-scout`, so there are no TOCTOU races) and answers registered
5//! route stubs. It uses a blocking, single-thread-per-connection server — **no
6//! async runtime required** — which makes it ideal for synchronous tests.
7//!
8//! # Quick start
9//!
10//! ```
11//! use tpt_http_stub::HttpStub;
12//! use std::io::{Read, Write};
13//! use std::net::TcpStream;
14//!
15//! let stub = HttpStub::new();
16//! stub.on("GET", "/users/1").respond(200, "alice");
17//!
18//! // Point any HTTP client at the base URL. Here we issue a raw request to keep
19//! // the example dependency-free.
20//! let host = stub.base_url().trim_start_matches("http://").to_string();
21//! let mut s = TcpStream::connect(&host).unwrap();
22//! s.write_all(b"GET /users/1 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").unwrap();
23//! s.flush().unwrap();
24//! let mut resp = String::new();
25//! s.read_to_string(&mut resp).unwrap();
26//! let body = resp.splitn(2, "\r\n\r\n").nth(1).unwrap();
27//! assert_eq!(body, "alice");
28//!
29//! stub.assert_called_once();
30//! ```
31//!
32//! (In real tests drive the stub with any HTTP client — the example above uses a
33//! raw socket to stay dependency-free.)
34
35use std::collections::HashMap;
36use std::io::{Read, Write};
37use std::net::TcpStream;
38use std::str::FromStr;
39use std::sync::mpsc;
40use std::sync::{Arc, Mutex};
41use std::thread;
42
43use tpt_port_scout::PortSet;
44
45/// An HTTP method, stored as an upper-cased string for case-insensitive matching.
46#[derive(Debug, Clone, PartialEq, Eq, Hash)]
47pub struct Method(String);
48
49impl Method {
50    /// Parse a method from a string, upper-casing it.
51    pub fn new(s: &str) -> Self {
52        Self(s.to_uppercase())
53    }
54}
55
56impl FromStr for Method {
57    type Err = std::convert::Infallible;
58    fn from_str(s: &str) -> Result<Self, Self::Err> {
59        Ok(Self::new(s))
60    }
61}
62
63impl std::fmt::Display for Method {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        f.write_str(&self.0)
66    }
67}
68
69/// A registered stub response.
70#[derive(Debug, Clone)]
71struct Stub {
72    status: u16,
73    body: Vec<u8>,
74    content_type: String,
75}
76
77/// A captured incoming request for post-hoc assertions.
78#[derive(Debug, Clone)]
79pub struct CapturedRequest {
80    /// The HTTP method, upper-cased.
81    pub method: String,
82    /// The request path (including any query string), e.g. `/users/1?expand=1`.
83    pub path: String,
84    /// The request body (empty for GETs).
85    pub body: Vec<u8>,
86    /// Parsed query parameters (from the path's `?...` portion).
87    pub query: HashMap<String, String>,
88}
89
90impl CapturedRequest {
91    /// The request path without the query string.
92    pub fn path_only(&self) -> &str {
93        self.path.split('?').next().unwrap_or(&self.path)
94    }
95
96    /// The request body decoded as UTF-8 (lossy).
97    pub fn body_str(&self) -> String {
98        String::from_utf8_lossy(&self.body).into_owned()
99    }
100}
101
102/// Shared, thread-safe state for a running stub server.
103struct Inner {
104    stubs: Mutex<HashMap<(Method, String), Stub>>,
105    requests: Mutex<Vec<CapturedRequest>>,
106}
107
108/// An in-process HTTP stub server.
109///
110/// Create with [`HttpStub::new`] (binds a random free port via `tpt-port-scout`),
111/// register route responses with [`HttpStub::on`], and assert with
112/// [`HttpStub::assert_called_once`] / [`HttpStub::requests`].
113///
114/// The server runs in background threads and is shut down (and expectations
115/// checked) when the `HttpStub` is dropped.
116pub struct HttpStub {
117    inner: Arc<Inner>,
118    base_url: String,
119    shutdown: Option<mpsc::Sender<()>>,
120    handle: Option<thread::JoinHandle<()>>,
121}
122
123impl HttpStub {
124    /// Start a stub server on a random free loopback port.
125    ///
126    /// # Panics
127    ///
128    /// Panics if no free port can be reserved (extremely unlikely).
129    #[allow(clippy::new_without_default)]
130    pub fn new() -> Self {
131        let ports = PortSet::reserve_one().expect("failed to reserve a free port");
132        let listener = ports
133            .into_std_listener()
134            .expect("reservation must hold one listener");
135        let addr = listener.local_addr().expect("listener has an address");
136        let base_url = format!("http://{addr}");
137
138        let inner = Arc::new(Inner {
139            stubs: Mutex::new(HashMap::new()),
140            requests: Mutex::new(Vec::new()),
141        });
142
143        let (tx, rx) = mpsc::channel::<()>();
144        let inner_srv = Arc::clone(&inner);
145        let handle = thread::spawn(move || {
146            // Stop accepting new connections once a shutdown signal arrives.
147            let _ = listener.set_nonblocking(true);
148            loop {
149                match rx.try_recv() {
150                    Ok(()) | Err(mpsc::TryRecvError::Disconnected) => break,
151                    Err(mpsc::TryRecvError::Empty) => {}
152                }
153                match listener.accept() {
154                    Ok((stream, _)) => {
155                        let inner = Arc::clone(&inner_srv);
156                        thread::spawn(move || handle_conn(stream, &inner));
157                    }
158                    Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
159                        thread::sleep(std::time::Duration::from_millis(5));
160                    }
161                    Err(_) => break,
162                }
163            }
164        });
165
166        Self {
167            inner,
168            base_url,
169            shutdown: Some(tx),
170            handle: Some(handle),
171        }
172    }
173
174    /// Register a stubbed response for `method` + `path`.
175    ///
176    /// Subsequent requests to that route return `status` with `body`. Multiple
177    /// calls for the same route overwrite the previous stub.
178    pub fn on(&self, method: impl AsRef<str>, path: &str) -> StubBuilder<'_> {
179        StubBuilder {
180            stub: self,
181            method: Method::new(method.as_ref()),
182            path: path.to_string(),
183        }
184    }
185
186    /// The base URL clients should target, e.g. `http://127.0.0.1:54321`.
187    pub fn base_url(&self) -> String {
188        self.base_url.clone()
189    }
190
191    /// All captured requests, in arrival order.
192    pub fn requests(&self) -> Vec<CapturedRequest> {
193        self.inner.requests.lock().expect("poisoned").clone()
194    }
195
196    /// The most recent captured request, if any.
197    pub fn last_request(&self) -> Option<CapturedRequest> {
198        self.inner
199            .requests
200            .lock()
201            .expect("poisoned")
202            .last()
203            .cloned()
204    }
205
206    /// Number of requests received.
207    pub fn call_count(&self) -> usize {
208        self.inner.requests.lock().expect("poisoned").len()
209    }
210
211    /// Assert exactly one request has been received.
212    #[track_caller]
213    pub fn assert_called_once(&self) {
214        let n = self.call_count();
215        assert!(n == 1, "expected exactly 1 call, but the stub received {n}");
216    }
217
218    /// Assert exactly `n` requests have been received.
219    #[track_caller]
220    pub fn assert_called_n(&self, n: usize) {
221        let actual = self.call_count();
222        assert!(
223            actual == n,
224            "expected {n} calls, but the stub received {actual}"
225        );
226    }
227
228    /// Assert at least one request has been received (default "missing stub → 500"
229    /// behaviour means the route must exist to get a 2xx).
230    #[track_caller]
231    pub fn assert_called(&self) {
232        assert!(
233            self.call_count() >= 1,
234            "expected the stub to be called at least once"
235        );
236    }
237}
238
239/// Builder returned by [`HttpStub::on`] to specify the response.
240pub struct StubBuilder<'a> {
241    stub: &'a HttpStub,
242    method: Method,
243    path: String,
244}
245
246impl StubBuilder<'_> {
247    /// Respond with `status` and a UTF-8 `body`.
248    pub fn respond(self, status: u16, body: impl AsRef<str>) {
249        self.respond_raw(
250            status,
251            "text/plain; charset=utf-8",
252            body.as_ref().as_bytes().to_vec(),
253        );
254    }
255
256    /// Respond with `status` and a raw byte `body` (`content_type` advertised).
257    pub fn respond_raw(self, status: u16, content_type: &str, body: Vec<u8>) {
258        let mut stubs = self.stub.inner.stubs.lock().expect("poisoned");
259        stubs.insert(
260            (self.method, self.path),
261            Stub {
262                status,
263                body,
264                content_type: content_type.to_string(),
265            },
266        );
267    }
268
269    /// Respond with `status` and a JSON-encoded `value`.
270    pub fn respond_json(self, status: u16, value: &impl serde::Serialize) {
271        match serde_json::to_vec(value) {
272            Ok(bytes) => self.respond_raw(status, "application/json; charset=utf-8", bytes),
273            Err(e) => panic!("failed to serialise stub JSON body: {e}"),
274        }
275    }
276}
277
278fn handle_conn(mut stream: TcpStream, inner: &Arc<Inner>) {
279    // Read the request line + headers + body (bounded). We don't need a full
280    // HTTP parser — just enough to route and echo.
281    let mut buf = Vec::with_capacity(1024);
282    let mut byte = [0u8; 1];
283    // Read until we have headers (blank line) and then any Content-Length body.
284    let mut header_end = None;
285    let mut total = 0usize;
286    while total < 64 * 1024 {
287        match stream.read(&mut byte) {
288            Ok(0) => break,
289            Ok(_) => {
290                buf.push(byte[0]);
291                total += 1;
292                if let Some(pos) = find_header_end(&buf) {
293                    header_end = Some(pos);
294                    break;
295                }
296            }
297            Err(_) => break,
298        }
299    }
300
301    let header_end = header_end.unwrap_or(buf.len());
302    let header_bytes = &buf[..header_end];
303    let headers = String::from_utf8_lossy(header_bytes);
304
305    let mut lines = headers.lines();
306    let request_line = lines.next().unwrap_or("").to_string();
307    let mut parts = request_line.split_whitespace();
308    let method = parts.next().unwrap_or("").to_uppercase();
309    let full_path = parts.next().unwrap_or("/").to_string();
310
311    // Determine body length from Content-Length.
312    let mut content_length = 0usize;
313    for line in lines {
314        if let Some((k, v)) = line.split_once(':') {
315            if k.trim().eq_ignore_ascii_case("content-length") {
316                content_length = v.trim().parse().unwrap_or(0);
317            }
318        }
319    }
320    let mut body = Vec::new();
321    if content_length > 0 {
322        body.extend_from_slice(&buf[header_end..]);
323        while body.len() < content_length {
324            let mut chunk = [0u8; 1024];
325            match stream.read(&mut chunk) {
326                Ok(0) => break,
327                Ok(n) => body.extend_from_slice(&chunk[..n]),
328                Err(_) => break,
329            }
330        }
331        body.truncate(content_length);
332    }
333
334    let path_only = full_path.split('?').next().unwrap_or("/").to_string();
335    let query = parse_query(&full_path);
336
337    let captured = CapturedRequest {
338        method: method.clone(),
339        path: full_path,
340        body,
341        query,
342    };
343    inner.requests.lock().expect("poisoned").push(captured);
344
345    // Route lookup.
346    let stub = {
347        let stubs = inner.stubs.lock().expect("poisoned");
348        stubs
349            .get(&(Method::new(&method), path_only.clone()))
350            .cloned()
351    };
352
353    match stub {
354        Some(stub) => {
355            let _ = write_response(&mut stream, stub.status, &stub.content_type, &stub.body);
356        }
357        None => {
358            let body = format!("no stub registered for {method} {path_only}");
359            let _ = write_response(
360                &mut stream,
361                500,
362                "text/plain; charset=utf-8",
363                body.as_bytes(),
364            );
365        }
366    }
367}
368
369fn find_header_end(buf: &[u8]) -> Option<usize> {
370    // Detect "\r\n\r\n" or "\n\n".
371    if buf.len() >= 4 {
372        for i in 0..=buf.len() - 4 {
373            if buf[i] == b'\r' && buf[i + 1] == b'\n' && buf[i + 2] == b'\r' && buf[i + 3] == b'\n'
374            {
375                return Some(i + 4);
376            }
377        }
378    }
379    if buf.len() >= 2 {
380        for i in 0..=buf.len() - 2 {
381            if buf[i] == b'\n' && buf[i + 1] == b'\n' {
382                return Some(i + 2);
383            }
384        }
385    }
386    None
387}
388
389fn parse_query(path: &str) -> HashMap<String, String> {
390    let mut map = HashMap::new();
391    if let Some(q) = path.split_once('?').map(|(_, q)| q) {
392        for pair in q.split('&') {
393            if pair.is_empty() {
394                continue;
395            }
396            let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
397            map.insert(percent_decode(k), percent_decode(v));
398        }
399    }
400    map
401}
402
403fn percent_decode(s: &str) -> String {
404    // Minimal decode for the common '%XX' escapes; leaves other chars intact.
405    let bytes = s.as_bytes();
406    let mut out = Vec::with_capacity(bytes.len());
407    let mut i = 0;
408    while i < bytes.len() {
409        if bytes[i] == b'%' && i + 2 < bytes.len() {
410            let hi = (bytes[i + 1] as char).to_digit(16);
411            let lo = (bytes[i + 2] as char).to_digit(16);
412            if let (Some(h), Some(l)) = (hi, lo) {
413                out.push((h * 16 + l) as u8);
414                i += 3;
415                continue;
416            }
417        }
418        out.push(bytes[i]);
419        i += 1;
420    }
421    String::from_utf8_lossy(&out).into_owned()
422}
423
424fn write_response(
425    stream: &mut TcpStream,
426    status: u16,
427    content_type: &str,
428    body: &[u8],
429) -> std::io::Result<()> {
430    let reason = status_text(status);
431    let headers = format!(
432        "HTTP/1.1 {status} {reason}\r\n\
433         Content-Type: {content_type}\r\n\
434         Content-Length: {}\r\n\
435         Connection: close\r\n\r\n",
436        body.len()
437    );
438    stream.write_all(headers.as_bytes())?;
439    stream.write_all(body)?;
440    stream.flush()?;
441    Ok(())
442}
443
444fn status_text(status: u16) -> &'static str {
445    match status {
446        200 => "OK",
447        201 => "Created",
448        204 => "No Content",
449        400 => "Bad Request",
450        401 => "Unauthorized",
451        403 => "Forbidden",
452        404 => "Not Found",
453        500 => "Internal Server Error",
454        _ => "OK",
455    }
456}
457
458impl Drop for HttpStub {
459    fn drop(&mut self) {
460        // Signal the acceptor thread to stop and join it. Dropping `shutdown`
461        // (the sender) also disconnects the channel. Any open per-request
462        // threads finish on their own.
463        if let Some(tx) = self.shutdown.take() {
464            let _ = tx.send(());
465        }
466        if let Some(handle) = self.handle.take() {
467            let _ = handle.join();
468        }
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475    use std::net::TcpStream as Client;
476
477    fn get(stub: &HttpStub, method: &str, path: &str) -> (u16, String) {
478        let url = stub.base_url();
479        let mut stream = Client::connect(url.trim_start_matches("http://")).unwrap();
480        let req =
481            format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n");
482        stream.write_all(req.as_bytes()).unwrap();
483        stream.flush().unwrap();
484        let mut resp = String::new();
485        stream.read_to_string(&mut resp).unwrap();
486        // Split status line.
487        let status_line = resp.lines().next().unwrap_or("");
488        let code: u16 = status_line
489            .split_whitespace()
490            .nth(1)
491            .and_then(|s| s.parse().ok())
492            .unwrap_or(0);
493        let body = resp
494            .split_once("\r\n\r\n")
495            .map(|x| x.1)
496            .unwrap_or("")
497            .to_string();
498        (code, body)
499    }
500
501    #[test]
502    fn stub_responds_with_registered_body() {
503        let stub = HttpStub::new();
504        stub.on("GET", "/users/1").respond(200, "alice");
505        let (code, body) = get(&stub, "GET", "/users/1");
506        assert_eq!(code, 200);
507        assert_eq!(body, "alice");
508        stub.assert_called_once();
509    }
510
511    #[test]
512    fn method_is_case_insensitive() {
513        let stub = HttpStub::new();
514        stub.on("post", "/items").respond(201, "created");
515        let (code, body) = get(&stub, "POST", "/items");
516        assert_eq!(code, 201);
517        assert_eq!(body, "created");
518    }
519
520    #[test]
521    fn missing_stub_returns_500() {
522        let stub = HttpStub::new();
523        let (code, body) = get(&stub, "GET", "/nope");
524        assert_eq!(code, 500);
525        assert!(body.contains("no stub"));
526    }
527
528    #[test]
529    fn json_responses_are_serialised() {
530        let stub = HttpStub::new();
531        stub.on("GET", "/json")
532            .respond_json(200, &serde_json::json!({"name": "bob", "age": 30}));
533        let (code, body) = get(&stub, "GET", "/json");
534        assert_eq!(code, 200);
535        let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
536        assert_eq!(parsed["name"], "bob");
537        assert_eq!(parsed["age"], 30);
538    }
539
540    #[test]
541    fn captures_request_and_query() {
542        let stub = HttpStub::new();
543        stub.on("GET", "/search").respond(200, "ok");
544        let _ = get(&stub, "GET", "/search?q=rust&page=2");
545        let req = stub.last_request().expect("request captured");
546        assert_eq!(req.method, "GET");
547        assert_eq!(req.path_only(), "/search");
548        assert_eq!(req.query.get("q").map(String::as_str), Some("rust"));
549        assert_eq!(req.query.get("page").map(String::as_str), Some("2"));
550        stub.assert_called_once();
551    }
552
553    #[test]
554    fn parallel_stubs_do_not_interfere() {
555        use std::sync::Arc;
556        let a = Arc::new(HttpStub::new());
557        let b = Arc::new(HttpStub::new());
558        a.on("GET", "/a").respond(200, "from-a");
559        b.on("GET", "/b").respond(200, "from-b");
560
561        let a2 = Arc::clone(&a);
562        let b2 = Arc::clone(&b);
563        let t1 = thread::spawn(move || get(&a2, "GET", "/a"));
564        let t2 = thread::spawn(move || get(&b2, "GET", "/b"));
565        let (ra, rb) = (t1.join().unwrap(), t2.join().unwrap());
566        assert_eq!(ra, (200, "from-a".to_string()));
567        assert_eq!(rb, (200, "from-b".to_string()));
568
569        assert_eq!(a.call_count(), 1);
570        assert_eq!(b.call_count(), 1);
571        // Each stub only saw its own route.
572        assert_eq!(a.last_request().unwrap().path_only(), "/a");
573        assert_eq!(b.last_request().unwrap().path_only(), "/b");
574    }
575
576    #[test]
577    fn assert_called_n_counts() {
578        let stub = HttpStub::new();
579        stub.on("GET", "/x").respond(200, "x");
580        let _ = get(&stub, "GET", "/x");
581        let _ = get(&stub, "GET", "/x");
582        stub.assert_called_n(2);
583        assert_eq!(stub.requests().len(), 2);
584    }
585
586    #[test]
587    #[should_panic(expected = "expected exactly 1 call")]
588    fn assert_called_once_panics_with_zero() {
589        let stub = HttpStub::new();
590        stub.assert_called_once();
591    }
592
593    #[test]
594    fn base_url_is_loopback_with_port() {
595        let stub = HttpStub::new();
596        let url = stub.base_url();
597        assert!(url.starts_with("http://127.0.0.1:"));
598    }
599}