使用功能标志"货物测试"运行其他测试

And*_*zie 8 testing rust rust-cargo

我有一些测试,我想在使用cargo test时忽略它们,并且仅在显式传递功能标志时运行.我知道这可以通过使用#[ignore]和来完成cargo test -- --ignored,但是我想因其他原因而有多组被忽略的测试.

我试过这个:

#[test]
#[cfg_attr(not(feature = "online_tests"), ignore)]
fn get_github_sample() {}
Run Code Online (Sandbox Code Playgroud)

当我cargo test按照需要运行时会忽略它,但我无法运行它.

我尝试了多种运行Cargo的方法,但测试仍然被忽略:

cargo test --features "online_tests"

cargo test --all-features
Run Code Online (Sandbox Code Playgroud)

然后我Cargo.toml根据此页面将功能定义添加到我的内容中,但它们仍会被忽略.

我在Cargo使用工作区.我尝试在两个Cargo.toml文件中添加功能定义没有区别.

She*_*ter 5

没有工作区

货代

[package]
name = "feature-tests"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]

[features]
network = []
filesystem = []

[dependencies]
Run Code Online (Sandbox Code Playgroud)

src / lib.rs

#[test]
#[cfg_attr(not(feature = "network"), ignore)]
fn network() {
    panic!("Touched the network");
}

#[test]
#[cfg_attr(not(feature = "filesystem"), ignore)]
fn filesystem() {
    panic!("Touched the filesystem");
}
Run Code Online (Sandbox Code Playgroud)

输出量

[package]
name = "feature-tests"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]

[features]
network = []
filesystem = []

[dependencies]
Run Code Online (Sandbox Code Playgroud)

(删除了一些输出以更好地显示效果)

带工作区

布局

#[test]
#[cfg_attr(not(feature = "network"), ignore)]
fn network() {
    panic!("Touched the network");
}

#[test]
#[cfg_attr(not(feature = "filesystem"), ignore)]
fn filesystem() {
    panic!("Touched the filesystem");
}
Run Code Online (Sandbox Code Playgroud)

feature-tests 包含上面第一部分中的文件。

货代

[package]
name = "workspace"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]

[features]
filesystem = ["feature-tests/filesystem"]
network = ["feature-tests/network"]

[workspace]

[dependencies]
feature-tests = { path = "feature-tests" }
Run Code Online (Sandbox Code Playgroud)

输出量

$ cargo test

running 2 tests
test filesystem ... ignored
test network ... ignored

$ cargo test --features network

running 2 tests
test filesystem ... ignored
test network ... FAILED

$ cargo test --features filesystem

running 2 tests
test network ... ignored
test filesystem ... FAILED
Run Code Online (Sandbox Code Playgroud)

(删除了一些输出以更好地显示效果)

使用带有虚拟清单的工作区

虚拟体现不要不支持指定的功能(货物问题#4942) 。您将需要在子项目中运行测试或指定适当的Cargo.toml的路径。

布局

.
??? Cargo.toml
??? feature-tests
?   ??? Cargo.toml
?   ??? src
?   ?   ??? lib.rs
??? src
?   ??? lib.rs
Run Code Online (Sandbox Code Playgroud)

feature-tests 包含上面第一部分中的文件。

货代

[workspace]
members = ["feature-tests"]
Run Code Online (Sandbox Code Playgroud)

输出量

[package]
name = "workspace"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]

[features]
filesystem = ["feature-tests/filesystem"]
network = ["feature-tests/network"]

[workspace]

[dependencies]
feature-tests = { path = "feature-tests" }
Run Code Online (Sandbox Code Playgroud)

(删除了一些输出以更好地显示效果)