Testing your logger in Python unit tests
When developing large scale applications, it is necessary to do proper logging to know where all the errors and exceptions are happening at.
In a Django project, I was trying to find ways to test whether my logger had been called to execute a logging action. In my case, you may want to test whether a log message is created when an exception is raised. This is going to be easy, and what you need to use is Python’s Mock class to mock the a logger instance.
Let’s say we have a simple function in python to get a value from a dictionary:
Now, in order to test if the function executes logging.warn
, we can just run the following testcase:
With this, we are able to test whether warn
is called, and if it was called with the right argument. You might ask, where did assert_called_with
come from? It actually comes from the mock object that we created from @mock.patch(logging)
. We have patched logging
with a Mock object that comes with the following assertion methods:
There are even more methods that you can test out with, and they are all in the docs here. You can now test your logger with any of these methods to ensure that your logic is right!