我正在使用宏来生成测试。想象一下这样一个简单的定义:
macro_rules! my_test {
($name:ident) => {
#[test]
fn $name() {
assert_eq!(6, 3 + 3);
}
};
}
我想禁用一些我用这种方式生成的测试:
my_test!(good_test_a);
my_test!(good_test_b);
#[ignore]
my_test!(bad_test_a);
#[ignore]
my_test!(bad_test_b);
然而,根据this GitHub issue,
在宏的扩展期间,消除了应用于宏调用的属性。
事实上,所有的测试都在运行;没有人被忽略。 (见Rust Playground。)
这个限制是否有任何实际的解决方法?是否有其他一些调用宏的方法可以将#[ignore]
属性应用于其扩展?
这个限制是否有任何实际的解决方法?
是。通过允许宏本身通过meta
macro fragment接受属性,你可以解决这个问题:
#![cfg(test)]
macro_rules! my_test {
($(#[$m:meta])* // This accepts `#[foo] #[bar(..)] ..`
$name:ident) => {
$(#[$m])* // This expands the attributes.
#[test]
fn $name() {
assert_eq!(6, 3 + 3);
}
};
}
my_test!(good_test_a);
my_test!(good_test_b);
// You can pass in `#[ignore]` or any series of attributes you wish:
my_test!(#[ignore] bad_test_a);
my_test!(#[ignore] bad_test_b);
运行这个,我们得到:
running 4 tests
test bad_test_a ... ignored
test bad_test_b ... ignored
test good_test_a ... ok
test good_test_b ... ok
test result: ok. 2 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out