Passing variables or constants as arguments to the #[should_panic(expected = )]] attribute macro

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 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";

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

        //test code here


yields the error:

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

Because the attribute macro only accepts string literals as parameters in expect. Is there a way to work around this limitation? I've research a lot of projects and they all seem to simply rewrite the string instead of referencing the constant, which seems to be a very poor solution.

In case there is no envisioned solution, this should become a feature request, so that tests become easier to maintain in case the strings for error codes change.

Fixing this would require the code that implements #[test] to recognize an identifier and put it into the expanded code properly. FWIW, it's in this function. In particular that value_str call I believe.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.