3 个不稳定版本
| 0.2.1 | 2021年4月18日 | 
|---|---|
| 0.2.0 | 2021年4月18日 | 
| 0.1.0 | 2021年4月13日 | 
#654 在 测试
7,302 每月下载量
14KB
149 代码行
wraptest
在每次单元测试前后运行代码的简单方法。
您指定的包装函数会为每个测试调用。在包装函数中,您可以执行任何设置,调用提供的测试函数,然后进行任何清理。
示例
基本
假设您想在某些测试之前设置一个跟踪订阅者以显示日志和跟踪事件
#[wraptest::wrap_tests(wrapper = with_logs)]
mod tests {
    use tracing::info;
    use tracing_subscriber::fmt::format::FmtSpan;
    fn with_logs<T>(test_fn: T)
    where T: FnOnce() -> () {
        let subscriber = tracing_subscriber::fmt::fmt()
           .with_env_filter("debug")
           .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)
           .with_test_writer()
           .finish();
        let _guard = tracing::subscriber::set_default(subscriber);
        test_fn();
    }
    #[test]
    fn with_tracing() {
        info!("with tracing!");
    }
}
异步
如果您有异步测试(目前仅支持 tokio::test)您可以提供异步包装。
#[wraptest::wrap_tests(async_wrapper = with_logs)]
mod tests {
    async fn with_logs<T, F>(test_fn: T)
    where
        T: FnOnce() -> F,
        F: Future<Output = ()>,
    {
        let subscriber = /* ... */
        let _guard = tracing::subscriber::set_default(subscriber);
        test_fn();
    }
    #[tokio::test]
    async fn with_tracing() {
        info!("with tracing, but async!");
    }
}
自定义返回类型
如果您想从测试返回除 () 之外的内容,只需更改包装函数的签名。以下是如何使包装函数泛型化以支持任何返回类型的方法
#[wraptest::wrap_tests(wrapper = with_setup, async_wrapper = with_setup_async)]
mod tests {
    # use std::{future::Future, time::Duration};
    fn with_setup<T, R>(test_fn: T) -> R
    where
        T: FnOnce() -> R,
    {
        eprintln!("Setting up...");
        let result = test_fn();
        eprintln!("Cleaning up...");
        result
    }
    async fn with_setup_async<T, F, R>(test_fn: T) -> R
    where
        T: FnOnce() -> F,
        F: Future<Output = R>,
    {
        eprintln!("Setting up...");
        let result = test_fn().await;
        eprintln!("Cleaning up...");
        result
    }
}
替代方案
特别感谢 d-e-s-o 为 test-env-log 所做的工作。如果我没有看到它,使用宏来减少冗余的测试设置就不会想到。
依赖项
~1.5MB
~36K SLoC