1use std::collections::{HashMap, VecDeque};
24use std::sync::{Arc, Mutex, MutexGuard, RwLock};
25
26use mlua::Lua;
27
28pub const MAX_RECORDED_CALLS: usize = 10_000;
31
32#[derive(Debug, Default)]
35pub struct Doubles {
36 fetch: Mutex<FetchMock>,
37 env: RwLock<HashMap<String, Option<String>>>,
39}
40
41impl Doubles {
42 pub fn new() -> Arc<Self> {
44 Arc::new(Self::default())
45 }
46
47 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 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 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 pub fn reset_env(&self) {
79 if let Ok(mut env) = self.env.write() {
80 env.clear();
81 }
82 }
83
84 pub(crate) fn env_override(&self, name: &str) -> Option<Option<String>> {
87 self.env.read().ok()?.get(name).cloned()
88 }
89}
90
91pub(crate) fn installed(lua: &Lua) -> Option<Arc<Doubles>> {
93 lua.app_data_ref::<Arc<Doubles>>().map(|d| d.clone())
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum UrlMatch {
99 Exact(String),
101 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#[derive(Debug, Clone)]
116pub struct FetchRule {
117 pub method: Option<String>,
119 pub url: UrlMatch,
121 pub status: u16,
123 pub headers: Vec<(String, String)>,
125 pub body: Vec<u8>,
127 pub times: Option<u32>,
130 pub error: Option<String>,
133}
134
135#[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#[derive(Debug, Clone)]
150pub struct FetchCall {
151 pub method: String,
153 pub url: String,
155 pub headers: Vec<(String, String)>,
157 pub body: Option<Vec<u8>>,
159 pub mocked: bool,
161}
162
163#[derive(Debug, Clone)]
165pub struct Canned {
166 pub status: u16,
168 pub headers: Vec<(String, String)>,
170 pub body: Vec<u8>,
172}
173
174#[derive(Debug)]
176pub enum FetchAnswer {
177 Canned(Canned),
179 Error(String),
181 PassThrough,
184 Refused,
186}
187
188#[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 pub fn add(&mut self, rule: FetchRule) {
200 self.rules.push(rule);
201 }
202
203 pub fn set_strict(&mut self, strict: bool) {
205 self.strict = strict;
206 }
207
208 pub fn calls(&self) -> impl Iterator<Item = &FetchCall> {
210 self.calls.iter()
211 }
212
213 pub fn dropped(&self) -> u64 {
216 self.dropped
217 }
218
219 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
268pub 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}