Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Rust is running a test build [duplicate]

Tags:

rust

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.

like image 806
Will Squire Avatar asked Jan 01 '23 23:01

Will Squire


1 Answers

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.

like image 171
Peter Hall Avatar answered Jan 12 '23 09:01

Peter Hall