简体   繁体   English

我应该在Rust中放置测试实用程序功能?

[英]Where should I put test utility functions in Rust?

I have the following code defining a path where generated files can be placed: 我有以下代码定义生成文件的路径:

fn gen_test_dir() -> tempdir::TempDir {                                        
    tempdir::TempDir::new_in(Path::new("/tmp"), "filesyncer-tests").unwrap()   
} 

This function is defined in tests/lib.rs , used in the tests in that file and I would also like to use it in the unit tests located in src/lib.rs . 这个函数在tests/lib.rs定义,在该文件的测试中使用,我也想在src/lib.rs中的单元测试中使用它。

Is this possible to achieve without compiling the utility functions into the non-test binary and without duplicating code? 如果不将实用程序功能编译成非测试二进制文件而不重复代码,是否可以实现?

What I do is put my unit tests with any other utilities into a submodule protected with #[cfg(test)] : 我所做的是将我的单元测试与任何其他工具一起放入一个受#[cfg(test)]保护的子模块中:

#[cfg(test)]
mod tests {  // The contents could be a separate file if it helps organisation
    // Not a test, but available to tests.
    fn some_utility(s: String) -> u32 {
        ...
    }

    #[test]
    fn test_foo() {
        assert_eq!(...);
    }
    // more tests
}

You can import from your #[cfg(test)] modules from other #[cfg(test)] modules, so, for example, in main.rs or in some other module, you can do something like: 您可以从导入#[cfg(test)]从其它模块#[cfg(test)]模块,因此,例如,在main.rs或以其他模块,你可以这样做:

#[cfg(test)]
pub mod test_util {
    pub fn return_two() -> usize { 2 }
}

and then from anywhere else in your project: 然后从项目的其他任何地方:

#[cfg(test)]
mod test {
    use crate::test_util::return_two;

    #[test]
    fn test_return_two() {
        assert_eq!(return_two(), 2);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM