1 个不稳定版本

0.1.0 2022年6月13日

#729 in 测试

Apache-2.0

24KB
194

kat-rs

已知答案测试的测试框架。

这个 crate 旨在大幅减少 Rust 测试相关的样板代码,并使已知答案测试更容易编写和扩展。

此框架将测试分为测试实现和数据,数据存储在 .toml 文件中。

在内部,Kat 使用 SerdeToml-rs 来反序列化测试数据。

kat-rs 在行动

Toml 文件布局

文件 WORKSPACE_ROOT/tests/data/my_data.toml

# In this section global variables are defined.
[global]
my_global_var = "This is a global variable"
my_custom_string_holder = "String Holder"

# In these sections we define test cases.
# Each test owns its own data. 
# Though every test must have the same
# data signature
[[test]]
id = 0
data = "This is data for test 0"
input = 24.8
expected = 24.8

# Multiple tests can be defined with
# consecutive "test" tables
[[test]]
id = 1
data = "This is data for test 1"
input = 3.1415
expected = 3.1415

编写测试

use kat::{
    types,
    kat_cfg,
    global,
    test,
    run,
};

// Some custom struct
struct CustomStringHolder {
    s: String,
    v: usize
}

impl_deserialize_from_toml_string!(
    |s| -> CustomStringHolder {
        CustomStringHolder {
            s, 
            v: 12
        }
    }
); 

// Path configuration relative to WORKSPACE_ROOT
kat_cfg(tests/data/my_data.toml);

// Define global variables
global! {
  my_global_var: types::TomlString,
  my_custom_string_holder: CustomStringHolder
}

// Define Test variables
test! {
    id: types::TomlInt,
    data = types::TomlString,
    input = types::TomlFloat
    expected = types::TomlFloat
}

// Implement Test Runner
run! {
  #[should_panic(expected = "x, y, not equal")]  
  |global, test| -> {
    
    println!("{}", global.my_global_var);
    println!("{}", global.my_custom_string_holder.s);
    assert_eq!(test.input, test.expected);

    let (x, y) = (10, 15);
    assert_eq!(x, y, "x, y, not equal");

  }

}

依赖项

~0.5–1.2MB
~27K SLoC