9 个不稳定版本 (4 个破坏性更新)
0.5.1 | 2024 年 6 月 2 日 |
---|---|
0.4.0 | 2024 年 4 月 7 日 |
0.3.2 | 2024 年 2 月 16 日 |
0.3.1 | 2023 年 6 月 1 日 |
0.1.1 | 2020 年 7 月 12 日 |
#31 in 并发
每月下载量 49,176
在 37 个 Crates 中使用 (直接使用 23 个)
29KB
490 行
mock_instant
注意 自版本 0.5 以来,MockClock/Instant/SystemTime 已移动到特定模块
注意 模块 global
和 thread_local
会改变线程间的行为。如果使用 global
,时钟会在线程间保持其状态,否则如果使用 thread_local
,则每个线程都会创建一个新的 源
为了确保行为不会令人惊讶,请在每个测试之前 重置 时钟(如果适用该行为。)
该 crate 允许您以确定性的方式测试 Instant
/Duration
/SystemTime
代码。
它提供了一个替换的 std::time::Instant
,该替换使用了确定性的 '时钟'
您可以通过以下方式将 std::time::Instant
替换为这个:
#[cfg(test)]
use mock_instant::global::Instant;
#[cfg(not(test))]
use std::time::Instant;
或对于 std::time::SystemTime
#[cfg(test)]
use mock_instant::global::{SystemTime, SystemTimeError};
#[cfg(not(test))]
use std::time::{SystemTime, SystemTimeError};
use mock_instant::global::{MockClock, 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`
MockClock::set_time(time: Duration)
// Advance the current time by this `Duration`
MockClock::advance(time: Duration)
// Get the current time
MockClock::time() -> Duration
// Overrides the current `SystemTime` to this duration
MockClock::set_system_time(time: Duration)
// Advance the current `SystemTime` by this duration
MockClock::sdvance_system_time(time: Duration)
// Get the current `SystemTime`
MockClock::system_time() -> Duration
// Determine if this MockClock was thread-local: (useful for assertions to ensure the right mode is being used)
MockClock::is_thread_local() -> bool
Instant::now().is_thread_local() -> bool
SystemTime::now().is_thread_local() -> bool
用法
注意 时钟从 Duration::ZERO
开始
在您的测试中,您可以使用 MockClock::set_time(Duration::ZERO)
来将时钟重置回 0。或者,您可以将其设置为某个哨兵时间值。
然后,在检查基于时间的逻辑之前,您可以前进时钟一些 Duration
(它将时间冻结到该持续时间)
您还可以使用 MockClock::time
获取当前冻结时间
SystemTime
也可以使用类似的 API 进行模拟。
线程安全性
通过模块提供了两种模式。API 相同,但 MockClock
的源在不同的线程中具有不同的行为。
-
mock_instant::全局
MockClock
将在每个线程中有一个新的状态Instant
将为每个线程拥有一个新的状态SystemTime
将为每个线程拥有一个新的状态
-
mock_instant::thread_local
MockClock
将在每个线程中有一个新的状态Instant
将为每个线程拥有一个新的状态SystemTime
将为每个线程拥有一个新的状态
许可证:0BSD