I am stuck trying to write a test case that will check whether the code goes inside of an except
block.
My method foo()
in case of an exception doesn't throw/raise it, it just logs information.
I have tried to use assertRaises but later I realized that this is not working for me because I am not raising an exception.
In Python docs it is clearly said that:
Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised.
So, if I have following method:
def foo():
try:
# Something that will cause an exception
except AttributeError:
log.msg("Shit happens")
is it possible to write a test case that will test whether execution goes inside of an except block?
You can't do this the way you want to. Python raises and handles exceptions all over the place—e.g., every single for
loop exits by raising and handling a StopIteration
. So, an assert that there was an exception somewhere, even if it was handled, would pretty much always pass.
What you can do is mock the logger, like this:
_logs = []
def mocklog(str):
_logs.append(str)
mymodule.log = mocklog
mymodule.foo()
assertEqual(_logs, ['Shit happens'])
Of course in a real-life project, you probably want to use a mocking library instead of hacking it in by hand like this, but that should demonstrate the idea.