Use functions from test modules


#1

Hi all I have a sub module structure, looks like

pub mod cubic_kernel;
pub mod lucy_kernel;

#[cfg(test)]
pub mod test_kernel;
#[cfg(test)]
pub mod test_cubic_kernel;

pub trait Kernel {
    fn get_wij(&self, rij: f32, h: f32) -> f32;
    fn get_dwij(&self, xij: &Vec<f32>, dwij: &mut Vec<f32>, rij: f32, h: f32);
}

// reuse imports
pub use self::cubic_kernel::CubicKernel;
// -----------------------------------
// This doesn't work
pub use self::test_kernel::sin_approximation;

Why can’t I use a function defined in test file for files which are not cfg(test)?


#2

Because #[cfg(test)] means “compile this only for tests”. These modules are entirely ignored in ordinary case, as if they don’t exist at all.


#3

Ok, thanks. I have follow up question.

One of my test file has this.

use super::cubic_kernel::CubicKernel;
// Line 2
use super::test_kernel::{sin_approximation, sin_deriv_approximation};
use std::f32::consts::{FRAC_1_PI, PI};
use assert_approx_eq::assert_approx_eq;

#[test]
fn test_cubic_kernel_attributes() {
    let ck = CubicKernel::new(2).unwrap();
    assert_eq!(ck.sigma, 10. / 7. * FRAC_1_PI);
    let ck = CubicKernel::new(1).unwrap();
    assert_eq!(ck.sigma, 2. / 3.);
}

Here in line 2 I am using a function which is actually in test file. Like, I am using a function from a a test file in an another test file. Why is this allowed? Because any time i can remove the other test file, from the previous logic.


#4

But at the same time you’ll remove the file that uses it.

You can think of it as having two independent code bases. One of them has all the code as you have written it, and it is compiled when you do cargo test. Another one has all the #[cfg(test)] entries deleted - it is used for the ordinary cargo builds. Of course, in fact there is only one codebase - but logically this is as such (almost, since there’s olso #[cfg(not(test))] - but let’s not complicate it for now).