如何根据一个常量在 Rust 中跳过一个测试?

huangapple go评论63阅读模式
英文:

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 &lt;= 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 &gt; 8);
  }

  #[test]
  fn will_panic_if_size_big() {
    assert!(SIZE &lt;= 8);
  }
}

答案1

得分: 1

抱歉,这仍然不可能。宏不能评估const,因为它们在常量评估之前执行,所以它等同于运行时条件。

英文:

Unfortunately, this is still not possible. Macros cannot evaluate consts, as they are executed before constant evaluation, so it is equivalent to runtime condition.

huangapple
  • 本文由 发表于 2023年6月30日 00:16:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定