Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pytest

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

like image 429
Sharad Avatar asked Mar 22 '16 17:03

Sharad


Video Answer


2 Answers

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
like image 128
Thomas Zumsteg Avatar answered Nov 15 '22 04:11

Thomas Zumsteg


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.

like image 24
Sharad Avatar answered Nov 15 '22 05:11

Sharad