How should I verify a log message when testing Python code under nose?

前端 未结 11 749
谎友^
谎友^ 2020-12-13 01:12

I\'m trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can\'t

11条回答
  •  忘掉有多难
    2020-12-13 02:09

    I used to mock loggers, but in this situation I found best to use logging handlers, so I wrote this one based on the document suggested by jkp(now dead, but cached on Internet Archive)

    class MockLoggingHandler(logging.Handler):
        """Mock logging handler to check for expected logs."""
    
        def __init__(self, *args, **kwargs):
            self.reset()
            logging.Handler.__init__(self, *args, **kwargs)
    
        def emit(self, record):
            self.messages[record.levelname.lower()].append(record.getMessage())
    
        def reset(self):
            self.messages = {
                'debug': [],
                'info': [],
                'warning': [],
                'error': [],
                'critical': [],
            }
    

提交回复
热议问题