Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#[should_panic] doesn't accept constant as expected panic message

When running rust unit tests it is very useful to utilize the attribute macro #[should_panic(expect = )] to assert that the test is panicking with the correct error message (which means it's panicking at the line you want it to panic and not because of a different error.

However, in applications that use standardized error messages defined in an errors.rs file, it is not possible to pass the constant for the error message as the argument for expect.

This:

pub const ERR_001: &str = "ERR_001 message";

#[test]
#[should_panic(expected = ERR_001)]
fn test_function() {

        //test code here

}

yields the following error:

error: expected unsuffixed literal or identifier, found `ERR_001`
  --> staking/src/storage.rs:74:31
   |
74 |     #[should_panic(expected = ERR_001)]
   |                    

Is there a way to pass a constant or variable to the #[should_panic(expected = )] macro? Or is it necessary to always write message instead of ?

like image 585
João A. Veiga Avatar asked Apr 12 '26 03:04

João A. Veiga


1 Answers

Because the error message says "or identifier" but ERR_001 is indeed an ident, this was a Rust bug.

However, the error message for the same code is now:

error: expected unsuffixed literal, found `ERR_001`
  --> src/main.rs:50:27
   |
50 | #[should_panic(expected = ERR_001)]
   |                           ^^^^^^^
   |

So it seems that they have fixed the bug, in that they now officially don't support this use-case: It seems to not currently be possible because the should_panic macro expects to parse a literal instead of literal/ident or even more general expr.

While that looks like a reasonably easy feature to implement (wherever the should_panic macro is defined), the fact that they ended up deciding to not do it when realizing the mismatch between the error message and behavior (and the fact that there was a mismatch in the first place) lets me think that maybe it's not as easy as it looks.

like image 72
Ten Avatar answered Apr 16 '26 07:04

Ten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!