英文:
How to skip a test in Rust based on a constant?
问题
const SIZE: usize = 8;
和一堆测试。 一些测试是用于当此常量大于8时,一些测试是用于当它小于8时,因为我测试一些特殊情况。 如何根据这个跳过测试?
例如,其中一个测试使用类型 u8
,如果 SIZE
大于8,则无法使用。
根据 https://stackoverflow.com/questions/43557542/how-to-conditionally-skip-tests-based-on-runtime-information,似乎无法在运行时执行此操作,但由于我所有的东西都在编译时,是否有一种看起来像
#[cfg(SIZE <= 8)]
只有在常量在正确范围内时才编译此测试的方法?
测试示例
#[cfg(test)]
mod test {
use super::SIZE;
#[test]
fn will_panic_if_size_small() {
assert!(SIZE > 8);
}
#[test]
fn will_panic_if_size_big() {
assert!(SIZE <= 8);
}
}
<details>
<summary>英文:</summary>
I have a constant
```rust
const SIZE: usize = 8;
and I have a bunch of tests. Some tests are for when this constant is larger than 8, some for when its lower than 8, as I test some special cases. How can I skip tests based on this?
For example, one such test uses the type u8
, and cannot be used if the SIZE
is larger than 8.
Based on https://stackoverflow.com/questions/43557542/how-to-conditionally-skip-tests-based-on-runtime-information, there is no way to do this at runtime, but since I have everything at compile time, is there a way looking like
#[cfg(SIZE <= 8)]
to compile this test only if the constant is in the right range?
Example of test
#[cfg(test)]
mod test {
use super::SIZE;
#[test]
fn will_panic_if_size_small() {
assert!(SIZE > 8);
}
#[test]
fn will_panic_if_size_big() {
assert!(SIZE <= 8);
}
}
答案1
得分: 1
抱歉,这仍然不可能。宏不能评估const
,因为它们在常量评估之前执行,所以它等同于运行时条件。
英文:
Unfortunately, this is still not possible. Macros cannot evaluate const
s, as they are executed before constant evaluation, so it is equivalent to runtime condition.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论