Skip to main content

Crate tpt_http_stub

Crate tpt_http_stub 

Source
Expand description

Lightweight in-process HTTP stub server for tests.

tpt-http-stub spins up a real TCP HTTP server on a random free port (reserved via tpt-port-scout, so there are no TOCTOU races) and answers registered route stubs. It uses a blocking, single-thread-per-connection server — no async runtime required — which makes it ideal for synchronous tests.

§Quick start

use tpt_http_stub::HttpStub;
use std::io::{Read, Write};
use std::net::TcpStream;

let stub = HttpStub::new();
stub.on("GET", "/users/1").respond(200, "alice");

// Point any HTTP client at the base URL. Here we issue a raw request to keep
// the example dependency-free.
let host = stub.base_url().trim_start_matches("http://").to_string();
let mut s = TcpStream::connect(&host).unwrap();
s.write_all(b"GET /users/1 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").unwrap();
s.flush().unwrap();
let mut resp = String::new();
s.read_to_string(&mut resp).unwrap();
let body = resp.splitn(2, "\r\n\r\n").nth(1).unwrap();
assert_eq!(body, "alice");

stub.assert_called_once();

(In real tests drive the stub with any HTTP client — the example above uses a raw socket to stay dependency-free.)

Structs§

CapturedRequest
A captured incoming request for post-hoc assertions.
HttpStub
An in-process HTTP stub server.
Method
An HTTP method, stored as an upper-cased string for case-insensitive matching.
StubBuilder
Builder returned by HttpStub::on to specify the response.