assertLogs可以检查日志消息的格式吗?

时间:2017-06-05 13:49:57

标签: python-3.x unit-testing

我可以使用Python的unittest assertLog来检查日志消息的格式吗?

def test_log_format(self):
    h.config_common_log(level=logging.DEBUG)
    h.get_log().debug('outside context')
    with self.assertLogs(level=logging.DEBUG) as a_log:
        h.get_log().debug('my_message - incontext')     
        self.assertRegex(a_log.output[0], ':\d+:my_message') # This fails
        # This shows the log data itself is correct, just the output message is wrong
        print('a_log.ouput={}\ta_log={!s}'.format(a_log.output, a_log))

# This was added to learn varying the logger would help. It did not.
def get_log():
    return logging.getLogger()

def config_common_log(level=logging.WARNING):
    get_log().setLevel(level)
    ch = logging.StreamHandler()
    ch.setFormatter(logging.Formatter('%(module)s:%(funcName)s:%(lineno)s:%(message)s'))  # Despite this format statement.
    get_log().addHandler(ch)

让我感到困惑的是外界背景'日志消息包括行号,但是“我的消息 - 在上下文中”#39;日志消息显示默认格式。

我目前的假设是assertLogs只检查一个StreamHandler并且(非常合理地)它使用默认的StreamHandler及其a_msg的默认格式化程序。要测试我的Formatter和StreamHandlder,我需要另一种方法。

1 个答案:

答案 0 :(得分:0)

我自己也有这个确切的问题,我发现来自 commentnodakai 非常有帮助。

为了扩展这一点,我采用了以下技巧来测试我的日志消息格式:

from mylibrary import MY_LOGGING_FORMAT
from unittest import case
case._AssertLogsContext.LOGGING_FORMAT = MY_LOGGING_FORMAT

我在 MY_LOGGING_FORMAT 中定义的格式是我传递给 logging.Formatter(...) 的内容。此黑客强制 assertLogs 使用相同的格式。