gpt4 book ai didi

testing - Rust宏可生成多个单独的测试

转载 作者:行者123 更新时间:2023-12-03 11:36:20 24 4
gpt4 key购买 nike

是否有可能生成独立测试的宏?我有两个文本文件,一个带有输入,另一个带有输出。文本文件中的每一行都代表一个新测试。
目前,这是我运行测试的方式:

    #[test]
fn it_works() {
let input = read_file("input.txt").expect("failed to read input");
let input = input.split("\n").collect::<Vec<_>>();

let output = read_file("output.txt").expect("failed to read output");
let output = output.split("\n").collect::<Vec<_>>();

input.iter().zip(output).for_each(|(a, b)| {
println!("a: {}, b: {}", a, b);
assert_eq!(b, get_result(a));
})

但是,正如您所看到的,如果一个测试失败,则所有测试都会失败,因为单个测试中存在一个循环。而且我需要将每个迭代作为一个单独的测试,而不必重复自己。
所以我想知道是否可以通过使用宏来实现?
理想情况下,宏将输出以下内容:
    #[test]
fn it_works_1() {
let input = read_file("input.txt").expect("failed to read input");
let input = input.split("\n").collect::<Vec<_>>();

let output = read_file("output.txt").expect("failed to read output");
let output = output.split("\n").collect::<Vec<_>>();

assert_eq!(output[0], get_result(input[0])); // first test
}

#[test]
fn it_works_2() {
let input = read_file("input.txt").expect("failed to read input");
let input = input.split("\n").collect::<Vec<_>>();

let output = read_file("output.txt").expect("failed to read output");
let output = output.split("\n").collect::<Vec<_>>();

assert_eq!(output[1], get_result(input[1])); // second test
}

// ... the N remaining tests: it_works_n()

最佳答案

您不能使用声明性宏来执行此操作,因为声明性宏无法生成用于命名测试函数的标识符。但是,您可以使用诸如 test-case 之类的 crate ,该 crate 可以使用不同的输入来运行相同的测试:

use test_case::test_case;

#[test_case(0)]
#[test_case(1)]
#[test_case(2)]
#[test]
fn it_works(index: usize) {
let input = read_file("input.txt").expect("failed to read input");
let input = input.split("\n").collect::<Vec<_>>();

let output = read_file("output.txt").expect("failed to read output");
let output = output.split("\n").collect::<Vec<_>>();

assert_eq!(output[index], get_result(input[index])); // first test
}
如果要测试的输入量很多,则可以使用声明性宏来生成上面的代码,该代码将添加所有 #[test_case]批注。

关于testing - Rust宏可生成多个单独的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65773658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com