Favorite recipe for dealing with loggers in test cases
Being able to on-the-fly setup your loggers is nice but can be painful for your test cases. Another use case is that you actually want to catch your loggers output from the code your testing. There lots of ways to solve this problem, but I find myself loving the below method
from code import Code
MockLog(list):
def __getattr__(self, name):
return self.append
Code.logger = MockLog()
def test_code():
code.run()
assert("Looking for this message to be logged by this point" in Code.logger)
How this works. In the Code class a logger will likely be set as an instance member. The above monkey patches that and when the instance tries to log the message with log.warning(msg) or log.error(msg) the message will just append to a list. I'm curious how folks without monkey patching at their disposal handle this?
from code import Code
MockLog(list):
def __getattr__(self, name):
return self.append
Code.logger = MockLog()
def test_code():
code.run()
assert("Looking for this message to be logged by this point" in Code.logger)
How this works. In the Code class a logger will likely be set as an instance member. The above monkey patches that and when the instance tries to log the message with log.warning(msg) or log.error(msg) the message will just append to a list. I'm curious how folks without monkey patching at their disposal handle this?