4个版本 (2个破坏性更新)
0.3.0 | 2024年6月18日 |
---|---|
0.2.0 | 2024年1月2日 |
0.1.1 | 2023年4月3日 |
0.1.0 | 2023年3月31日 |
#132 in 测试
10,441 每月下载量
用于 12 crates
14KB
99 行
test-harness
这个过程宏可以将您的测试与接受具有测试签名函数的任何函数一起封装。您的测试函数可以接受任意数量的参数并返回任何类型,只要在框架中用正确的参数调用它。
示例
use test_harness::test;
fn my_test_harness(test: impl FnOnce(String)) {
let string = std::iter::repeat_with(fastrand::alphanumeric).take(10).collect();
test(string)
}
#[test(harness = my_test_harness)]
fn my_test(random_string: String) {
assert_eq!(string.len(), 10);
}
这扩展为以下内容,没有进一步的宏魔法
fn my_test_harness<F>(test: impl FnOnce(String)) {
let string = std::iter::repeat_with(fastrand::alphanumeric).take(10).collect();
test(string)
}
#[test]
fn my_test() -> impl std::process::Termination {
fn my_test(random_string: String) -> Result<(), &'static str> {
assert_eq!(string.len(), 10);
Ok(())
}
my_test_harness(my_test)
}
返回Result
use test_harness::test;
fn my_test_harness<F>(test: F) -> Result<(), &'static str>
where F: FnOnce(String) -> Result<(), &'static str> {
let string = std::iter::repeat_with(fastrand::alphanumeric).take(10).collect();
test(string)
}
#[test(harness = my_test_harness)]
fn my_test(random_string: String) -> Result<(), &'static str> {
assert_eq!(string.len(), 10);
Ok(())
}
这扩展为以下内容,没有进一步的宏魔法
fn my_test_harness<F>(test: F) -> Result<(), &'static str>
where F: FnOnce(String) -> Result<(), &'static str> {
let string = std::iter::repeat_with(fastrand::alphanumeric).take(10).collect();
test(string)
}
#[test]
fn my_test() -> impl std::process::Termination {
fn my_test(random_string: String) -> Result<(), &'static str> {
assert_eq!(string.len(), 10);
Ok(())
}
my_test_harness(my_test)
}
异步示例
您可以使用它设置异步运行时并启动或阻塞测试。
use test_harness::test;
mod my_mod {
pub fn set_up<F, Fut>(test: F) -> Result<(), Box<dyn std::error::Error>>
where
F: FnOnce(&'static str) -> Fut,
Fut: std::future::Future<Output = Result<(), Box<dyn std::error::Error>>> + Send + 'static,
{
futures_lite::future::block_on(test("hello"))
}
}
#[test(harness = my_mod::set_up)]
async fn my_test(s: &'static str) -> Result<(), Box<dyn std::error::Error>> {
assert_eq!(s, "hello");
Ok(())
}
省略框架名称
如果您将框架命名为 harness
,则可以省略框架名称,如下所示
use test_harness::test;
pub fn harness<F, Fut, Out>(test: F) -> Out
where
F: FnOnce(&'static str) -> Fut,
Fut: std::future::Future<Output = Out> + Send + 'static,
Out: std::process::Termination
{
futures_lite::future::block_on(test("hello"))
}
#[test(harness)]
async fn test_one(s: &'static str) -> Result<(), Box<dyn std::error::Error>> {
assert_eq!(s, "hello");
Ok(())
}
#[test(harness)]
async fn test_two(s: &'static str) {
assert_eq!(s, "hello");
}
退回到标准 #[test]
如果没有使用任何额外参数使用此宏,它的工作方式与内置的 #[test]
宏完全相同。
use test_harness::test;
#[test]
fn normal_test() {
assert!(true);
}
依赖项
~270–720KB
~17K SLoC