如何在unittest中验证python日志格式?

Jef*_*hiu 5 python logging unit-testing pytest

最近我在写一个python日志扩展,我想为我的扩展添加一些测试来验证我的扩展是否按预期工作。
但是,我不知道如何捕获完整的日志并与我在 unittest/pytest 中的异常结果进行比较。

简化示例

# app.py
import logging
def create_logger():
    formatter = logging.Formatter(fmt='%(name)s-%(levelname)s-%(message)s')
    hdlr = logging.StreamHandler()
    hdlr.setFormatter(formatter)
    logger = logging.getLogger(__name__)
    logger.setLevel('DEBUG')
    logger.addHandler(hdlr)
    return logger


app_logger = create_logger()
Run Code Online (Sandbox Code Playgroud)

这是我的测试

尝试 1:单元测试

from app import app_logger
import unittest


class TestApp(unittest.TestCase):

    def test_logger(self):
        with self.assertLogs('', 'DEBUG') as cm:
            app_logger.debug('hello')
        # or some other way to capture the log output.
        self.assertEqual('app-DEBUG-hello', cm.output)
Run Code Online (Sandbox Code Playgroud)

尝试 2:pytest caplog

from app import app_logger
import pytest


def test_logger(caplog):
    app_logger.debug('hello')
    assert caplog.text == 'app-DEBUG-hello'
Run Code Online (Sandbox Code Playgroud)

尝试 3:pytest capsys

从应用程序导入 app_logger 导入 pytest

def test_logger(capsys):
    app_logger.debug('hello')
    out, err = capsys.readouterr()
    assert err
    assert err == 'app-DEBUG-hello'
Run Code Online (Sandbox Code Playgroud)

考虑到会有很多不同格式的测试,我不想手动检查日志格式。我不知道如何获取我在控制台上看到的完整日志,并将其与我在测试用例中预期的日志进行比较。希望得到您的帮助,谢谢。

Lit*_*les 2

在阅读了该库的源代码后unittest,我找到了以下绕过方法。请注意,它的工作原理是更改导入模块的受保护成员,因此它可能会在未来版本中损坏。

from unittest.case import _AssertLogsContext
_AssertLogsContext.LOGGING_FORMAT = 'same format as your logger'
Run Code Online (Sandbox Code Playgroud)

在这些命令之后,打开的日志记录上下文self.assertLogs将使用上述格式。我真的不知道为什么这个值是硬编码的并且不可配置。

我没有找到读取记录器格式的选项,但如果使用,logging.config.dictConfig则可以使用同一字典中的值。