如何忽略在doctests上pytest期间生成的structlog debug/info/etc ?



我试图找出如何忽略structlog在我的doctests日志输出。似乎pytest能够忽略来自日志记录的日志,但不能忽略来自structlog的日志(至少不是本地的)。

示例如下:

import logging
import structlog

LOGGING_LOGGER = logging.getLogger(__name__)
STRUCTLOG_LOGGER = structlog.getLogger(__name__)

def func_with_logging():
"""
>>> func_with_logging()
1
"""
LOGGING_LOGGER.debug("ABC")
return 1

def func_with_structlog():
"""
>>> func_with_structlog()
1
"""
STRUCTLOG_LOGGER.debug("ABC")
return 1

上面的structlog只通过doctest。

========================================= test session starts =========================================
platform linux -- Python 3.9.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /home/bbeattie/test
collected 2 items
myfile.py .F                                                                                    [100%]
============================================== FAILURES ===============================================
________________________________ [doctest] myfile.func_with_structlog _________________________________
019
020     >>> func_with_structlog()
Expected:
1
Got:
2022-05-07 18:32.13 [debug    ] ABC
1
/home/bbeattie/test/myfile.py:20: DocTestFailure
======================================= short test summary info =======================================
FAILED myfile.py::myfile.func_with_structlog
===================================== 1 failed, 1 passed in 0.03s =====================================

我错过了一些明显的标志pytest?

您可以将structlog配置为不记录到stdout,或者将其配置为使用标准库日志记录,以便pytest的日志记录助手工作。

https://www.structlog.org/en/stable/testing.html中的自定义夹具应该是实现第一种方法的最简单方法,对于后者,"在structlog"内渲染"是最简单的方法。这种方法应该奏效。添加您自己的配置structlog的专用夹具(会话范围应该很好,不需要为每个测试重新配置)。

最新更新