[pytest-dev] Custom reporting for asserts without comparison operators?
holger krekel
holger at merlinux.eu
Mon Mar 19 10:13:06 EDT 2018
On Mon, Mar 19, 2018 at 15:03 +0100, Floris Bruynooghe wrote:
> 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()))
i wonder if one could try to rewrite the ast for "assert myfunc(x)" to
"assert __pytest_funcrepr_helper(myfunc(x), 'myfunc(x)')" with something like:
class __pytest_funcrepr_helper:
def __init__(self, val, source):
self.val = val
self.source = source
def __bool__(self):
return bool(self.val)
def __repr__(self):
return "{!r} returned non-true {!r}".format(self.source, self.val)
but maybe i am not grasping all details involved. It's been a while since
i looked into ast-rewriting ...
holger
> 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
> _______________________________________________
> pytest-dev mailing list
> pytest-dev at python.org
> https://mail.python.org/mailman/listinfo/pytest-dev
More information about the pytest-dev
mailing list