Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does `#[test]` imply `#[cfg(test)]`?

Conventionally, unit tests in Rust are given a separate module, which is conditionally compiled with #[cfg(test)]:

#[cfg(test)]
mod tests {
    #[test]
    fn test1() { ... }

    #[test]
    fn test2() { ... }
}

However, I've been using a style where tests are more inline:

pub fn func1() {...}

#[cfg(test)]
#[test]
fn test_func1() {...}

pub fn func2() {...}

#[cfg(test)]
#[test]
fn test_func2() {...}

My question is, does #[test] imply #[cfg(test)]? That is, if I tag my test functions with #[test] but not #[cfg(test)], will they still be correctly absent in non-test builds?

like image 212
Lucretiel Avatar asked Feb 03 '23 18:02

Lucretiel


1 Answers

My question is, does #[test] imply #[cfg(test)]? That is, if I tag my test functions with #[test] but not #[cfg(test)], will they still be correctly absent in non-test builds?

Yes. If you are not using a separate module for tests then you don't need to use #[cfg(test)]. Functions marked with #[test] are already excluded from non-test builds. This can be verified very easily:

#[test]
fn test() {}

fn main() {
    test(); // error[E0425]: cannot find function `test` in this scope
}
like image 85
Peter Hall Avatar answered Feb 06 '23 15:02

Peter Hall