7 unstable releases

0.4.0 Apr 7, 2024
0.3.2 Feb 16, 2024
0.3.1 Jun 1, 2023
0.3.0 Apr 22, 2023
0.1.1 Jul 12, 2020

#37 in Concurrency

Download history 8107/week @ 2024-01-24 7406/week @ 2024-01-31 7046/week @ 2024-02-07 8081/week @ 2024-02-14 8663/week @ 2024-02-21 10356/week @ 2024-02-28 11545/week @ 2024-03-06 9615/week @ 2024-03-13 9014/week @ 2024-03-20 10098/week @ 2024-03-27 11613/week @ 2024-04-03 10976/week @ 2024-04-10 8928/week @ 2024-04-17 9235/week @ 2024-04-24 8229/week @ 2024-05-01 7814/week @ 2024-05-08

35,857 downloads per month
Used in 31 crates (20 directly)

0BSD license

20KB
347 lines

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:

#[cfg(test)]
use mock_instant::Instant;

#[cfg(not(test))]
use std::time::Instant;

or for a std::time::SystemTime

#[cfg(test)]
use mock_instant::{SystemTime, SystemTimeError};

#[cfg(not(test))]
use std::time::{SystemTime, SystemTimeError};

Example

# use mock_instant::MockClock;
# use mock_instant::Instant;
use std::time::Duration;

let now = Instant::now();
MockClock::advance(Duration::from_secs(15));
MockClock::advance(Duration::from_secs(2));

// its been '17' seconds
assert_eq!(now.elapsed(), Duration::from_secs(17));

API:

// Overrides the current time to this `Duration`
MockClick::set_time(time: Duration)

// Advance the current time by this `Duration`
MockClick::advance(time: Duration)

// Get the current time
MockClick::time() -> Duration

// Overrides the current `SystemTime` to this duration
MockClick::set_system_time(time: Duration)

// Advance the current `SystemTime` by this duration
MockClick::sdvance_system_time(time: Duration)

// Get the current `SystemTime`
MockClick::system_time() -> Duration

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

No runtime deps