mirror of
https://github.com/chatmail/core.git
synced 2026-04-17 13:36:30 +03:00
Add a new crate `deltachat_time` with a fake `struct SystemTimeTools` for mocking `SystemTime::now()` for test purposes. One still needs to use `std::time::SystemTime` as a struct representing a system time. I think such a minimalistic approach is ok -- even if somebody uses the original `SystemTime::now()` instead of the mock by mistake, that could break only tests but not the program itself. The worst thing that can happen is that tests using `SystemTime::shift()` and checking messages timestamps f.e. wouldn't catch the corresponding bugs, but now we don't have such tests at all which is much worse.
36 lines
936 B
Rust
36 lines
936 B
Rust
#![allow(missing_docs)]
|
|
|
|
use std::sync::RwLock;
|
|
use std::time::{Duration, SystemTime};
|
|
|
|
static SYSTEM_TIME_SHIFT: RwLock<Duration> = RwLock::new(Duration::new(0, 0));
|
|
|
|
/// Fake struct for mocking `SystemTime::now()` for test purposes. You still need to use
|
|
/// `SystemTime` as a struct representing a system time.
|
|
pub struct SystemTimeTools();
|
|
|
|
impl SystemTimeTools {
|
|
pub const UNIX_EPOCH: SystemTime = SystemTime::UNIX_EPOCH;
|
|
|
|
pub fn now() -> SystemTime {
|
|
return SystemTime::now() + *SYSTEM_TIME_SHIFT.read().unwrap();
|
|
}
|
|
|
|
/// Simulates a system clock forward adjustment by `duration`.
|
|
pub fn shift(duration: Duration) {
|
|
*SYSTEM_TIME_SHIFT.write().unwrap() += duration;
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn it_works() {
|
|
SystemTimeTools::shift(Duration::from_secs(60));
|
|
let t = SystemTimeTools::now();
|
|
assert!(t > SystemTime::now());
|
|
}
|
|
}
|