vendredi 27 mars 2020

Rust: what is the proper way to define custom attributes for conditional compilation?

I'd like to be able to pass a flag to cargo test to enable logging in my tests, when I need to debug them.

I've come up with something like:

#[cfg(logging)]
use crate::logging;

#[test]
fn mytest() {
    #[cfg(logging)]
    logging::enable();
    // ..
    assert!(true);
}

Then I can enable the logs with

RUSTFLAGS="--cfg logging" cargo test

It works but it feels like I'm abusing the rustc flag system. It also has the side effect of recompiling all the crates with my logging flag, which (besides the fact that it takes ages) may be an issue if this flag is used by one of my dependency some day.

Is there a better way to define and use custom attributes? I could add a feature to my cargo manifest, but this is not really a feature since it's just for the tests.


Just a note: normally, cargo test captures the output of each test. Unfortunately that doesn't seem to work when using tracing and tracing_subscriber for logging.

Aucun commentaire:

Enregistrer un commentaire