use pretty_assertions::assert_eq;
use serde_json::{json, Value as Json};
use super::*;
const TWO_HOOKS: &str = r#"# My hooks.
version = 1
# Logs every tool call.
[[hook]]
id = "log"
on = "after_tool_use"
# How long it may run.
timeout = "1s" # generous
command = ["logger"]
env = ["TOKEN"]
# Notifies me.
[[hook]]
id = "notify"
on = "run_completed"
command = [ "notify-send", "done" ]
timeout = "2s"
"#;
const NOTIFY: &str = r#"
# Notifies me.
[[hook]]
id = "notify"
on = "run_completed"
command = [ "notify-send", "done" ]
timeout = "2s"
"#;
const LOG_EDITED: &str = r#"# My hooks.
version = 1
# Logs every tool call.
[[hook]]
id = "log"
on = "after_tool_use"
# How long it may run.
timeout = "5s" # generous
command = ["logger"]
tools = ["bash"]
"#;
fn put(id: &str, value: Json) -> HookConfigChange {
HookConfigChange::Put {
id: id.to_owned(),
value,
}
}
fn remove(id: &str) -> HookConfigChange {
HookConfigChange::Remove { id: id.to_owned() }
}
fn logger() -> Json {
json!({"on": "after_tool_use", "command": ["logger"], "timeout": "1s"})
}
#[test]
fn a_change_rewrites_only_the_hook_it_names() {
struct Case {
name: &'static str,
file: Option<&'static str>,
changes: Vec<HookConfigChange>,
expected: Result<String, HookEditError>,
}
let new_file = "version = 1\n\n[[hook]]\nid = \"log\"\non = \"after_tool_use\"\ncommand = [\"logger\"]\ntimeout = \"1s\"\n";
let cases = [
Case {
name: "a put into an absent file",
file: None,
changes: vec![put("log", logger())],
expected: Ok(new_file.to_owned()),
},
Case {
name: "a put into an empty file",
file: Some(""),
changes: vec![put("log", logger())],
expected: Ok(new_file.to_owned()),
},
Case {
name: "a put over a hook the file holds",
file: Some(TWO_HOOKS),
changes: vec![put(
"log",
json!({
"on": "after_tool_use",
"command": ["logger"],
"timeout": "5s",
"tools": ["bash"],
}),
)],
expected: Ok(format!("{LOG_EDITED}{NOTIFY}")),
},
Case {
name: "a put of a new hook",
file: Some(TWO_HOOKS),
changes: vec![put(
"fmt",
json!({"on": "after_tool_use", "command": ["fmt", "--all"], "timeout": "1s", "enabled": false}),
)],
expected: Ok(format!(
"{TWO_HOOKS}\n[[hook]]\nid = \"fmt\"\non = \"after_tool_use\"\ncommand = [\"fmt\", \"--all\"]\ntimeout = \"1s\"\nenabled = false\n"
)),
},
Case {
name: "a put that turns a hook back on leaves `enabled` out",
file: Some("version = 1\n\n[[hook]]\nid = \"log\"\non = \"after_tool_use\"\ncommand = [\"logger\"]\ntimeout = \"1s\"\nenabled = false\n"),
changes: vec![put(
"log",
json!({"on": "after_tool_use", "command": ["logger"], "timeout": "1s", "enabled": true}),
)],
expected: Ok(new_file.to_owned()),
},
Case {
name: "a remove",
file: Some(TWO_HOOKS),
changes: vec![remove("log")],
expected: Ok(format!("# My hooks.\nversion = 1\n{NOTIFY}")),
},
Case {
name: "a remove of the last hook",
file: Some(new_file),
changes: vec![remove("log")],
expected: Ok("version = 1\n".to_owned()),
},
Case {
name: "a remove of a hook the file lacks",
file: Some(TWO_HOOKS),
changes: vec![put("fmt", logger()), remove("nope")],
expected: Err(HookEditError::Missing { id: "nope".into() }),
},
Case {
name: "a put whose value holds its id",
file: Some(TWO_HOOKS),
changes: vec![put("log", json!({"id": "log", "on": "after_tool_use"}))],
expected: Err(HookEditError::HoldsId { id: "log".into() }),
},
Case {
name: "a put whose value is not a table",
file: Some(TWO_HOOKS),
changes: vec![put("log", json!(["logger"]))],
expected: Err(HookEditError::NotTable { id: "log".into() }),
},
Case {
name: "a put with a field TOML cannot hold",
file: Some(TWO_HOOKS),
changes: vec![put("log", json!({"on": "after_tool_use", "timeout": null}))],
expected: Err(HookEditError::Field {
id: "log".into(),
field: "timeout".into(),
problem: "must not be null".into(),
}),
},
];
for case in cases {
assert_eq!(
apply_hook_changes(case.file, &case.changes),
case.expected,
"{}",
case.name
);
}
}
#[test]
fn a_read_gives_each_hook_by_id_or_refuses_a_file_it_cannot_split() {
type Read<'a> = Result<Vec<(&'a str, &'a str)>, ()>;
let cases: [(&str, &str, Read); 5] = [
(
"two hooks",
TWO_HOOKS,
Ok(vec![
(
"log",
r#"{"on":"after_tool_use","timeout":"1s","command":["logger"],"env":["TOKEN"]}"#,
),
(
"notify",
r#"{"on":"run_completed","command":["notify-send","done"],"timeout":"2s"}"#,
),
]),
),
("no hooks", "version = 1\n", Ok(vec![])),
("not TOML", "version = \n", Err(())),
("hook is not tables", "version = 1\nhook = 1\n", Err(())),
(
"a hook without an id",
"version = 1\n[[hook]]\non = \"run_completed\"\n",
Err(()),
),
];
for (name, file, expected) in cases {
let read = hook_entries(file)
.map(|entries| {
entries
.into_iter()
.map(|entry| (entry.id, serde_json::to_string(&entry.value).unwrap()))
.collect::<Vec<_>>()
})
.map_err(|error| match error {
HookEditError::FileInvalid(_) => (),
error => panic!("{name}: refused as {error:?}"),
});
let expected = expected.map(|hooks| {
hooks
.into_iter()
.map(|(id, value)| (id.to_owned(), value.to_owned()))
.collect::<Vec<_>>()
});
assert_eq!(read, expected, "{name}");
}
}