use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, MutexGuard, RwLock};
use mlua::Lua;
pub const MAX_RECORDED_CALLS: usize = 10_000;
#[derive(Debug, Default)]
pub struct Doubles {
fetch: Mutex<FetchMock>,
env: RwLock<HashMap<String, Option<String>>>,
}
impl Doubles {
pub fn new() -> Arc<Self> {
Arc::new(Self::default())
}
pub fn reset(&self) {
if let Ok(mut fetch) = self.fetch.lock() {
*fetch = FetchMock::default();
}
if let Ok(mut env) = self.env.write() {
env.clear();
}
}
pub fn fetch(&self) -> mlua::Result<MutexGuard<'_, FetchMock>> {
self.fetch
.lock()
.map_err(|_| mlua::Error::RuntimeError("the fetch double lock is poisoned".into()))
}
pub fn set_env(&self, name: &str, value: Option<String>) {
if let Ok(mut env) = self.env.write() {
env.insert(name.to_string(), value);
}
}
pub fn reset_env(&self) {
if let Ok(mut env) = self.env.write() {
env.clear();
}
}
pub(crate) fn env_override(&self, name: &str) -> Option<Option<String>> {
self.env.read().ok()?.get(name).cloned()
}
}
pub(crate) fn installed(lua: &Lua) -> Option<Arc<Doubles>> {
lua.app_data_ref::<Arc<Doubles>>().map(|d| d.clone())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UrlMatch {
Exact(String),
Prefix(String),
}
impl UrlMatch {
fn matches(&self, url: &str) -> bool {
match self {
UrlMatch::Exact(expected) => url == expected,
UrlMatch::Prefix(prefix) => url.starts_with(prefix.as_str()),
}
}
}
#[derive(Debug, Clone)]
pub struct FetchRule {
pub method: Option<String>,
pub url: UrlMatch,
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
pub times: Option<u32>,
pub error: Option<String>,
}
#[derive(Debug)]
pub struct MockedFailure(pub String);
impl std::fmt::Display for MockedFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "fetch failed (mocked): {}", self.0)
}
}
impl std::error::Error for MockedFailure {}
#[derive(Debug, Clone)]
pub struct FetchCall {
pub method: String,
pub url: String,
pub headers: Vec<(String, String)>,
pub body: Option<Vec<u8>>,
pub mocked: bool,
}
#[derive(Debug, Clone)]
pub struct Canned {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
}
#[derive(Debug)]
pub enum FetchAnswer {
Canned(Canned),
Error(String),
PassThrough,
Refused,
}
#[derive(Debug, Default)]
pub struct FetchMock {
rules: Vec<FetchRule>,
calls: VecDeque<FetchCall>,
strict: bool,
dropped: u64,
}
impl FetchMock {
pub fn add(&mut self, rule: FetchRule) {
self.rules.push(rule);
}
pub fn set_strict(&mut self, strict: bool) {
self.strict = strict;
}
pub fn calls(&self) -> impl Iterator<Item = &FetchCall> {
self.calls.iter()
}
pub fn dropped(&self) -> u64 {
self.dropped
}
pub fn answer(
&mut self,
method: &str,
url: &str,
headers: Vec<(String, String)>,
body: Option<Vec<u8>>,
) -> FetchAnswer {
let rule = self.rules.iter_mut().find(|rule| {
rule.method
.as_deref()
.is_none_or(|m| m.eq_ignore_ascii_case(method))
&& rule.url.matches(url)
&& rule.times.is_none_or(|left| left > 0)
});
let answer = match rule {
Some(rule) => {
if let Some(left) = &mut rule.times {
*left -= 1;
}
match &rule.error {
Some(message) => FetchAnswer::Error(message.clone()),
None => FetchAnswer::Canned(Canned {
status: rule.status,
headers: rule.headers.clone(),
body: rule.body.clone(),
}),
}
}
None if self.strict => FetchAnswer::Refused,
None => FetchAnswer::PassThrough,
};
if self.calls.len() >= MAX_RECORDED_CALLS {
self.calls.pop_front();
self.dropped += 1;
}
self.calls.push_back(FetchCall {
method: method.to_ascii_uppercase(),
url: url.to_string(),
headers,
body,
mocked: matches!(answer, FetchAnswer::Canned(_) | FetchAnswer::Error(_)),
});
answer
}
}
pub fn session_cookie_value(
data: &mlua::Table,
name: &str,
secret: &str,
max_age: Option<i64>,
) -> mlua::Result<String> {
crate::session::signed_value(data, name, secret, max_age)
}
#[cfg(test)]
mod tests {
use super::*;
fn rule(method: Option<&str>, url: UrlMatch, times: Option<u32>) -> FetchRule {
FetchRule {
method: method.map(str::to_string),
url,
status: 202,
headers: vec![("content-type".into(), "text/plain".into())],
body: b"canned".to_vec(),
times,
error: None,
}
}
fn status(answer: FetchAnswer) -> Option<u16> {
match answer {
FetchAnswer::Canned(c) => Some(c.status),
_ => None,
}
}
#[test]
fn exact_and_prefix_rules_match_what_they_say() {
let mut mock = FetchMock::default();
mock.add(rule(
None,
UrlMatch::Exact("https://hooks.example/notes".into()),
None,
));
mock.add(rule(
None,
UrlMatch::Prefix("https://api.example/".into()),
None,
));
let mut ask = |url: &str| status(mock.answer("GET", url, Vec::new(), None));
assert_eq!(ask("https://hooks.example/notes"), Some(202));
assert_eq!(ask("https://hooks.example/notes/1"), None, "exact is exact");
assert_eq!(ask("https://api.example/v1/rates"), Some(202));
assert_eq!(
ask("https://api.example.evil/"),
None,
"a prefix is a string prefix"
);
}
#[test]
fn methods_and_times_narrow_a_rule_and_the_first_match_wins() {
let mut mock = FetchMock::default();
mock.add(rule(
Some("POST"),
UrlMatch::Prefix("https://x/".into()),
Some(1),
));
let mut fallback = rule(None, UrlMatch::Prefix("https://x/".into()), None);
fallback.status = 503;
mock.add(fallback);
assert_eq!(
status(mock.answer("get", "https://x/a", Vec::new(), None)),
Some(503)
);
assert_eq!(
status(mock.answer("post", "https://x/a", Vec::new(), None)),
Some(202)
);
assert_eq!(
status(mock.answer("POST", "https://x/a", Vec::new(), None)),
Some(503),
"a spent rule falls through to the next"
);
}
#[test]
fn strict_refuses_what_no_rule_matches_and_every_call_is_recorded() {
let mut mock = FetchMock::default();
mock.add(rule(None, UrlMatch::Exact("https://x/a".into()), None));
assert!(matches!(
mock.answer("GET", "https://x/b", Vec::new(), None),
FetchAnswer::PassThrough
));
mock.set_strict(true);
assert!(matches!(
mock.answer("GET", "https://x/b", Vec::new(), None),
FetchAnswer::Refused
));
mock.answer(
"post",
"https://x/a",
vec![("x-signature".into(), "sha256=1".into())],
Some(b"{}".to_vec()),
);
let calls: Vec<_> = mock.calls().collect();
assert_eq!(calls.len(), 3);
assert_eq!(calls[2].method, "POST");
assert!(calls[2].mocked);
assert!(!calls[1].mocked);
assert_eq!(calls[2].body.as_deref(), Some(&b"{}"[..]));
}
#[test]
fn the_call_record_is_bounded() {
let mut mock = FetchMock::default();
for i in 0..MAX_RECORDED_CALLS + 5 {
mock.answer("GET", &format!("https://x/{i}"), Vec::new(), None);
}
assert_eq!(mock.calls().count(), MAX_RECORDED_CALLS);
assert_eq!(mock.dropped(), 5);
assert_eq!(
mock.calls().next().map(|c| c.url.as_str()),
Some("https://x/5"),
"the oldest go first"
);
}
#[test]
fn reset_clears_every_double() {
let doubles = Doubles::new();
doubles.set_env("APP_KEY", Some("k".into()));
doubles
.fetch()
.expect("fetch")
.add(rule(None, UrlMatch::Prefix("https://".into()), None));
doubles.fetch().expect("fetch").set_strict(true);
doubles.reset();
assert_eq!(doubles.env_override("APP_KEY"), None);
let mut fetch = doubles.fetch().expect("fetch");
assert!(matches!(
fetch.answer("GET", "https://x/", Vec::new(), None),
FetchAnswer::PassThrough
));
}
}