python-3.x - assertLogs 可以检查日志消息的格式吗?

标签 python-3.x unit-testing

我可以使用 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,我需要另一种方法。

最佳答案

我自己也有这个确切的问题,我找到了 comment来自 nodakai很有帮助。
只是为了扩展这一点,我采用了以下技巧来测试我的日志消息格式:

from mylibrary import MY_LOGGING_FORMAT
from unittest import case
case._AssertLogsContext.LOGGING_FORMAT = MY_LOGGING_FORMAT
我在 MY_LOGGING_FORMAT 中定义的格式是我传入的logging.Formatter(...) .这个黑客部队assertLogs使用相同的格式。

关于python-3.x - assertLogs 可以检查日志消息的格式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44370513/

相关文章:

python - quit() 在 Python-3.x 和 IPython 中的工作方式不同

python - 使用复杂的 mysql 查询 python 没有返回正确的值

python - 如何在 Python 中一行输入 2 个整数?

.net - 有关测试或单元测试的一些基本问题

python - 抑制单元测试中的补充错误消息

java - 为多个 JUnit 测试类添加一个设置步骤

python - 元组列表的频率

python - BeautifulSoup :Scrape Table Data

php - 如何模拟 php native ldap 函数,如 lda_connect、ldap_get_entries、ldap_search 和 ldap_read

.NET NUnit 测试 - Assembly.GetEntryAssembly() 为空