use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum Staleness {
#[default]
Cached,
Strict {
max_cache_age: String,
},
Unchecked,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cached_round_trips() {
let s: Staleness = serde_json::from_str(r#"{"mode":"cached"}"#).unwrap();
assert_eq!(s, Staleness::Cached);
let back = serde_json::to_value(&s).unwrap();
assert_eq!(back["mode"], "cached");
}
#[test]
fn strict_requires_max_cache_age() {
let s: Staleness =
serde_json::from_str(r#"{"mode":"strict","max_cache_age":"5m"}"#).unwrap();
match s {
Staleness::Strict { max_cache_age } => assert_eq!(max_cache_age, "5m"),
other => panic!("expected strict, got {other:?}"),
}
}
#[test]
fn strict_without_max_cache_age_errors() {
let res: Result<Staleness, _> = serde_json::from_str(r#"{"mode":"strict"}"#);
assert!(res.is_err(), "expected error, got {res:?}");
}
#[test]
fn unchecked_round_trips() {
let s: Staleness = serde_json::from_str(r#"{"mode":"unchecked"}"#).unwrap();
assert_eq!(s, Staleness::Unchecked);
}
#[test]
fn default_is_cached() {
assert_eq!(Staleness::default(), Staleness::Cached);
}
#[test]
fn yaml_strict_parses() {
let yaml = r#"
mode: strict
max_cache_age: 0s
"#;
let s: Staleness = serde_yaml::from_str(yaml).unwrap();
assert!(matches!(s, Staleness::Strict { .. }));
}
#[test]
fn yaml_cached_minimal_form() {
let yaml = "mode: cached\n";
let s: Staleness = serde_yaml::from_str(yaml).unwrap();
assert_eq!(s, Staleness::Cached);
}
}