yegor256
yegor256

Reputation: 105083

How to configure logging for all Rust integration tests at once?

I have sources in src/ directory and tests together with them in the same files. Then, in src/lib.rs I have this:

#[cfg(test)]
use simple_logger::SimpleLogger;
#[cfg(test)]
use log::LevelFilter;
#[cfg(test)]
#[ctor::ctor]
fn init() {
    SimpleLogger::new()
        .with_level(LevelFilter::Trace)
        .init()
        .unwrap();
}

This turns logging on for all unit tests.

Then, I have integration tests in tests/ directory. If I put the same code into tests/lib.rs, it makes no effect. Where can I put it so that logging is configured by integration tests the same way as it's done for unit tests?

Upvotes: 0

Views: 253

Answers (1)

Caesar
Caesar

Reputation: 8514

The reason that this is not working is that integration tests are separate crates which depend on the lib crate - but without the #[cfg(test)] enabled. I'm not sure there even is a cfg flag you could use to know that the lib crate is being compiled for integration testing, but it would not be clean to do such a thing anyway. Instead, you could adopt the method described in Rust By Example: put the code you posted into a tests/common/mod.rs and add mod common; to all your integration tests. If that is still too much work per test, you could have your integration tests under a separate Cargo.toml of the same workspace, and have that Cargo.toml have a library that compiles the code you posted unconditionally (and never publish that to crates.io).

Upvotes: 1

Related Questions