#mocking #async #tokio #compatible #compatibility #runtimes

async-time-mock-tokio

用于异步运行时的可模拟时间(tokio兼容性)

3个不稳定版本

0.1.1 2024年1月22日
0.1.0 2023年2月19日
0.0.1 2023年1月11日

#162 in 测试

Download history 37/week @ 2024-03-13 30/week @ 2024-03-20 24/week @ 2024-03-27 14/week @ 2024-04-03 7/week @ 2024-04-10 11/week @ 2024-04-17 19/week @ 2024-04-24 1/week @ 2024-05-01 18/week @ 2024-05-08 33/week @ 2024-05-15 15/week @ 2024-05-22 6/week @ 2024-05-29 38/week @ 2024-06-05 41/week @ 2024-06-12 26/week @ 2024-06-19 77/week @ 2024-06-26

每月下载量 184次

MIT 许可证

19KB
438

async-time-mock-tokio

基于 async-time-mock-core 的tokio兼容API的异步时间模拟,灵感来源于在异步Rust中模拟时间的描述。

注意:此库仍处于初级阶段,API可能还会更改(即:改进)。请在GitHub上留下您的反馈和建议。

Cargo功能

  • mock:启用模拟时钟。如果您只在测试中启用此功能,则此库将成为tokio时间函数的薄包装。

示例

use async_time_mock_tokio::MockableClock;
use std::{
	sync::atomic::{AtomicBool, Ordering},
	time::Duration,
};

static HAS_SLEPT: AtomicBool = AtomicBool::new(false);

async fn sleep(clock: MockableClock) {
	// Sleep is either mocked or a real tokio::sleep, depending on which variant of `MockableClock` you pass in.
	let _guard = clock.sleep(Duration::from_secs(3600)).await;
	// Dropping this guard signifies that all the effects of the timer have finished.
	// This allows test code to wait until the condition to assert for has happened.

	println!("Slept for an hour");
	HAS_SLEPT.store(true, Ordering::SeqCst);
}

#[tokio::main]
async fn main() {
	let (clock, controller) = MockableClock::mock(); // In production, you can use MockableClock::Real instead

	tokio::spawn(sleep(clock));

	controller.advance_time(Duration::from_secs(600)).await;
	assert!(!HAS_SLEPT.load(Ordering::SeqCst), "Timer won't trigger after just 10 minutes.");

	// advance_time will first trigger the sleep in the task above and then wait until the `_guard` was dropped.
	// This ensures that the task had enough time to actually set `HAS_SLEPT` to `true`.
	controller.advance_time(Duration::from_secs(3000)).await;
	assert!(HAS_SLEPT.load(Ordering::SeqCst), "Timer has triggered after 1 hour.")
}

依赖项

~2.3–4MB
~66K SLoC