I'm looking into how to perform assert introspection in Python, in the same way that py.test does. For example...
>>> a = 1
>>> b = 2
>>> assert a == b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError # <--- I want more information here, eg 'AssertionError: 1 != 2'
I see that the py.code library has some functionality around this and I've also seen this answer, noting that sys.excepthook allows you to plug in whatever behavior you want to exceptions, but it's not clear to me how to put it all together.
I don't think it is straightforward to reproduce pytest's assert introspection in a standalone context. The docs contain a few more details on how it works:
pytest rewrites test modules on import. It does this by using an import hook to write a new pyc files. Most of the time this works transparently. However, if you are messing with import yourself, the import hook may interfere. If this is the case, simply use --assert=reinterp or --assert=plain. Additionally, rewriting will fail silently if it cannot write new pycs, i.e. in a read-only filesystem or a zipfile.
It looks like it would require quite some hacks to make that work in arbitrary modules, so you're probably better off to use a solution suggested in the other answers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With