use super::{ImportStamp, import_stamp_at};
use std::{
fs,
path::Path,
time::{Duration, SystemTime, UNIX_EPOCH},
};
const AUTH: &str = r#"{"OPENAI_API_KEY":"fixture-key-a"}"#;
const UPDATED_AUTH: &str = r#"{"OPENAI_API_KEY":"fixture-key-b"}"#;
const SINCE_EPOCH: Duration = Duration::from_secs(1_700_000_000);
fn set_modified(path: &Path, time: SystemTime) {
fs::OpenOptions::new()
.write(true)
.open(path)
.unwrap()
.set_modified(time)
.unwrap();
}
fn write_auth(path: &Path, contents: &str) {
fs::write(path, contents).unwrap();
set_modified(path, UNIX_EPOCH + SINCE_EPOCH);
}
fn stamp(path: &Path) -> ImportStamp {
import_stamp_at(path).unwrap().unwrap()
}
#[test]
fn import_stamp_ignores_unrelated_sibling_writes() {
let home = tempfile::tempdir().unwrap();
let auth = home.path().join("auth.json");
write_auth(&auth, AUTH);
let before = stamp(&auth);
fs::write(home.path().join(".codex-global-state.json"), "{}").unwrap();
assert!(stamp(&auth) == before);
}
#[test]
fn import_stamp_detects_an_edit_with_the_same_mtime() {
let home = tempfile::tempdir().unwrap();
let auth = home.path().join("auth.json");
write_auth(&auth, AUTH);
let before = stamp(&auth);
write_auth(&auth, UPDATED_AUTH);
assert!(stamp(&auth) != before);
}
#[test]
fn import_stamp_detects_a_new_mtime_with_the_same_contents() {
let home = tempfile::tempdir().unwrap();
let auth = home.path().join("auth.json");
write_auth(&auth, AUTH);
let before = stamp(&auth);
set_modified(&auth, UNIX_EPOCH + SINCE_EPOCH + Duration::from_secs(60));
assert!(stamp(&auth) != before);
}
#[test]
fn import_stamp_detects_an_atomic_replacement_with_the_same_contents_and_mtime() {
let home = tempfile::tempdir().unwrap();
let auth = home.path().join("auth.json");
let replacement = home.path().join("replacement.json");
write_auth(&auth, AUTH);
write_auth(&replacement, AUTH);
let before = stamp(&auth);
fs::rename(replacement, &auth).unwrap();
assert!(stamp(&auth) != before);
}
#[test]
fn import_stamp_detects_a_replacement_in_a_swapped_home_directory() {
let root = tempfile::tempdir().unwrap();
let home = root.path().join("codex");
let staged_home = root.path().join("staged");
fs::create_dir(&home).unwrap();
fs::create_dir(&staged_home).unwrap();
let auth = home.join("auth.json");
write_auth(&auth, AUTH);
write_auth(&staged_home.join("auth.json"), AUTH);
let before = stamp(&auth);
fs::rename(&home, root.path().join("previous")).unwrap();
fs::rename(staged_home, home).unwrap();
assert!(stamp(&auth) != before);
}