[pytest-dev] Custom reporting for asserts without comparison operators?

Shawn Brown 03sjbrown at gmail.com
Fri Mar 16 15:15:12 EDT 2018


 I understand how to use pytest_assertrepr_compare() to return custom
assertion reports--but this interface requires a comparison operator. I'm
hoping to write a plugin that makes custom reports for statements like:

    assert myfunc(myobj)

Where myfunc() returns True or False. But without an operator (e.g. "=="),
I can't intercept the results to build my custom report.

While I *could* use a comparison operator, doing so is semantically wrong
for most of my use cases! And in the spirit of pytest and Pythonic code,
I'm hoping to handle the "assert myfunc(myobj)" case as written because
it's clean and caters to the test writer.

I investigated the idea of trying to manipulate the AST before the tests
are executed by using other pytest-supported hooks but this doesn't seem
possible. I also looked at the idea of subclassing pytests's
AssertionRewriter but there doesn't seem to be a mechanism for supporting
this within the context of non-invasive plugin behavior--it looks like I
would have to monkey patch pytest itself which isn't a route I want to take.

I've also looked at returning a subclassed False instance that contains my
report info and uses a custom repr for displaying it. But this was too much
of a hack and caused problems.

My current current "solution" is to have an assert_myfunc() function that
raises errors directly so the statements read "assert_myfunc(myobj)". But
I'd really like to use Python's native assert for this.

Are there other approaches I might take to rewrite an assertion report for
statements like "assert myfunc(myobj)" in a pytest-friendly/non-fragile way?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pytest-dev/attachments/20180316/5b774893/attachment-0001.html>


More information about the pytest-dev mailing list