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

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

    Keying off @Reef's answer, I did tried the code below. It works well for me both for Python 2.7 (if you install mock) and for Python 3.4.

    """
    Demo using a mock to test logging output.
    """
    
    import logging
    try:
        import unittest
    except ImportError:
        import unittest2 as unittest
    
    try:
        # Python >= 3.3
        from unittest.mock import Mock, patch
    except ImportError:
        from mock import Mock, patch
    
    logging.basicConfig()
    LOG=logging.getLogger("(logger under test)")
    
    class TestLoggingOutput(unittest.TestCase):
        """ Demo using Mock to test logging INPUT. That is, it tests what
        parameters were used to invoke the logging method, while still
        allowing actual logger to execute normally.
    
        """
        def test_logger_log(self):
            """Check for Logger.log call."""
            original_logger = LOG
            patched_log = patch('__main__.LOG.log',
                                side_effect=original_logger.log).start()
    
            log_msg = 'My log msg.'
            level = logging.ERROR
            LOG.log(level, log_msg)
    
            # call_args is a tuple of positional and kwargs of the last call
            # to the mocked function.
            # Also consider using call_args_list
            # See: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_args
            expected = (level, log_msg)
            self.assertEqual(expected, patched_log.call_args[0])
    
    
    if __name__ == '__main__':
        unittest.main()
    

提交回复
热议问题