Skip to main content

nitr_std/
testing.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! Test doubles for `nitr test`: canned outbound responses and
7//! environment overrides, installed by a test as **data** and read by the
8//! standard library at the seams that honour them.
9//!
10//! A test file and the server's pooled states are separate Lua universes,
11//! so a double cannot be a Lua function patched into `nitr.*`: it would
12//! change the test's state and nothing a handler sees. Instead the runner
13//! puts one [`Doubles`] into the app data of every state it builds — the
14//! pooled ones through `ServerBuilder::setup`, which also runs on a
15//! poison rebuild and a reload, and its own test state directly — and the
16//! setters live under `nitr.test`, which only the runner registers.
17//!
18//! Absent app data means no double: that is the production path, and it
19//! costs each seam one app-data lookup. The types here are plain data, so
20//! the module compiles in every feature set even though the fetch seam
21//! exists only with `fetch`.
22
23use std::collections::{HashMap, VecDeque};
24use std::sync::{Arc, Mutex, MutexGuard, RwLock};
25
26use mlua::Lua;
27
28/// How many outbound calls a test records before the oldest are dropped:
29/// a chatty handler must not grow the record without bound.
30pub const MAX_RECORDED_CALLS: usize = 10_000;
31
32/// Every double a test can install, shared by the test state and every
33/// pooled state of the server under test.
34#[derive(Debug, Default)]
35pub struct Doubles {
36    fetch: Mutex<FetchMock>,
37    /// Environment overrides: `Some(value)` sets, `None` unsets.
38    env: RwLock<HashMap<String, Option<String>>>,
39}
40
41impl Doubles {
42    /// An empty set of doubles, ready to share.
43    pub fn new() -> Arc<Self> {
44        Arc::new(Self::default())
45    }
46
47    /// Clears every double: rules, recorded calls, the strict flag and
48    /// the environment overrides. The runner calls it before every test.
49    pub fn reset(&self) {
50        if let Ok(mut fetch) = self.fetch.lock() {
51            *fetch = FetchMock::default();
52        }
53        if let Ok(mut env) = self.env.write() {
54            env.clear();
55        }
56    }
57
58    /// The outbound-request double.
59    ///
60    /// # Errors
61    ///
62    /// Only when a panic poisoned the lock, which nothing here can cause.
63    pub fn fetch(&self) -> mlua::Result<MutexGuard<'_, FetchMock>> {
64        self.fetch
65            .lock()
66            .map_err(|_| mlua::Error::RuntimeError("the fetch double lock is poisoned".into()))
67    }
68
69    /// Overrides one environment variable: `Some` sets it, `None` makes it
70    /// read as unset. The `[env]` policy still applies on top.
71    pub fn set_env(&self, name: &str, value: Option<String>) {
72        if let Ok(mut env) = self.env.write() {
73            env.insert(name.to_string(), value);
74        }
75    }
76
77    /// Removes every environment override.
78    pub fn reset_env(&self) {
79        if let Ok(mut env) = self.env.write() {
80            env.clear();
81        }
82    }
83
84    /// The override for `name`, when one is installed: `Some(None)` is an
85    /// explicit unset.
86    pub(crate) fn env_override(&self, name: &str) -> Option<Option<String>> {
87        self.env.read().ok()?.get(name).cloned()
88    }
89}
90
91/// The doubles installed on this state, if any.
92pub(crate) fn installed(lua: &Lua) -> Option<Arc<Doubles>> {
93    lua.app_data_ref::<Arc<Doubles>>().map(|d| d.clone())
94}
95
96/// How a rule matches a request URL.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum UrlMatch {
99    /// The whole URL, as the client serializes it.
100    Exact(String),
101    /// A prefix, written with a trailing `*` (`https://api.example/*`).
102    Prefix(String),
103}
104
105impl UrlMatch {
106    fn matches(&self, url: &str) -> bool {
107        match self {
108            UrlMatch::Exact(expected) => url == expected,
109            UrlMatch::Prefix(prefix) => url.starts_with(prefix.as_str()),
110        }
111    }
112}
113
114/// One canned answer for `nitr.fetch`.
115#[derive(Debug, Clone)]
116pub struct FetchRule {
117    /// The method to match, uppercase; `None` matches any.
118    pub method: Option<String>,
119    /// The URL to match.
120    pub url: UrlMatch,
121    /// The status of the canned response.
122    pub status: u16,
123    /// Its headers, in order.
124    pub headers: Vec<(String, String)>,
125    /// Its body.
126    pub body: Vec<u8>,
127    /// How many requests it answers before falling through; `None` is
128    /// unlimited.
129    pub times: Option<u32>,
130    /// A transport failure to raise instead of answering: the request
131    /// fails the way a reset or a timeout would, and is retryable.
132    pub error: Option<String>,
133}
134
135/// The failure a `t.fetch.mock { error = ... }` rule raises.
136#[derive(Debug)]
137pub struct MockedFailure(pub String);
138
139impl std::fmt::Display for MockedFailure {
140    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141        write!(f, "fetch failed (mocked): {}", self.0)
142    }
143}
144
145impl std::error::Error for MockedFailure {}
146
147/// One outbound call made while the doubles were installed, whether a
148/// rule answered it or not.
149#[derive(Debug, Clone)]
150pub struct FetchCall {
151    /// The request method, uppercase.
152    pub method: String,
153    /// The URL as the client serialized it.
154    pub url: String,
155    /// The request headers, in order.
156    pub headers: Vec<(String, String)>,
157    /// The request body, when it had one.
158    pub body: Option<Vec<u8>>,
159    /// Whether a rule answered it.
160    pub mocked: bool,
161}
162
163/// The canned response a matched rule produced.
164#[derive(Debug, Clone)]
165pub struct Canned {
166    /// Response status.
167    pub status: u16,
168    /// Response headers, in order.
169    pub headers: Vec<(String, String)>,
170    /// Response body.
171    pub body: Vec<u8>,
172}
173
174/// What the double says about one outbound request.
175#[derive(Debug)]
176pub enum FetchAnswer {
177    /// A rule matched: answer with this instead of sending.
178    Canned(Canned),
179    /// A rule matched and stands for a transport failure.
180    Error(String),
181    /// No rule matched and the double is not strict: send it for real,
182    /// down the unchanged path, policy and resolver included.
183    PassThrough,
184    /// No rule matched and the double is strict: refuse.
185    Refused,
186}
187
188/// Canned responses, the recorded calls, and the strict flag.
189#[derive(Debug, Default)]
190pub struct FetchMock {
191    rules: Vec<FetchRule>,
192    calls: VecDeque<FetchCall>,
193    strict: bool,
194    dropped: u64,
195}
196
197impl FetchMock {
198    /// Adds a rule; rules are tried in the order they were added.
199    pub fn add(&mut self, rule: FetchRule) {
200        self.rules.push(rule);
201    }
202
203    /// Whether an unmatched request is refused instead of sent.
204    pub fn set_strict(&mut self, strict: bool) {
205        self.strict = strict;
206    }
207
208    /// The calls recorded so far, oldest first.
209    pub fn calls(&self) -> impl Iterator<Item = &FetchCall> {
210        self.calls.iter()
211    }
212
213    /// How many of the oldest calls were dropped past
214    /// [`MAX_RECORDED_CALLS`].
215    pub fn dropped(&self) -> u64 {
216        self.dropped
217    }
218
219    /// Records one outbound request and decides its fate: the first rule
220    /// that matches (method and URL) and has uses left answers it and
221    /// spends one use.
222    pub fn answer(
223        &mut self,
224        method: &str,
225        url: &str,
226        headers: Vec<(String, String)>,
227        body: Option<Vec<u8>>,
228    ) -> FetchAnswer {
229        let rule = self.rules.iter_mut().find(|rule| {
230            rule.method
231                .as_deref()
232                .is_none_or(|m| m.eq_ignore_ascii_case(method))
233                && rule.url.matches(url)
234                && rule.times.is_none_or(|left| left > 0)
235        });
236        let answer = match rule {
237            Some(rule) => {
238                if let Some(left) = &mut rule.times {
239                    *left -= 1;
240                }
241                match &rule.error {
242                    Some(message) => FetchAnswer::Error(message.clone()),
243                    None => FetchAnswer::Canned(Canned {
244                        status: rule.status,
245                        headers: rule.headers.clone(),
246                        body: rule.body.clone(),
247                    }),
248                }
249            }
250            None if self.strict => FetchAnswer::Refused,
251            None => FetchAnswer::PassThrough,
252        };
253        if self.calls.len() >= MAX_RECORDED_CALLS {
254            self.calls.pop_front();
255            self.dropped += 1;
256        }
257        self.calls.push_back(FetchCall {
258            method: method.to_ascii_uppercase(),
259            url: url.to_string(),
260            headers,
261            body,
262            mocked: matches!(answer, FetchAnswer::Canned(_) | FetchAnswer::Error(_)),
263        });
264        answer
265    }
266}
267
268/// The value `session:save` would write for `data`: the JSON payload
269/// (with the expiry when `max_age` is set) signed for `name` — so a test
270/// can put a session into a client's jar without a login round trip.
271///
272/// # Errors
273///
274/// The same as `session:save`: a secret under 16 bytes, reserved keys,
275/// values that are not JSON, or a payload over the cookie bound.
276pub fn session_cookie_value(
277    data: &mlua::Table,
278    name: &str,
279    secret: &str,
280    max_age: Option<i64>,
281) -> mlua::Result<String> {
282    crate::session::signed_value(data, name, secret, max_age)
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288
289    fn rule(method: Option<&str>, url: UrlMatch, times: Option<u32>) -> FetchRule {
290        FetchRule {
291            method: method.map(str::to_string),
292            url,
293            status: 202,
294            headers: vec![("content-type".into(), "text/plain".into())],
295            body: b"canned".to_vec(),
296            times,
297            error: None,
298        }
299    }
300
301    fn status(answer: FetchAnswer) -> Option<u16> {
302        match answer {
303            FetchAnswer::Canned(c) => Some(c.status),
304            _ => None,
305        }
306    }
307
308    #[test]
309    fn exact_and_prefix_rules_match_what_they_say() {
310        let mut mock = FetchMock::default();
311        mock.add(rule(
312            None,
313            UrlMatch::Exact("https://hooks.example/notes".into()),
314            None,
315        ));
316        mock.add(rule(
317            None,
318            UrlMatch::Prefix("https://api.example/".into()),
319            None,
320        ));
321        let mut ask = |url: &str| status(mock.answer("GET", url, Vec::new(), None));
322        assert_eq!(ask("https://hooks.example/notes"), Some(202));
323        assert_eq!(ask("https://hooks.example/notes/1"), None, "exact is exact");
324        assert_eq!(ask("https://api.example/v1/rates"), Some(202));
325        assert_eq!(
326            ask("https://api.example.evil/"),
327            None,
328            "a prefix is a string prefix"
329        );
330    }
331
332    #[test]
333    fn methods_and_times_narrow_a_rule_and_the_first_match_wins() {
334        let mut mock = FetchMock::default();
335        mock.add(rule(
336            Some("POST"),
337            UrlMatch::Prefix("https://x/".into()),
338            Some(1),
339        ));
340        let mut fallback = rule(None, UrlMatch::Prefix("https://x/".into()), None);
341        fallback.status = 503;
342        mock.add(fallback);
343        assert_eq!(
344            status(mock.answer("get", "https://x/a", Vec::new(), None)),
345            Some(503)
346        );
347        assert_eq!(
348            status(mock.answer("post", "https://x/a", Vec::new(), None)),
349            Some(202)
350        );
351        assert_eq!(
352            status(mock.answer("POST", "https://x/a", Vec::new(), None)),
353            Some(503),
354            "a spent rule falls through to the next"
355        );
356    }
357
358    #[test]
359    fn strict_refuses_what_no_rule_matches_and_every_call_is_recorded() {
360        let mut mock = FetchMock::default();
361        mock.add(rule(None, UrlMatch::Exact("https://x/a".into()), None));
362        assert!(matches!(
363            mock.answer("GET", "https://x/b", Vec::new(), None),
364            FetchAnswer::PassThrough
365        ));
366        mock.set_strict(true);
367        assert!(matches!(
368            mock.answer("GET", "https://x/b", Vec::new(), None),
369            FetchAnswer::Refused
370        ));
371        mock.answer(
372            "post",
373            "https://x/a",
374            vec![("x-signature".into(), "sha256=1".into())],
375            Some(b"{}".to_vec()),
376        );
377        let calls: Vec<_> = mock.calls().collect();
378        assert_eq!(calls.len(), 3);
379        assert_eq!(calls[2].method, "POST");
380        assert!(calls[2].mocked);
381        assert!(!calls[1].mocked);
382        assert_eq!(calls[2].body.as_deref(), Some(&b"{}"[..]));
383    }
384
385    #[test]
386    fn the_call_record_is_bounded() {
387        let mut mock = FetchMock::default();
388        for i in 0..MAX_RECORDED_CALLS + 5 {
389            mock.answer("GET", &format!("https://x/{i}"), Vec::new(), None);
390        }
391        assert_eq!(mock.calls().count(), MAX_RECORDED_CALLS);
392        assert_eq!(mock.dropped(), 5);
393        assert_eq!(
394            mock.calls().next().map(|c| c.url.as_str()),
395            Some("https://x/5"),
396            "the oldest go first"
397        );
398    }
399
400    #[test]
401    fn reset_clears_every_double() {
402        let doubles = Doubles::new();
403        doubles.set_env("APP_KEY", Some("k".into()));
404        doubles
405            .fetch()
406            .expect("fetch")
407            .add(rule(None, UrlMatch::Prefix("https://".into()), None));
408        doubles.fetch().expect("fetch").set_strict(true);
409        doubles.reset();
410        assert_eq!(doubles.env_override("APP_KEY"), None);
411        let mut fetch = doubles.fetch().expect("fetch");
412        assert!(matches!(
413            fetch.answer("GET", "https://x/", Vec::new(), None),
414            FetchAnswer::PassThrough
415        ));
416    }
417}