#mock #test #time #instant

mock_instant

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

6 releases

0.3.2 Feb 16, 2024
0.3.1 Jun 1, 2023
0.3.0 Apr 22, 2023
0.2.1 Oct 14, 2020
0.1.1 Jul 12, 2020

#44 in Testing

Download history 7052/week @ 2023-11-10 5910/week @ 2023-11-17 5732/week @ 2023-11-24 7593/week @ 2023-12-01 7323/week @ 2023-12-08 8689/week @ 2023-12-15 4562/week @ 2023-12-22 4568/week @ 2023-12-29 7004/week @ 2024-01-05 6052/week @ 2024-01-12 7504/week @ 2024-01-19 8228/week @ 2024-01-26 7782/week @ 2024-02-02 7530/week @ 2024-02-09 7998/week @ 2024-02-16 7685/week @ 2024-02-23

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

0BSD license

19KB
367 lines

mock_instant

mock_instant

This crate allows you to test Instant/Duration code, deterministically per thread.

If cross-thread determinism is required, enable the sync feature:

mock_instant = { version = "0.3", features = ["sync"] }

It provides a replacement std::time::Instant and std::time::SystemTime that uses a deterministic thread-local '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 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));

Mocking a SystemTime

# use mock_instant::{MockClock, SystemTime};
use std::time::Duration;

let now = SystemTime::now();
MockClock::advance_system_time(Duration::from_secs(15));
MockClock::advance_system_time(Duration::from_secs(2));

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

Caveats

If the sync feature is enabled then all tests using this crate will use a global singleton clock.

see https://github.com/museun/mock_instant/issues/6

License: 0BSD

Dependencies

~13KB