Is there a way to override default assert in pytest (python)?

痞子三分冷 提交于 2019-12-23 12:08:03

问题


I'd like to a log some information to a file/database every time assert is invoked. Is there a way to override assert or register some sort of callback function to do this, every time assert is invoked?

Regards Sharad


回答1:


I don't think that would be possible. assert is a statement (and not a function) in Python and has a predefined behavior. It's a language element and cannot just be modified. Changing the language cannot be the solution to a problem. Problem has to be solved using what is provided by the language

There is one thing you can do though. Assert will raise AssertionError exception on failure. This can be exploited to get the job done. Place the assert statement in Try-expect block and do your callbacks inside that block. It isn't as good a solution as you are looking for. You have to do this with every assert. Modifying a statement's behavior is something one won't do.




回答2:


Try overload the AssertionError instead of assert. The original assertion error is available in exceptions module in python2 and builtins module in python3.

import exceptions

class AssertionError:
    def __init__(self, *args, **kwargs):
        print("Log me!")
        raise exceptions.AssertionError



回答3:


It is possible, because pytest is actually re-writing assert expressions in some cases. I do not know how to do it or how easy it is, but here is the documentation explaining when assert re-writing occurs in pytest: https://docs.pytest.org/en/latest/assert.html

By default, if the Python version is greater than or equal to 2.6, py.test rewrites assert statements in test modules.

...

py.test rewrites test modules on import. It does this by using an import hook to write a new pyc files.

Theoretically, you could look at the pytest code to see how they do it, and perhaps do something similar.

For further information, Benjamin Peterson wrote up Behind the scenes of py.test’s new assertion rewriting [ at http://pybites.blogspot.com/2011/07/behind-scenes-of-pytests-new-assertion.html ]




回答4:


I suggest to use pyhamcrest. It has very beatiful matchers which can be simply reimplemented. Also you can write your own.



来源:https://stackoverflow.com/questions/36160713/is-there-a-way-to-override-default-assert-in-pytest-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!