【问题标题】:How can I programmatically set target_os in a unit test?如何在单元测试中以编程方式设置 target_os?
【发布时间】:2020-09-16 19:26:50
【问题描述】:

我尝试了以下方法:

fn get_system_extension(&self) -> String {
    if cfg!(target_os = "windows") {
        String::from(".lib")
    } else {
        String::new()
    }
}

mod test {
    #[allow(unused_imports)]
    use super::*;

    use std::env;

    #[test]
    fn get_system_extension_one() -> Result<(), CcrustyError> {
        env::set_var("CARGO_BUILD_TARGET", "linux");

        let result = get_system_extension();

        assert_eq!(String::new(), result);

        Ok(())
    }

    #[test]
    fn get_system_extension_two() -> Result<(), CcrustyError> {
        env::set_var("CARGO_CFG_UNIX", "");

        let result = get_system_extension();

        assert_eq!(String::new(), result);

        Ok(())
    }
}

根据the documentation,这些可以设置在一个文件中,但我不知道如何将它们动态链接到测试。

【问题讨论】:

  • 这没有任何意义。您想定位一个不是您正在为其编译的操作系统吗?
  • 其实,是也不是。我想在我的测试中测试这两个目标而不必更改操作系统,问题本身可能不清楚
  • 不,这很清楚。我不明白的是你想如何测试两个不同操作系统的特定于操作系统的代码,同时只在一个操作系统上构建和运行你的代码。
  • 另外,我希望你见过crates.io/crates/cc

标签: unit-testing rust tdd


【解决方案1】:

您是否正在寻找类似的东西:

#[test]
    fn currect_system_extension() -> Result<(), CcrustyError> {
        let system = env::var_os("CARGO_BUILD_TARGET");
        let result = get_system_extension();

        match system => {
             "linux" => assert_eq!(String::new(), result),
             "windows" => assert_eq!(".libs".to_string(), result),
             _ => (),
        }
        Ok(())
    }

即使这样,您也必须编译这两个版本才能进行此测试以覆盖代码。看看使用--all-targets

https://doc.rust-lang.org/cargo/commands/cargo-test.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多