Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to import macros from an external crate during tests only, without any warnings?

Tags:

rust

I have something like:

#[macro_use] extern crate log;

pub fn do_nothing() { let _ = log::Level::Info; }

#[cfg(test)]
mod tests {
    #[test]
    fn test_a() { debug!("Message."); }
}

this compiles with a warning:

warning: unused `#[macro_use]` import

If I remove the macro import, and change the 1st line to:

extern crate log;

then I get the following error at compile time:

error: cannot find macro `debug!` in this scope

If I then try and import the macros only for the tests module, i.e.:

extern crate log;

pub fn do_nothing() { let _ = log::Level::Info; }

#[cfg(test)]

mod tests {
    #[macro_use] extern crate log;
    #[test]
    fn test_a() { debug!("Message."); }
}

then I get the compiler error:

error[E0468]: an `extern crate` loading macros must be at the crate root

Is there a solution which avoids all warnings without just suppressing them?

like image 529
Dave Challis Avatar asked Mar 19 '18 14:03

Dave Challis


Video Answer


1 Answers

You can use cfg_attr:

#[cfg_attr(test, macro_use)]
extern crate log;

See also:

  • Is it possible to conditionally derive with features?
  • Can I conditionally compile my Rust program for a Windows subsystem?
  • Run additional tests by using a feature flag to "cargo test"
like image 52
Shepmaster Avatar answered Sep 20 '22 01:09

Shepmaster