#![allow(
clippy::missing_docs_in_private_items,
reason = "test helpers and fixtures do not need doc comments"
)]
use super::*;
use crate::routines::{new_store, slugify};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
struct TempHome(std::path::PathBuf);
impl TempHome {
fn set() -> Self {
let dir = std::env::temp_dir().join(format!("moadim-svctest-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).expect("create temp home");
unsafe {
std::env::set_var("MOADIM_HOME_OVERRIDE", &dir);
}
Self(dir)
}
}
impl Drop for TempHome {
fn drop(&mut self) {
unsafe {
std::env::remove_var("MOADIM_HOME_OVERRIDE");
}
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn make_routine(id: &str, title: &str, created_at: u64, updated_at: u64) -> Routine {
Routine {
model: None,
id: id.to_string(),
schedule: "@daily".to_string(),
title: title.to_string(),
agent: "claude".to_string(),
prompt: "do the thing".to_string(),
goal: None,
repositories: vec![],
machines: vec![crate::machine::current_machine()],
enabled: true,
source: "managed".to_string(),
created_at,
updated_at,
last_manual_trigger_at: None,
last_scheduled_trigger_at: None,
snoozed_until: None,
skip_runs: None,
power_saving: false,
tags: vec![],
ttl_secs: None,
max_runtime_secs: None,
env: std::collections::HashMap::new(),
}
}
fn store_with(routines: Vec<Routine>) -> RoutineStore {
let mut map = HashMap::new();
for routine in routines {
map.insert(routine.id.clone(), routine);
}
Arc::new(Mutex::new(map))
}
fn valid_create_request() -> CreateRoutineRequest {
CreateRoutineRequest {
model: None,
schedule: "@daily".into(),
title: "Valid Title".into(),
agent: "claude".into(),
prompt: "do the thing".into(),
goal: None,
repositories: vec![],
machines: vec![crate::machine::current_machine()],
enabled: true,
ttl_secs: None,
max_runtime_secs: None,
tags: vec![],
env: std::collections::HashMap::new(),
}
}
fn empty_update_request() -> UpdateRoutineRequest {
UpdateRoutineRequest {
model: None,
schedule: None,
title: None,
agent: None,
prompt: None,
goal: None,
repositories: None,
machines: None,
enabled: None,
ttl_secs: None,
max_runtime_secs: None,
tags: None,
env: None,
}
}
static PATH_GUARD: Mutex<()> = Mutex::new(());
fn with_empty_path(body: impl FnOnce()) {
let guard = PATH_GUARD
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let saved = std::env::var_os("PATH");
std::env::set_var("PATH", "");
body();
match saved {
Some(value) => std::env::set_var("PATH", value),
None => std::env::remove_var("PATH"),
}
drop(guard);
}
#[test]
fn svc_create_rejects_duplicate_slug() {
let _home = TempHome::set();
let title = "Svc Create Dup ZZZ";
let store = new_store();
with_empty_path(|| {
let first = svc_create(
&store,
CreateRoutineRequest {
model: None,
schedule: "@daily".into(),
title: title.into(),
agent: "claude".into(),
prompt: "p".into(),
goal: None,
repositories: vec![],
machines: vec![crate::machine::current_machine()],
enabled: true,
ttl_secs: None,
max_runtime_secs: None,
tags: vec![],
env: std::collections::HashMap::new(),
},
)
.unwrap();
let conflict = svc_create(
&store,
CreateRoutineRequest {
model: None,
schedule: "@daily".into(),
title: " svc create DUP zzz ".into(),
agent: "claude".into(),
prompt: "p".into(),
goal: None,
repositories: vec![],
machines: vec![crate::machine::current_machine()],
enabled: true,
ttl_secs: None,
max_runtime_secs: None,
tags: vec![],
env: std::collections::HashMap::new(),
},
);
assert!(matches!(conflict, Err(AppError::Conflict(_))));
svc_delete(&store, &first.routine.id).unwrap();
});
}
#[test]
fn svc_create_trims_title_before_persisting() {
let title = "Svc Create Trim ZZZ";
let store = new_store();
with_empty_path(|| {
let created = svc_create(
&store,
CreateRoutineRequest {
title: " Svc Create Trim ZZZ ".into(),
..valid_create_request()
},
)
.unwrap();
assert_eq!(created.routine.title, title);
svc_delete(&store, &created.routine.id).unwrap();
});
let _ = crate::routine_storage::remove_routine_dir(&slugify(title));
}
#[test]
fn svc_create_rejects_malformed_agent_config() {
let _home = TempHome::set();
let agent_name = "svc-create-malformed-agent-zzz";
std::fs::create_dir_all(crate::paths::agents_dir()).unwrap();
let cfg = crate::paths::agent_toml_path(agent_name);
std::fs::write(&cfg, "command = [\n").unwrap();
let store = new_store();
let result = svc_create(
&store,
CreateRoutineRequest {
model: None,
schedule: "@daily".into(),
title: "Svc Create Malformed ZZZ".into(),
agent: agent_name.into(),
prompt: "p".into(),
goal: None,
repositories: vec![],
machines: vec![crate::machine::current_machine()],
enabled: true,
ttl_secs: None,
max_runtime_secs: None,
tags: vec![],
env: std::collections::HashMap::new(),
},
);
match result {
Err(AppError::BadRequest(msg)) => assert!(msg.contains("malformed config")),
other => panic!("expected BadRequest, got {other:?}"),
}
}
#[test]
fn svc_create_rejects_unreadable_agent_config() {
let agent_name = "svc-create-unreadable-agent-zzz";
std::fs::create_dir_all(crate::paths::agents_dir()).unwrap();
let cfg = crate::paths::agent_toml_path(agent_name);
std::fs::create_dir_all(&cfg).unwrap();
let store = new_store();
let result = svc_create(
&store,
CreateRoutineRequest {
model: None,
schedule: "@daily".into(),
title: "Svc Create Unreadable ZZZ".into(),
agent: agent_name.into(),
prompt: "p".into(),
goal: None,
repositories: vec![],
machines: vec![],
tags: vec![],
enabled: true,
ttl_secs: None,
max_runtime_secs: None,
env: std::collections::HashMap::new(),
},
);
match result {
Err(AppError::BadRequest(msg)) => assert!(msg.contains("unreadable config")),
other => panic!("expected BadRequest, got {other:?}"),
}
std::fs::remove_dir_all(&cfg).unwrap();
}
#[test]
fn svc_update_rejects_malformed_agent_config() {
let _home = TempHome::set();
let agent_name = "svc-update-malformed-agent-zzz";
std::fs::create_dir_all(crate::paths::agents_dir()).unwrap();
let cfg = crate::paths::agent_toml_path(agent_name);
std::fs::write(&cfg, "command = [\n").unwrap();
let title = "Svc Update Malformed ZZZ";
let store = new_store();
let routine = make_routine("upd-mal-id", title, 1, 1);
crate::routine_storage::write_routine(&routine).unwrap();
store.lock().unwrap().insert("upd-mal-id".into(), routine);
let result = svc_update(
&store,
"upd-mal-id",
UpdateRoutineRequest {
model: None,
schedule: None,
title: None,
agent: Some(agent_name.into()),
prompt: None,
goal: None,
repositories: None,
machines: None,
enabled: None,
ttl_secs: None,
max_runtime_secs: None,
tags: None,
env: None,
},
);
match result {
Err(AppError::BadRequest(msg)) => assert!(msg.contains("malformed config")),
other => panic!("expected BadRequest, got {other:?}"),
}
}
#[test]
fn svc_update_rejects_renaming_into_existing_slug() {
let _home = TempHome::set();
let title_keep = "Svc Update Keep ZZZ";
let title_other = "Svc Update Other ZZZ";
let store = new_store();
let routine_keep = make_routine("keep-id", title_keep, 1, 1);
let routine_other = make_routine("other-id", title_other, 2, 2);
crate::routine_storage::write_routine(&routine_keep).unwrap();
crate::routine_storage::write_routine(&routine_other).unwrap();
store.lock().unwrap().insert("keep-id".into(), routine_keep);
store
.lock()
.unwrap()
.insert("other-id".into(), routine_other);
with_empty_path(|| {
let conflict = svc_update(
&store,
"other-id",
UpdateRoutineRequest {
model: None,
schedule: None,
title: Some(title_keep.into()),
agent: None,
prompt: None,
goal: None,
repositories: None,
machines: None,
enabled: None,
ttl_secs: None,
max_runtime_secs: None,
tags: None,
env: None,
},
);
assert!(matches!(conflict, Err(AppError::Conflict(_))));
});
}
#[test]
fn svc_update_migrates_workbenches_on_rename() {
let _home = TempHome::set();
let old_title = "Svc Update Rename Old ZZZ";
let new_title = "Svc Update Rename New ZZZ";
let old_slug = slugify(old_title);
let new_slug = slugify(new_title);
let store = store_with(vec![make_routine("rename-id", old_title, 1, 1)]);
let workbenches = crate::paths::workbenches_dir();
let old_dir = workbenches.join(format!("{old_slug}-1000"));
std::fs::create_dir_all(&old_dir).unwrap();
std::fs::write(old_dir.join("agent.log"), "prior run log").unwrap();
let unparseable = workbenches.join("not-a-workbench-name");
std::fs::create_dir_all(&unparseable).unwrap();
let blocked_old = workbenches.join(format!("{old_slug}-500"));
std::fs::create_dir_all(&blocked_old).unwrap();
let blocked_new = workbenches.join(format!("{new_slug}-500"));
std::fs::create_dir_all(&blocked_new).unwrap();
std::fs::write(blocked_new.join("marker"), "occupied").unwrap();
with_empty_path(|| {
svc_update(
&store,
"rename-id",
UpdateRoutineRequest {
title: Some(new_title.into()),
..empty_update_request()
},
)
.unwrap();
});
assert!(!old_dir.exists());
let migrated = workbenches.join(format!("{new_slug}-1000"));
assert_eq!(
std::fs::read_to_string(migrated.join("agent.log")).unwrap(),
"prior run log"
);
assert!(unparseable.exists());
assert!(blocked_old.exists());
assert_eq!(
std::fs::read_to_string(blocked_new.join("marker")).unwrap(),
"occupied"
);
let logs = svc_logs(&store, "rename-id").unwrap();
assert_eq!(logs.content, "prior run log");
}