Search code examples
testingrustpanic

Run "should_panic" tests with different inputs


Assume the following function which gets the nth bit from a u8:

    fn get_bit(&self, n: u8) -> bool {
        if n > 7 {
            panic!("Overflow detected while using `get_bit`: Tried to get the {n}th bit.");
        }
        let result = *self >> n & 1;
        if result == 1 {
            return true;
        } else {
            return false;
        }
    }

The basic (panic-case) test looks like this:

#[test]
#[should_panic]
fn get_bit_panic_ut() {
    0b0000_0000.get_bit(8);
}

As you can see this only tests for 8 as input. I want to make sure that this function will panic for any input between 8 and 255. So my naive attempt was:

#[test]
#[should_panic]
fn get_bit_panic_ut() {
    for i in 8..=255 {
        println!("{i}"); // For demonstration purposes
        0b0000_0000.get_bit(i);
    }
}

If I run the above with the --nocapture flag, I can see that the test execution stops after 8. So my question is how do I test for all the other cases here?

One option I came across, which might work is the rtest crate. I wonder if rust provides any out of the box mechanics for scenarios like this.


Solution

  • No - but you can easily simulate it:

    #[test]
    fn get_bit_panic_ut() {
        for i in 8..=255 {
            println!("{i}"); // For demonstration purposes
            assert!(std::panic::catch_unwind(|| 0b0000_0000.get_bit(i)).is_err());
        }
    }