#![allow(dead_code)]
use std::collections::{HashMap, VecDeque};
use std::fmt::Write as _;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::JoinHandle;
static TEMP_FILE_SEQ: AtomicU64 = AtomicU64::new(0);
pub struct TempFile {
path: PathBuf,
}
impl TempFile {
pub fn new(prefix: &str, bytes: &[u8]) -> Self {
let seq = TEMP_FILE_SEQ.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!("{prefix}_{}_{seq}.tmp", std::process::id()));
std::fs::write(&path, bytes).expect("failed to write temporary test file");
Self { path }
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecordedRequest {
pub method: String,
pub path: String,
pub headers: HashMap<String, String>,
pub body: Vec<u8>,
}
impl RecordedRequest {
pub fn body_text(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
pub fn json_body<T: serde::de::DeserializeOwned>(&self) -> serde_json::Result<T> {
serde_json::from_slice(&self.body)
}
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.get(&name.to_ascii_lowercase())
.map(String::as_str)
}
}
#[derive(Clone, Debug)]
pub struct MockResponse {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
}
impl MockResponse {
pub fn json<T: serde::Serialize>(status: u16, value: &T) -> Self {
let body = serde_json::to_vec(value).expect("mock JSON serialization failed");
Self {
status,
headers: vec![("Content-Type".to_string(), "application/json".to_string())],
body,
}
}
pub fn text(status: u16, body: impl Into<String>) -> Self {
Self {
status,
headers: vec![(
"Content-Type".to_string(),
"text/plain; charset=utf-8".to_string(),
)],
body: body.into().into_bytes(),
}
}
pub fn bytes(status: u16, content_type: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
Self {
status,
headers: vec![("Content-Type".to_string(), content_type.into())],
body: body.into(),
}
}
pub fn empty(status: u16) -> Self {
Self {
status,
headers: Vec::new(),
body: Vec::new(),
}
}
pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
}
type RouteHandler = Arc<dyn Fn(&RecordedRequest) -> MockResponse + Send + Sync>;
#[derive(Default)]
struct MockState {
recorded: Vec<RecordedRequest>,
queued: VecDeque<MockResponse>,
routes: Vec<(Option<String>, String, RouteHandler)>,
prefix_routes: Vec<(Option<String>, String, RouteHandler)>,
}
pub struct MockServer {
addr: SocketAddr,
state: Arc<Mutex<MockState>>,
handle: JoinHandle<()>,
}
impl MockServer {
pub async fn start() -> Self {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("failed to bind mock server");
let addr = listener.local_addr().expect("failed to get local addr");
let state = Arc::new(Mutex::new(MockState::default()));
let state_clone = Arc::clone(&state);
let handle = tokio::spawn(async move {
loop {
let Ok((stream, _)) = listener.accept().await else {
break;
};
let state_per_conn = Arc::clone(&state_clone);
tokio::spawn(async move {
let _ = handle_connection(stream, state_per_conn).await;
});
}
});
Self {
addr,
state,
handle,
}
}
pub fn base_url(&self) -> String {
format!("http://{}", self.addr)
}
pub fn enqueue(&self, response: MockResponse) {
self.state.lock().unwrap().queued.push_back(response);
}
pub fn on_route<F>(
&self,
method: impl Into<Option<String>>,
path: impl Into<String>,
handler: F,
) where
F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
{
self.state
.lock()
.unwrap()
.routes
.push((method.into(), path.into(), Arc::new(handler)));
}
pub fn on_prefix<F>(
&self,
method: impl Into<Option<String>>,
prefix: impl Into<String>,
handler: F,
) where
F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
{
self.state.lock().unwrap().prefix_routes.push((
method.into(),
prefix.into(),
Arc::new(handler),
));
}
pub fn on_get<F>(&self, path: impl Into<String>, handler: F)
where
F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
{
self.on_route("GET".to_string(), path, handler);
}
pub fn on_post<F>(&self, path: impl Into<String>, handler: F)
where
F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
{
self.on_route("POST".to_string(), path, handler);
}
pub fn on_put<F>(&self, path: impl Into<String>, handler: F)
where
F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
{
self.on_route("PUT".to_string(), path, handler);
}
pub fn on_patch<F>(&self, path: impl Into<String>, handler: F)
where
F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
{
self.on_route("PATCH".to_string(), path, handler);
}
pub fn on_delete<F>(&self, path: impl Into<String>, handler: F)
where
F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
{
self.on_route("DELETE".to_string(), path, handler);
}
pub fn on_get_prefix<F>(&self, prefix: impl Into<String>, handler: F)
where
F: Fn(&RecordedRequest) -> MockResponse + Send + Sync + 'static,
{
self.on_prefix("GET".to_string(), prefix, handler);
}
pub fn recorded_requests(&self) -> Vec<RecordedRequest> {
self.state.lock().unwrap().recorded.clone()
}
}
impl Drop for MockServer {
fn drop(&mut self) {
self.handle.abort();
}
}
async fn handle_connection(
mut stream: TcpStream,
state: Arc<Mutex<MockState>>,
) -> std::io::Result<()> {
let mut buf = Vec::with_capacity(4096);
let mut chunk = [0_u8; 2048];
let header_end;
loop {
let n = stream.read(&mut chunk).await?;
if n == 0 {
return Ok(());
}
buf.extend_from_slice(&chunk[..n]);
if let Some(pos) = find_header_end(&buf) {
header_end = pos;
break;
}
}
let header_bytes = &buf[..header_end];
let header_text = String::from_utf8_lossy(header_bytes);
let mut lines = header_text.split("\r\n");
let request_line = lines.next().unwrap_or_default();
let mut parts = request_line.split_whitespace();
let method = parts.next().unwrap_or("GET").to_string();
let path = parts.next().unwrap_or("/").to_string();
let mut headers = HashMap::new();
let mut content_length: usize = 0;
for line in lines {
if let Some((k, v)) = line.split_once(':') {
let key = k.trim().to_ascii_lowercase();
let val = v.trim().to_string();
if key == "content-length" {
content_length = val.parse::<usize>().unwrap_or(0);
}
headers.insert(key, val);
}
}
let body_start = header_end + 4;
while buf.len() < body_start + content_length {
let n = stream.read(&mut chunk).await?;
if n == 0 {
break;
}
buf.extend_from_slice(&chunk[..n]);
}
let body_end = (body_start + content_length).min(buf.len());
let body = buf[body_start..body_end].to_vec();
let recorded = RecordedRequest {
method,
path,
headers,
body,
};
let response = dispatch(&state, &recorded);
write_response(&mut stream, &response).await
}
fn dispatch(state: &Arc<Mutex<MockState>>, req: &RecordedRequest) -> MockResponse {
let handler_opt = {
let mut guard = state.lock().unwrap();
guard.recorded.push(req.clone());
let exact = guard
.routes
.iter()
.rev()
.find(|(m, p, _)| {
m.as_ref()
.is_none_or(|m| m.eq_ignore_ascii_case(&req.method))
&& *p == req.path
})
.map(|(_, _, h)| Arc::clone(h));
if exact.is_some() {
exact
} else {
let prefix = guard
.prefix_routes
.iter()
.rev()
.find(|(m, p, _)| {
m.as_ref()
.is_none_or(|m| m.eq_ignore_ascii_case(&req.method))
&& req.path.starts_with(p.as_str())
})
.map(|(_, _, h)| Arc::clone(h));
if prefix.is_some() {
prefix
} else if let Some(resp) = guard.queued.pop_front() {
return resp;
} else {
None
}
}
};
match handler_opt {
Some(handler) => handler(req),
None => MockResponse::text(
404,
format!("no mock route for {} {}", req.method, req.path),
),
}
}
async fn write_response(stream: &mut TcpStream, resp: &MockResponse) -> std::io::Result<()> {
let reason = status_reason(resp.status);
let mut head = format!(
"HTTP/1.1 {} {}\r\nContent-Length: {}\r\nConnection: close\r\n",
resp.status,
reason,
resp.body.len()
);
for (k, v) in &resp.headers {
let _ = write!(head, "{k}: {v}\r\n");
}
head.push_str("\r\n");
stream.write_all(head.as_bytes()).await?;
if !resp.body.is_empty() {
stream.write_all(&resp.body).await?;
}
stream.flush().await
}
fn status_reason(code: u16) -> &'static str {
match code {
200 => "OK",
201 => "Created",
204 => "No Content",
301 => "Moved Permanently",
302 => "Found",
307 => "Temporary Redirect",
308 => "Permanent Redirect",
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
429 => "Too Many Requests",
500 => "Internal Server Error",
502 => "Bad Gateway",
503 => "Service Unavailable",
_ => "OK",
}
}
fn find_header_end(buf: &[u8]) -> Option<usize> {
buf.windows(4).position(|w| w == b"\r\n\r\n")
}