#cfg(test) evaluation, miscompilation?

5 messages · Page 1 of 1 (latest)

torpid forge
#

So not sure if I am misunderstanding something here, or if there is some kind of weird miscompilation going on.

I have:

let debuginfo = match std::env::var("DEBUG").map(|debug| {
    debug
        .parse::<bool>()
        .expect("`DEBUG` should only be `true` or `false`")
}) {
    Ok(debuginfo) => debuginfo,
    _ => {
        if cfg!(test) {
            true
        } else {
            panic!("`DEBUG` should be set by `cargo`")
        }
    }
};

And when run with cargo test, it hits the panic!.

But when I put:

let debuginfo = match std::env::var("DEBUG").map(|debug| {
    debug
        .parse::<bool>()
        .expect("`DEBUG` should only be `true` or `false`")
}) {
    Ok(debuginfo) => debuginfo,
    _ => {
        if cfg!(test) {
            true
        } else {
            panic!("`DEBUG` should be set by `cargo`")
        }
    }
};

// This is now below
let foo = match std::env::var("foo") {
    ok(foo) => foo,
    _ => {
        if cfg!(test) {
            string::from("cfg!(test)")
        } else {
            panic!("`foo` should be set by `baz`")
        }
    }
};

panic!("{foo}");

with foo just below it, with no other changes to the DEBUG code, it now panics on foo.

Am I stupid? Why is it not panicking on DEBUG anymore when the foo panic exists?

The other issue is that for cargo test, theDEBUG block isn't evaluating to true, but panics instead.

I have also tried #[cfg(test)] (without the foo stuff) and it still had panicked on the "DEBUG should be set" message when running cargo test, so should have only compiled in a _ => true arm, and not a _ => panic!(..) arm.

torpid forge
#

Thanks! That does what I needed.

Do you happen to have an explanation of the explained behavior above, with cfg!(test)? And why it would panic in a different spot adding code below?

hollow mesa
#

but i think DEBUG is meant for rustc and not for your program