use crate::application::ports::Clock;
use std::sync::{Arc, Mutex};
use std::time::Instant;
#[derive(Debug, Clone)]
pub struct MockClock {
current_time: Arc<Mutex<Instant>>,
}
impl MockClock {
pub fn new(start: Instant) -> Self {
Self {
current_time: Arc::new(Mutex::new(start)),
}
}
pub fn advance(&self, duration: std::time::Duration) {
let mut time = self
.current_time
.lock()
.expect("MockClock mutex poisoned - a test thread panicked while holding the lock");
*time += duration;
}
pub fn set(&self, instant: Instant) {
let mut time = self
.current_time
.lock()
.expect("MockClock mutex poisoned - a test thread panicked while holding the lock");
*time = instant;
}
}
impl Clock for MockClock {
fn now(&self) -> Instant {
*self
.current_time
.lock()
.expect("MockClock mutex poisoned - a test thread panicked while holding the lock")
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn test_mock_clock() {
let start = Instant::now();
let clock = MockClock::new(start);
assert_eq!(clock.now(), start);
clock.advance(Duration::from_secs(10));
assert_eq!(clock.now(), start + Duration::from_secs(10));
let new_time = start + Duration::from_secs(100);
clock.set(new_time);
assert_eq!(clock.now(), new_time);
}
}