You can create a custom handler that can check the message sent through logging. BufferingHandler is perfect for this job.
You may also want to attach a handler in your test to any logger that you use in your code, for example logging.getLogger('foo').addHandler(...) . Ultimately, you can bind a handler in the setUp and tearDown your test case.
import logging import logging.handlers class AssertingHandler(logging.handlers.BufferingHandler): def __init__(self,capacity): logging.handlers.BufferingHandler.__init__(self,capacity) def assert_logged(self,test_case,msg): for record in self.buffer: s = self.format(record) if s == msg: return test_case.assertTrue(False, "Failed to find log message: " + msg) def cook_eggs(): logging.warn("eggs are ready!") import unittest class TestLogging(unittest.TestCase): def test(self): asserting_handler = AssertingHandler(10) logging.getLogger().addHandler(asserting_handler) cook_eggs() asserting_handler.assert_logged(self,"eggs are ready!") logging.getLogger().removeHandler(asserting_handler) unittest.main()
Rod
source share