use std::time::{Duration, Instant};
const TEST_CLOCK_LEEWAY: Duration = Duration::from_secs(315_569_520);
#[derive(Debug)]
pub struct TestClock {
now: Instant,
}
impl Default for TestClock {
fn default() -> Self {
TestClock::new()
}
}
impl TestClock {
pub fn new() -> Self {
Self {
now: Instant::now() + TEST_CLOCK_LEEWAY,
}
}
pub fn now(&self) -> Instant {
self.now
}
pub fn advance(&mut self, duration: Duration) {
self.now += duration;
}
pub fn rewind(&mut self, duration: Duration) {
self.now -= duration;
}
pub fn advance_time(&mut self, ms: u64) {
self.advance(Duration::from_millis(ms))
}
}
#[cfg(test)]
mod tests {
use std::{thread, time::Duration};
use super::TestClock;
#[test]
fn test_clock_operation() {
let mut clock = TestClock::new();
let initial = clock.now();
thread::sleep(Duration::from_millis(10));
assert_eq!(initial, clock.now());
clock.advance(Duration::from_secs(1));
clock.advance_time(1_000);
assert_eq!(clock.now() - initial, Duration::from_secs(2));
clock.rewind(Duration::from_secs(3));
assert_eq!(initial - clock.now(), Duration::from_secs(1));
}
}