mock_instant
NOTE As of version 0.4, the thread-local clock has been removed. The clock will always be thread-safe.
To ensure unsurprising behavior, reset the clock before each test (if that behavior is applicable.)
This crate allows you to test Instant/Duration/SystemTime code, deterministically.
This uses a static mutex to have a thread-aware clock.
It provides a replacement std::time::Instant that uses a deterministic 'clock'
You can swap out the std::time::Instant with this one by doing something similar to:
use Instant;
use Instant;
or for a std::time::SystemTime
#[cfg(test)]
use mock_instant::{SystemTime, SystemTimeError};
#[cfg(not(test))]
use std::time::{SystemTime, SystemTimeError};
Example
# use MockClock;
# use Instant;
use Duration;
let now = now;
advance;
advance;
// its been '17' seconds
assert_eq!;
API:
// Overrides the current time to this `Duration`
set_time
// Advance the current time by this `Duration`
advance
// Get the current time
time // Overrides the current `SystemTime` to this duration
set_system_time
// Advance the current `SystemTime` by this duration
sdvance_system_time
// Get the current `SystemTime`
system_time
Usage:
NOTE The clock starts at Duration::ZERO
In your tests, you can use MockClock::set_time(Duration::ZERO) to reset the clock back to 0. Or, you can set it to some sentinel time value.
Then, before you check your time-based logic, you can advance the clock by some Duration (it'll freeze the time to that duration)
You can also get the current frozen time with MockClock::time
SystemTime is also mockable with a similar API.
License: 0BSD