use shep_core::dogs::validate::{Proposed, Verdict};
#[must_use = "the body is what the dog writes back on its channel"]
pub fn validate_answer(params: Option<&str>, check: impl FnOnce(&Proposed) -> Verdict) -> String {
let Some(params) = params else {
return Verdict::refuse("shep sent no table to validate").body();
};
let Some(proposed) = Proposed::parse(params) else {
return Verdict::refuse("shep sent something that is not a proposed table").body();
};
check(&proposed).body()
}
#[cfg(test)]
mod tests {
use serde_json::{Value, json};
use super::*;
#[test]
fn a_check_that_accepts_answers_accept() {
let body = validate_answer(Some(r#"{"table":{"keep":2},"sheep":"api"}"#), |proposed| {
assert_eq!(proposed.sheep(), Some("api"));
assert_eq!(proposed.table().get("keep"), Some(&json!(2)));
Verdict::Accept
});
assert_eq!(body, r#"{"accept":true}"#);
}
#[test]
fn a_check_that_refuses_carries_its_reason_to_the_operator() {
let body = validate_answer(Some(r#"{"table":{"checkout":"/other"}}"#), |_| {
Verdict::refuse("this checkout belongs to another project")
});
assert_eq!(
serde_json::from_str::<Value>(&body).unwrap(),
json!({
"accept": false,
"reason": "this checkout belongs to another project"
})
);
}
#[test]
fn a_params_shep_never_sent_is_refused_without_asking_the_dog() {
for params in [None, Some(""), Some("not a table")] {
let body = validate_answer(params, |_| {
panic!("a dog is never asked about a table shep did not send")
});
assert_eq!(
serde_json::from_str::<Value>(&body)
.expect("the refusal is a verdict")
.get("accept")
.and_then(Value::as_bool),
Some(false),
"{params:?}"
);
}
}
}