Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Is this possible to achieve without compiling the utility functions into the non-test binary and without duplicating code?

like image 306
PureW Avatar asked Jun 23 '16 14:06

PureW


1 Answers

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)]
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);
    }
}

like image 95
MPlanchard Avatar answered Oct 16 '22 13:10

MPlanchard