Python + nose:对记录的文本做出断言?

Dav*_*ver 6 python testing logging nose

是否有一些简单的方法来捕获和记录有关已记录消息的断言nose

例如,我希望能够做到这样的事情:

cook_eggs()
assert_logged("eggs are ready!")
Run Code Online (Sandbox Code Playgroud)

Rod*_*Rod 12

您可以创建自定义处理程序,以检查通过日志记录发送的消息.该BufferingHandler是这个职位的完美匹配.

您可能还希望在测试中将处理程序附加到您在代码中使用的任何记录器,例如logging.getLogger('foo').addHandler(...).您最终可以在测试用例的setUptearDown方法中附加处理程序.

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()
Run Code Online (Sandbox Code Playgroud)