7

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

Sharad
  • 9,282
  • 3
  • 19
  • 36

4 Answers4

4

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
2

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.

Sharad
  • 1,867
  • 14
  • 33
2

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 ]

Eddified
  • 3,085
  • 8
  • 36
  • 47
0

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

Sergei Voronezhskii
  • 2,184
  • 19
  • 32