Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a Rust unit test that ensures that a panic has occurred?

I have a Rust function that panics under some condition and I wish to write a test case to validate whether the function is panicking or not. I couldn't find anything except the assert! and assert_eq! macros. Is there some mechanism for testing this?

I could spawn a new task and checking whether that task panics or not. Does it make sense?


Returning a Result<T, E> is not suitable in my case.

I wish to add support for the Add trait to a Matrix type I am implementing. The ideal syntax for such addition would look like:

let m = m1 + m2 + m3; 

where m1, m2, m3 are all matrices. Hence, the result type of add should be Matrix. Something like the following would be too cryptic:

let m = ((m1 + m2).unwrap() + m3).unwrap() 

At the same time, the add() function needs to validate that the two matrices being added have same dimension. Thus, add() needs to panic if the dimensions don't match. The available option is panic!().

like image 202
Shailesh Kumar Avatar asked Oct 20 '14 15:10

Shailesh Kumar


People also ask

How do you write test cases in Rust?

At its simplest, a test in Rust is a function that's annotated with the test attribute. Attributes are metadata about pieces of Rust code; one example is the derive attribute we used with structs in Chapter 5. To change a function into a test function, add #[test] on the line before fn .

How do you panic in Rust?

You can override the panic hook using std::panic::set_hook() . Inside the hook a panic can be accessed as a &dyn Any + Send , which contains either a &str or String for regular panic!() invocations. To panic with a value of another other type, panic_any can be used.

How do you ignore a test in Rust?

Ignoring Some Tests Unless Specifically Requested If you want to run all tests whether they're ignored or not, you can run cargo test -- --include-ignored .


1 Answers

You can find the answer in testing section of the Rust book. More specifically, you want #[should_panic] attribute:

#[test] #[should_panic] fn test_invalid_matrices_multiplication() {     let m1 = Matrix::new(3, 4);  // assume these are dimensions     let m2 = Matrix::new(5, 6);     m1 * m2 } 
like image 87
Vladimir Matveev Avatar answered Sep 26 '22 10:09

Vladimir Matveev