Search code examples
testingrustassertion

Suppress default message of assert_eq! when custom message provided?


To my surprise, when I supply a custom message, it seems that assert_eq!'s default message is also printed out regardless.

Here I'm comparing some very long strs. So it is preferable not to clutter up the console but instead take a limited slice of each.

let left = tds.get_bulk_post_str();
let error_msg = format!("Bulk text is not what is expected: get_bulk_post_str() starts\n{}...\n\nExpected text starts\n{}...\n", 
    &left[0..20], &expected_bulk_text[0..20]);
// assert_eq! not used because assert_eq! apparently does not suppress its default message even when you supply a custom message!
// ... and in this case the default message is far too long.
// assert_eq!(left, expected_bulk_text, "{}", error_msg);

// instead, I think I'm forced to do something like this:
if left != expected_bulk_text {
    panic!("{}", error_msg)
}

... is there any way of suppressing the default message?

If not, this seems a strange design choice, unlike any other language I know. Is it deliberate?

PS I'm aware the first 20 chars of each string might be identical. Obviously if I really wanted to go to town on this I'd have to examine both strings to find out the first case of difference, and just print corresponding slices from the middle.


Solution

  • Use assert! instead:

    assert!(
        left == expected_bulk_text,
        "Bulk text is not what is expected: get_bulk_post_str() starts\n\
        {}...\n\n\
        Expected text starts\n\
        {}...\n", 
        &left[0..20],
        &expected_bulk_text[0..20],
    );