#instant #time #mocking #test

mock_instant

a simple way to mock an std::time::Instant

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 4790/week @ 2024-01-01 6861/week @ 2024-01-08 6389/week @ 2024-01-15 7572/week @ 2024-01-22 8362/week @ 2024-01-29 7420/week @ 2024-02-05 7670/week @ 2024-02-12 8230/week @ 2024-02-19 9865/week @ 2024-02-26 10905/week @ 2024-03-04 10817/week @ 2024-03-11 8644/week @ 2024-03-18 9938/week @ 2024-03-25 11006/week @ 2024-04-01 11687/week @ 2024-04-08 8703/week @ 2024-04-15

41,780 downloads per month
Used in 32 crates (21 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