简体   繁体   中英

How to pass a `msg` to unittest.mock assert methods?

The TestCase docs specify that assert methods can take an optional msg keyword argument to specify a message to add context to the assertion:

All the assert methods accept a msg argument that, if specified, is used as the error message on failure (see also longMessage).

Is there a way to do this with the unittest.mock assert methods, in particular assert_any_call ?

Looking at the source of assert_any_call , the message is hard-coded:

raise AssertionError(
    '%s call not found' % expected_string
) from cause

Moreover, the AssertionError is raised directly in the code, rather than being the consequence of a failed assert statement. This pattern is followed by all the assert_* methods in the module. So there is no way to set a custom message unless you subclass and override the methods that interest you.

I know this question is old, bit I think it's still relevant:

You can always just catch and reraise yourself:

try:
    my_mock.assert_any_call()
except AssertionError as e:
    raise AssertionError("My custom message") from e

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM