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

Floris Bruynooghe flub at devork.be
Mon Mar 19 10:03:59 EDT 2018


On Sun, Mar 18 2018, Shawn Brown wrote:
> Unfortunately, this does not solve my usecase. I'm trying to handle cases
> where the following statement would pass:
>
>     assert myfunc(failing_input) == False
>
> But where this next statement would fail using my custom report:
>
>     assert myfunc(failing_input)
>
> Calling myfunc() needs to return True or False (or at least Truthy or
> Falsy)--this is locked-in behavior.

I'm not sure if this is compatible with Python's semantics really.  If I
understand correctly you're asking for a full-on macro implementation on
Python or something.  Which in theory you could do with an AST
NodeVisitor, but really Python isn't made for this -- sounds like you'd
enjoy lisp! ;-)

The best thing I can suggest is to make use of the::

   assert myfunc(failing_input), repr(myfunc(failing_input()))

functionality to also get a custom error message.  Here your myfunc()
whould have to return some object which both implements __bool__ as well
as __repr__ I guess.

Maybe there's a feature request in here for something like this::

   class Foo:
       def __bool__(self):
           return False

       def __repr__(self):
           return 'multiline\nstring'

   assert Foo()

To actually show the repr in the error message, which it currently
doesn't.  I'd like to know what other people think of such a feature
though, and haven't thought through all the implications yet.  But I'm
curious, would something like that solve your case?

Cheers,
Floris


More information about the pytest-dev mailing list