#instant #time #mocking #testing #replace #thread-safe

mock_instant

简单模拟 std::time::Instant 的方法

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 并发

Download history 8748/week @ 2024-05-03 10893/week @ 2024-05-10 9323/week @ 2024-05-17 9796/week @ 2024-05-24 11709/week @ 2024-05-31 11272/week @ 2024-06-07 16696/week @ 2024-06-14 14458/week @ 2024-06-21 12279/week @ 2024-06-28 15651/week @ 2024-07-05 11409/week @ 2024-07-12 12812/week @ 2024-07-19 13178/week @ 2024-07-26 13137/week @ 2024-08-02 10398/week @ 2024-08-09 10145/week @ 2024-08-16

每月下载量 49,176
37 个 Crates 中使用 (直接使用 23 个)

0BSD 许可证

29KB
490

mock_instant

注意 自版本 0.5 以来,MockClock/Instant/SystemTime 已移动到特定模块

注意 模块 globalthread_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

无运行时依赖