| 1 |
use std::{sync::Mutex, time::Duration}; |
| 2 |
|
| 3 |
static TIME: Mutex<Duration> = Mutex::new(Duration::ZERO); |
| 4 |
static SYSTEM_TIME: Mutex<Duration> = Mutex::new(Duration::ZERO); |
| 5 |
|
| 6 |
fn with_time(d: impl Fn(&mut Duration)) { |
| 7 |
let mut t = TIME.lock().unwrap(); |
| 8 |
d(&mut t); |
| 9 |
} |
| 10 |
|
| 11 |
fn get_time() -> Duration { |
| 12 |
*TIME.lock().unwrap() |
| 13 |
} |
| 14 |
|
| 15 |
fn with_system_time(d: impl Fn(&mut Duration)) { |
| 16 |
let mut t = SYSTEM_TIME.lock().unwrap(); |
| 17 |
d(&mut t); |
| 18 |
} |
| 19 |
|
| 20 |
fn get_system_time() -> Duration { |
| 21 |
*SYSTEM_TIME.lock().unwrap() |
| 22 |
} |
| 23 |
|
| 24 |
crate::macros::define_mock_clock! { |
| 25 |
false; |
| 26 |
/// This uses a global mutex state for the deterministic clock |
| 27 |
} |
| 28 |
|
| 29 |
crate::macros::define_instant! { |
| 30 |
MockClock::time; |
| 31 |
false; |
| 32 |
/// This uses a global mutex for its time source |
| 33 |
} |
| 34 |
|
| 35 |
crate::macros::define_system_time! { |
| 36 |
MockClock::system_time; |
| 37 |
false; |
| 38 |
/// This uses a global mutex for its time source |
| 39 |
} |
| 40 |
|
| 41 |
crate::macros::define_instant_tests!(); |
| 42 |
|
| 43 |
#[cfg(test)] |
| 44 |
mod tests { |
| 45 |
use super::*; |
| 46 |
|
| 47 |
#[test] |
| 48 |
fn is_thread_local() { |
| 49 |
assert!(!MockClock::is_thread_local()); |
| 50 |
assert!(!Instant::now().is_thread_local()); |
| 51 |
assert!(!SystemTime::now().is_thread_local()); |
| 52 |
} |
| 53 |
|
| 54 |
#[test] |
| 55 |
fn thread_sharing() { |
| 56 |
MockClock::set_time(Duration::ZERO); |
| 57 |
|
| 58 |
let start = Instant::now(); |
| 59 |
|
| 60 |
std::thread::spawn(move || { |
| 61 |
let start = Instant::now(); |
| 62 |
MockClock::advance(Duration::from_secs(3)); |
| 63 |
assert_eq!(start.elapsed(), Duration::from_secs(3)); |
| 64 |
}) |
| 65 |
.join() |
| 66 |
.unwrap(); |
| 67 |
|
| 68 |
std::thread::spawn(move || { |
| 69 |
let next = Instant::now(); |
| 70 |
MockClock::advance(Duration::from_secs(30)); |
| 71 |
assert_eq!(next.elapsed(), Duration::from_secs(30)); |
| 72 |
}) |
| 73 |
.join() |
| 74 |
.unwrap(); |
| 75 |
|
| 76 |
MockClock::advance(Duration::from_secs(10)); |
| 77 |
// using seconds because a mutex can be slow on some operating systems |
| 78 |
// the creation/locking time may be in microseconds so we'll have something like 43.002 != 43 |
| 79 |
assert_eq!(start.elapsed().as_secs(), 43); |
| 80 |
} |
| 81 |
} |