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

前端 未结 11 704
谎友^
谎友^ 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

    If you define a helper method like this:

    import logging
    
    def capture_logging():
        records = []
    
        class CaptureHandler(logging.Handler):
            def emit(self, record):
                records.append(record)
    
            def __enter__(self):
                logging.getLogger().addHandler(self)
                return records
    
            def __exit__(self, exc_type, exc_val, exc_tb):
                logging.getLogger().removeHandler(self)
    
        return CaptureHandler()
    

    Then you can write test code like this:

        with capture_logging() as log:
            ... # trigger some logger warnings
        assert len(log) == ...
        assert log[0].getMessage() == ...
    

提交回复
热议问题