159 lines · 4.9 KB · RustRaw
//! A small HTTP/1.1 server inside the test process: it records every request//! and answers each through the test's own handler.#![allow(dead_code)]use std::io::{BufRead, BufReader, Read, Write};use std::net::{TcpListener, TcpStream};use std::sync::{Arc, Mutex};use serde_json::Value;#[derive(Debug, Clone)]pub struct Request { pub method: String, pub path: String, pub headers: Vec<(String, String)>, pub body: Vec<u8>,}impl Request { pub fn header(&self, name: &str) -> Option<&str> { self.headers .iter() .find(|(key, _)| key.eq_ignore_ascii_case(name)) .map(|(_, value)| value.as_str()) } pub fn json(&self) -> Value { serde_json::from_slice(&self.body).expect("a JSON body") }}pub struct Answer { pub status: u16, pub body: Vec<u8>, /// The body's type when it is not JSON (a stored file's). pub kind: Option<String>,}impl Answer { pub fn json(status: u16, body: Value) -> Answer { Answer { status, body: serde_json::to_vec(&body).unwrap(), kind: None, } } pub fn empty(status: u16) -> Answer { Answer { status, body: Vec::new(), kind: None } }}type Handler = dyn Fn(&Request) -> Answer + Send + Sync;pub struct TestServer { pub url: String, seen: Arc<Mutex<Vec<Request>>>,}impl TestServer { pub fn start(handler: impl Fn(&Request) -> Answer + Send + Sync + 'static) -> TestServer { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); let seen = Arc::new(Mutex::new(Vec::new())); let handler: Arc<Handler> = Arc::new(handler); let recorded = Arc::clone(&seen); std::thread::spawn(move || { for stream in listener.incoming() { let Ok(stream) = stream else { continue }; let handler = Arc::clone(&handler); let recorded = Arc::clone(&recorded); std::thread::spawn(move || serve(stream, &*handler, &recorded)); } }); TestServer { url, seen } } pub fn requests(&self) -> Vec<Request> { self.seen.lock().unwrap().clone() } /// `METHOD path` of every request, in order. pub fn lines(&self) -> Vec<String> { self.requests() .iter() .map(|r| format!("{} {}", r.method, r.path)) .collect() }}fn serve(stream: TcpStream, handler: &Handler, seen: &Mutex<Vec<Request>>) { let mut writer = stream.try_clone().unwrap(); let mut reader = BufReader::new(stream); loop { let mut line = String::new(); if reader.read_line(&mut line).unwrap_or(0) == 0 { return; } let mut parts = line.split_whitespace(); let method = parts.next().unwrap_or("").to_string(); let path = parts.next().unwrap_or("").to_string(); let mut headers = Vec::new(); loop { let mut header = String::new(); reader.read_line(&mut header).unwrap(); let header = header.trim_end(); if header.is_empty() { break; } if let Some((key, value)) = header.split_once(':') { headers.push((key.trim().to_string(), value.trim().to_string())); } } let length = headers .iter() .find(|(k, _)| k.eq_ignore_ascii_case("content-length")) .and_then(|(_, v)| v.parse::<usize>().ok()) .unwrap_or(0); let mut body = vec![0; length]; reader.read_exact(&mut body).unwrap(); let request = Request { method, path, headers, body }; seen.lock().unwrap().push(request.clone()); let answer = handler(&request); let head_only = request.method == "HEAD"; let reason = match answer.status { 200 => "OK", 206 => "Partial Content", 401 => "Unauthorized", 404 => "Not Found", 409 => "Conflict", _ => "Status", }; let mut out = format!( "HTTP/1.1 {} {reason}\r\ncontent-type: {}\r\ncontent-length: {}\r\n\r\n", answer.status, answer.kind.as_deref().unwrap_or("application/json"), answer.body.len() ) .into_bytes(); if !head_only { out.extend_from_slice(&answer.body); } if writer.write_all(&out).is_err() { return; } }}pub mod helper;pub mod object;/// The fixture the Rust structs wrote, `crates/cotton-client/fixtures/import/<name>.json`.pub fn fixture(name: &str) -> Value { let path = cotton_store::manifest_dir() .join("../cotton-client/fixtures/import") .join(format!("{name}.json")); serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()}