I can use cfg!(debug_assertions)
to check if the Rust project is running in development mode, but I'd like to know how to check if a test is being run. Is there a similar flag for tests I can use in an if
statement?
The reason is to prevent database writes while running integration tests.
You can use cfg!(test)
:
if cfg!(test) {
// do test stuff
} else {
// do non-test stuff
}
However, this can lead to fragile code. For example, you might accidentally not execute some code in production, even though the tests all pass. It is often more robust to switch code at the item level, which would result in a compile error if you get it wrong:
#[cfg(test)]
impl Write for DB {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
// test stuff
}
fn flush(&mut self) -> Result<()> {
// test stuff
}
}
#[cfg(not(test))]
impl Write for DB {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
// actually write
}
fn flush(&mut self) -> Result<()> {
// actually flush
}
}
If you forget to implement the not(test)
version, you will get a compilation error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With