忽略基于环境变量的测试

kri*_*hna 6 rust

有一些测试在本地运行,但不在 Github 工作流程上运行。我花了相当长的时间但无法调试和修复它们。现在,我想在 ci/cd 上忽略它们,但在本地运行它们。既然 Github 提供了一个方便的环境变量CI,它始终保持不变,我可以用它来忽略测试吗?

我不想将整个函数代码包装在if(env::var("CI").is_ok()). 还有更好的办法吗?

pok*_*One 6

您可以执行此操作的一种方法是向您的Cargo.toml文件添加一项功能,例如ci或类似的功能。然后让您的 GitHub 操作在启用该功能的情况下进行编译,并在相关测试上设置条件编译属性。

为此,您首先需要向Cargo.toml文件中添加一个新功能:

[features]
ci = []
Run Code Online (Sandbox Code Playgroud)

然后在测试的 Rust 代码中,您可以编写如下内容:

#[test]
#[cfg_attr(feature = "ci", ignore)]
fn test_some_code() {
    println!("This is a test");
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您在本地运行,cargo test您将看到测试运行,但如果您运行,cargo test --features ci您将看到测试显示ignored,如下所示:

在此输入图像描述

现在您只需更改 GitHub 操作即可使用此功能进行编译。如果你的操作看起来像这样:

jobs:
  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2
    - name: Build
      run: cargo build --verbose
    - name: Run tests
      run: cargo test --verbose
Run Code Online (Sandbox Code Playgroud)

然后添加--features ci到cargo build 和cargo test 命令的末尾。

有关条件编译的更多信息,请参阅 Rust 书籍:https ://doc.rust-lang.org/reference/conditional-compilation.html

有关 Cargo 功能的更多信息,请参阅 Cargo 书籍: https: //doc.rust-lang.org/cargo/reference/features.html