Skip to main content

ocre/testing/
fake.rs

1//! [`FakeServer`]: a stand-in for another service's API, on `127.0.0.1`.
2
3use std::{
4    collections::BTreeMap,
5    io::{BufReader, Write as _},
6    net::{TcpListener, TcpStream},
7    sync::{Arc, Mutex},
8    thread,
9};
10
11use serde::de::DeserializeOwned;
12use serde_json::Value;
13
14/// A request the [`FakeServer`] received.
15///
16/// # Examples
17///
18/// ```
19/// use ocre::testing::FakeServer;
20///
21/// let server = FakeServer::start();
22/// let _ = ureq::post(&format!("{}/hook?x=1", server.url())).header("X-Event", "ping").send("{\"a\":1}");
23/// let request = server.requests().pop().unwrap();
24/// assert_eq!((request.method.as_str(), request.path.as_str()), ("POST", "/hook?x=1"));
25/// assert_eq!(request.header("x-event"), Some("ping"));
26/// assert_eq!(request.json::<serde_json::Value>()["a"], 1);
27/// ```
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct ReceivedRequest {
30    /// `GET`, `POST`...
31    pub method: String,
32    /// The path and query string (`/v1/jobs?limit=2`).
33    pub path: String,
34    /// Headers, lowercase names (the last value of a repeated header).
35    pub headers: BTreeMap<String, String>,
36    /// The body (chunked bodies decoded).
37    pub body: Vec<u8>,
38}
39
40impl ReceivedRequest {
41    /// The value of header `name` (case-insensitive).
42    pub fn header(&self, name: &str) -> Option<&str> {
43        self.headers.get(&name.to_ascii_lowercase()).map(String::as_str)
44    }
45
46    /// The body as text (invalid UTF-8 replaced).
47    pub fn text(&self) -> String {
48        String::from_utf8_lossy(&self.body).into_owned()
49    }
50
51    /// The body parsed as JSON.
52    ///
53    /// # Panics
54    ///
55    /// When the body is not JSON of type `T`.
56    #[track_caller]
57    pub fn json<T: DeserializeOwned>(&self) -> T {
58        serde_json::from_slice(&self.body).unwrap_or_else(|err| {
59            panic!("{} {}: the body is not the JSON expected ({err}): {}", self.method, self.path, self.text())
60        })
61    }
62}
63
64/// An answer of the fake: status, content type and body.
65#[derive(Debug, Clone)]
66struct Answer {
67    method: String,
68    prefix: String,
69    status: u16,
70    content_type: String,
71    body: Vec<u8>,
72}
73
74#[derive(Debug, Default)]
75struct State {
76    answers: Vec<Answer>,
77    requests: Vec<ReceivedRequest>,
78}
79
80/// A fake HTTP service on `127.0.0.1` for request tests: canned answers by method and path prefix, and every request it received.
81///
82/// `ocre test --e2e` runs the app in workerd on the same machine, so the
83/// app can call it. Point the app at [`url`](Self::url) for one client's
84/// requests with a test header ([`Client::header`](crate::testing::Client::header)
85/// and [`http::test_override`](crate::http::test_override)), or a
86/// webhook endpoint at it, then assert on [`requests`](Self::requests)
87/// (wrap the check in [`eventually`](crate::testing::eventually) when a
88/// job makes the call). A request no answer matches gets `404` with
89/// `{"error": "no fake answer"}`. The server runs until the test process
90/// ends; each request is served on its own thread.
91///
92/// # Examples
93///
94/// ```no_run
95/// use ocre::{serde_json::json, testing::{Client, FakeServer, eventually}};
96///
97/// #[test]
98/// #[ignore = "request test: run with `ocre test --e2e`"]
99/// fn checkout_creates_an_invoice() {
100///     let payments = FakeServer::start();
101///     payments.answer_json("POST", "/invoices", 201, &json!({"id": "inv_1", "url": "https://pay.example/inv_1"}));
102///     let mut client = Client::new().header("x-ocre-test-payments-api", payments.url());
103///     client.post("/checkout", &[("plan", "pro")]).assert_redirect_to("https://pay.example/inv_1");
104///     let invoice = eventually(|| payments.requests().into_iter().find(|r| r.path == "/invoices"));
105///     assert_eq!(invoice.json::<ocre::serde_json::Value>()["amount"], 900);
106/// }
107/// ```
108#[derive(Debug, Clone)]
109pub struct FakeServer {
110    url: String,
111    state: Arc<Mutex<State>>,
112}
113
114impl FakeServer {
115    /// Starts the server on a free port of `127.0.0.1`.
116    ///
117    /// # Panics
118    ///
119    /// When no port can be bound.
120    pub fn start() -> Self {
121        let listener = TcpListener::bind("127.0.0.1:0").expect("FakeServer: bind 127.0.0.1");
122        let url = format!("http://{}", listener.local_addr().expect("FakeServer: local address"));
123        let state = Arc::new(Mutex::new(State::default()));
124        let shared = Arc::clone(&state);
125        thread::spawn(move || {
126            for stream in listener.incoming().flatten() {
127                let state = Arc::clone(&shared);
128                thread::spawn(move || serve(stream, &state));
129            }
130        });
131        Self { url, state }
132    }
133
134    /// The base URL, `http://127.0.0.1:<port>`, without a trailing slash.
135    pub fn url(&self) -> &str {
136        &self.url
137    }
138
139    /// Answers `method` requests (`*` for any) whose path starts with `path_prefix` with `status` and `body` (`text/plain`).
140    ///
141    /// The newest matching answer wins, so a test can change an answer midway.
142    pub fn answer(&self, method: &str, path_prefix: &str, status: u16, body: &str) -> &Self {
143        self.add(method, path_prefix, status, "text/plain; charset=utf-8", body.as_bytes().to_vec())
144    }
145
146    /// [`answer`](Self::answer) with a JSON body (`application/json`).
147    pub fn answer_json(&self, method: &str, path_prefix: &str, status: u16, value: &Value) -> &Self {
148        self.add(method, path_prefix, status, "application/json", value.to_string().into_bytes())
149    }
150
151    fn add(&self, method: &str, prefix: &str, status: u16, content_type: &str, body: Vec<u8>) -> &Self {
152        let answer = Answer {
153            method: method.to_ascii_uppercase(),
154            prefix: prefix.to_owned(),
155            status,
156            content_type: content_type.to_owned(),
157            body,
158        };
159        self.state.lock().expect("FakeServer state").answers.push(answer);
160        self
161    }
162
163    /// Every request received so far, oldest first.
164    pub fn requests(&self) -> Vec<ReceivedRequest> {
165        self.state.lock().expect("FakeServer state").requests.clone()
166    }
167}
168
169/// Reads one request from `stream`, records it, and writes the answer.
170fn serve(stream: TcpStream, state: &Mutex<State>) {
171    let Ok(mut writer) = stream.try_clone() else { return };
172    let Some(request) = read_request(BufReader::new(stream)) else { return };
173    let answer = {
174        let mut state = state.lock().expect("FakeServer state");
175        let answer = state
176            .answers
177            .iter()
178            .rev()
179            .find(|answer| {
180                (answer.method == "*" || answer.method == request.method) && request.path.starts_with(&answer.prefix)
181            })
182            .cloned();
183        state.requests.push(request);
184        answer
185    };
186    let answer = answer.unwrap_or_else(|| Answer {
187        method: String::new(),
188        prefix: String::new(),
189        status: 404,
190        content_type: "application/json".to_owned(),
191        body: br#"{"error":"no fake answer"}"#.to_vec(),
192    });
193    let head = format!(
194        "HTTP/1.1 {} Fake\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
195        answer.status,
196        answer.content_type,
197        answer.body.len()
198    );
199    let _ = writer.write_all(head.as_bytes()).and_then(|()| writer.write_all(&answer.body));
200}
201
202/// Parses an HTTP/1.1 request: request line, headers, then a `Content-Length` or chunked body.
203pub(crate) fn read_request(mut reader: impl std::io::BufRead) -> Option<ReceivedRequest> {
204    let mut line = String::new();
205    reader.read_line(&mut line).ok()?;
206    let mut parts = line.split_whitespace();
207    let (method, path) = (parts.next()?.to_owned(), parts.next()?.to_owned());
208    let mut headers = BTreeMap::new();
209    loop {
210        let mut line = String::new();
211        if reader.read_line(&mut line).ok()? == 0 {
212            return None;
213        }
214        let line = line.trim_end();
215        if line.is_empty() {
216            break;
217        }
218        if let Some((name, value)) = line.split_once(':') {
219            headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_owned());
220        }
221    }
222    let mut body = Vec::new();
223    if headers.get("transfer-encoding").is_some_and(|value| value.eq_ignore_ascii_case("chunked")) {
224        loop {
225            let mut size = String::new();
226            reader.read_line(&mut size).ok()?;
227            let size = usize::from_str_radix(size.trim().split(';').next()?, 16).ok()?;
228            let mut chunk = vec![0; size + 2]; // the chunk and its CRLF
229            reader.read_exact(&mut chunk).ok()?;
230            if size == 0 {
231                break;
232            }
233            body.extend_from_slice(&chunk[..size]);
234        }
235    } else if let Some(length) = headers.get("content-length").and_then(|value| value.parse::<usize>().ok()) {
236        body.resize(length, 0);
237        reader.read_exact(&mut body).ok()?;
238    }
239    Some(ReceivedRequest { method, path, headers, body })
240}