【问题标题】:Can assertLogs check the format of a log message?assertLogs 可以检查日志消息的格式吗?
【发布时间】:2017-06-05 13:49:57
【问题描述】:

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

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)

让我感到困惑的是“外部上下文”日志消息包含行号,但“我的消息 - 上下文”日志消息显示默认格式。

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

【问题讨论】:

标签: python-3.x unit-testing


【解决方案1】:

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

为了进一步扩展,我使用了以下技巧来测试我的日志消息格式:

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

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

【讨论】:

    猜你喜欢
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多