关于 rust-async-testing
面向 Rust 开发者的 Tokio 异步测试模式参考,涵盖测试运行时、时间控制、并发、超时及内存生命周期测试。
主要功能
- 01Tokio 异步测试设置
- 02暂停时间测试
- 03多线程并发测试
- 04超时与错误路径测试
- 05异步内存生命周期模式
适用场景
- 01测试基于 Tokio 的异步函数
- 02无需真实等待地检查时间行为
- 03测试并发任务与共享状态
- 04验证内存 episode 生命周期操作
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ d-o-hub/ rust-self-learning-memory --skill rust-async-testing安装后在 Claude Code 中输入/rust-async-testing确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
resources/concurrent-ops.mdmock-storage.mdtokio-patterns.md详细介绍
Rust 异步测试模式
使用 Tokio 测试 Rust 异步代码的最佳实践。
核心模式
基本异步测试
#[tokio::test]
async fn test_episode_creation() {
let memory = SelfLearningMemory::new(Default::default()).await?;
let id = memory.start_episode("Test", ctx, TaskType::CodeGen).await;
assert!(!id.is_empty());
}
基于时间的测试
#[tokio::test(start_paused = true)]
async fn test_timeout_behavior() {
// Time advances only when awaited
let start = tokio::time::Instant::now();
tokio::time::sleep(Duration::from_secs(5)).await;
assert!(start.elapsed().as_millis() < 100);
}
并发操作
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_concurrent_episodes() {
let memory = Arc::new(setup_memory().await);
let handles: Vec<_> = (0..10).map(|i| {
let mem = memory.clone();
tokio::spawn(async move {
mem.start_episode(format!("Task {}", i), ctx, type_).await
})
}).collect();
let results = futures::future::join_all(handles).await;
assert_eq!(results.len(), 10);
}
超时测试
#[tokio::test]
async fn test_operation_timeout() {
let result = tokio::time::timeout(
Duration::from_secs(2),
slow_operation()
).await;
assert!(result.is_err());
}
最佳实践
- 使用
#[tokio::test],而非block_on - 在时间测试中启用
start_paused = true - 在并发测试中使用
multi_thread - 模拟外部依赖
- 测试错误路径
常见陷阱
| 错误做法 | 正确做法 |
|---|---|
std::thread::sleep() | tokio::time::sleep().await |
memory.start_episode() | memory.start_episode().await |
| 使用单线程进行并发测试 | multi_thread 运行时 |
针对内存的模式
#[tokio::test]
async fn test_complete_lifecycle() {
let memory = setup_memory().await;
// Start → Log Steps → Complete → Verify
let id = memory.start_episode("test", ctx, type_).await;
memory.log_execution_step(id.clone(), step).await;
memory.complete_episode(id.clone(), outcome, None).await?;
let episode = memory.get_episode(&id).await?;
assert_eq!(episode.outcome, outcome);
}
评论
支持 Markdown