use std::fs;
use super::*;
#[test]
fn ledger_today_uses_civil_days_at_each_push_not_the_current_offset() {
let state = crate::test_os::tempdir();
let stamp = |text: &str| text.parse::<Timestamp>().unwrap();
let before = stamp("2026-03-08T04:59:59Z");
let midnight = stamp("2026-03-08T05:00:00Z");
let daylight = stamp("2026-03-08T07:00:00Z");
let now = stamp("2026-03-08T16:00:00Z");
let future = stamp("2026-03-08T16:01:00Z");
for (at, count) in [(before, 9), (midnight, 3), (daylight, 2), (future, 11)] {
record_at(state.path(), count, at).unwrap();
}
let history = history_in(Some(state.path()), now, |instant| {
let hours = if instant < daylight.time() { -5 } else { -4 };
instant
.to_offset(time::UtcOffset::from_hms(hours, 0, 0).unwrap())
.date()
})
.unwrap();
assert_eq!(history.recent.len(), 4);
assert_eq!(history.pushed_today, 5);
}
#[test]
fn concurrent_pushes_keep_all_counts() {
let state = crate::test_os::tempdir();
let at = Timestamp::new(time::OffsetDateTime::UNIX_EPOCH).unwrap();
let counts = 1..=8;
let ready = std::sync::Barrier::new(counts.clone().count());
std::thread::scope(|scope| {
for count in counts.clone() {
let path = state.path();
let ready = &ready;
scope.spawn(move || {
ready.wait();
record_at(path, count, at).unwrap();
});
}
});
let mut saved: Vec<_> = kept_at(state.path(), at)
.unwrap()
.into_iter()
.map(|entry| entry.count)
.collect();
saved.sort_unstable();
assert_eq!(saved, counts.collect::<Vec<_>>());
}
#[test]
fn keeps_each_push_with_its_count_and_drops_old_ones() {
let state = crate::test_os::tempdir();
let at =
Timestamp::new(time::OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(10)).unwrap();
let after = |duration| Timestamp::new(at.time() + duration).unwrap();
assert!(kept_at(state.path(), at).unwrap().is_empty());
record_at(state.path(), 3, at).unwrap();
record_at(state.path(), 2, after(time::Duration::seconds(1))).unwrap();
let wire: serde_json::Value =
serde_json::from_str(&fs::read_to_string(state.path().join(FILE)).unwrap()).unwrap();
assert_eq!(
wire,
serde_json::json!([{"at":10000,"count":3},{"at":11000,"count":2}])
);
let counts = |now| {
kept_at(state.path(), now)
.unwrap()
.into_iter()
.map(|push| push.count)
.collect::<Vec<_>>()
};
assert_eq!(counts(after(time::Duration::hours(48))), [3, 2]);
assert_eq!(
counts(after(
time::Duration::hours(48) + time::Duration::milliseconds(1)
)),
[2]
);
assert!(counts(after(time::Duration::hours(49))).is_empty());
}
#[test]
fn corrupt_history_is_reported_and_not_overwritten() {
let state = crate::test_os::tempdir();
let ledger = state.path().join(FILE);
let corrupt = b"{broken";
fs::write(&ledger, corrupt).unwrap();
let at = Timestamp::new(time::OffsetDateTime::UNIX_EPOCH).unwrap();
assert!(
matches!(history_at(Some(state.path()), at), Err(error) if error.contains("Invalid remote push history"))
);
assert!(record_at(state.path(), 3, at).is_err());
assert_eq!(fs::read(ledger).unwrap(), corrupt);
}