For example, we have a library called small_lib
. In its lib.rs
:
#[cfg(test)]
const RETURN_CONST:usize = 4;
#[cfg(not(test))]
const RETURN_CONST:usize = 2;
pub fn dumb_fn() -> usize {
RETURN_CONST
}
In main.rs
of the main repository:
use small_lib::dumb_fn;
fn main() {
println!("{}", dumb_fn());
}
#[cfg(test)]
mod test {
use small_lib::dumb_fn;
#[test]
fn it_works() {
assert_eq!(dumb_fn(), 4);
}
}
In both cargo run
and cargo test
commands, that dumb_fn()
returned 2. However, I want to see dumb_fn
returns 4 in cargo test
, while it returns 2 in cargo run
.
Assume I have full access to the library, how should I do that? And what if I don't have full access?
If you remove the test module from main.rs and put it in lib.rs it works.
#[cfg(test)]
const RETURN_CONST: usize = 4;
#[cfg(not(test))]
const RETURN_CONST: usize = 2;
pub fn dumb_fn() -> usize {
RETURN_CONST
}
#[cfg(test)]
mod test {
use crate::dumb_fn;
#[test]
fn it_works() {
assert_eq!(dumb_fn(), 4);
}
}
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.01s
Running unittests src/lib.rs (/home/COMPILE/js/cargo_target/debug/deps/whats-59c6c9a0d1349b40)
running 1 test
test test::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
the test
cfg is only set for the crate that you are running unit tests of, it is NOT set transitively for the dependencies.
for example, when you running tests of the bin crate of main.rs
, only the bin crate will set test
, the library crate of lib.rs
is just an extern crate (same as crates in packages you added from crates.io
), and is compiled without the test
flag.
4 Likes
If you have full control of the library you could define a feature and depend on the library with that feature enabled if your bin crate has a feature enabled.
But I don't know if you can toggle a feature on or off based on whether you're running a test or not (cfg(test)).
Nor do I know how to make main.rs and lib.rs in the same crate depend on each other with features. It might be easier to split your lib.rs into a separate crate and use a cargo workspace.