【问题标题】:How does one test optional features in Rust?如何测试 Rust 中的可选功能?
【发布时间】:2020-03-13 08:09:01
【问题描述】:

我有一个想要添加可选功能的包。我在 Cargo.toml 中添加了适当的部分:

[features]
foo = []

我为cfg!宏的基本功能写了一个实验测试:

#[test]
fn testing_with_foo() {
    assert!(cfg!(foo));
}

看起来我可以在测试期间通过--features--all-features 中的任何一个选项激活功能:

(master *=) $ cargo help test
cargo-test 
Execute all unit and integration tests and build examples of a local package

USAGE:
    cargo test [OPTIONS] [TESTNAME] [-- <args>...]

OPTIONS:
    -q, --quiet                      Display one character per test instead of one line
        ...
        --features <FEATURES>...     Space-separated list of features to activate
        --all-features               Activate all available features

不过,cargo test --features foo testing_with_foocargo test --all-features testing_with_foo 都不起作用。

这样做的正确方法是什么?

【问题讨论】:

  • 你试过cargo test -- --features foo testing_with_foo(注意--)。

标签: unit-testing testing rust conditional-compilation


【解决方案1】:

解决方案是@Jmb 提出的:assert!(cfg!(feature = "foo"));。货运手册上的内容

这可以通过#[cfg(feature = "foo")]在代码中进行测试。

允许人们确认条件编译有效,但不提供可以测试的布尔值。如果要在运行时基于特性进行分支,需要cfg!

【讨论】:

    【解决方案2】:

    您的测试不正确。引用the Cargo book:

    这可以通过#[cfg(feature = "foo")]在代码中进行测试。

    【讨论】:

    • 或者更接近 OP 想要的:assert!(cfg!(feature = "foo"));
    • 货运本上到底是哪里写的?我在任何地方都找不到它。 '这可以通过#[cfg(feature = "foo")]在代码中测试'
    • 链接有点过时了,你可以看看这个-doc.rust-lang.org/cargo/reference/features.html
    猜你喜欢
    • 2022-10-09
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多