小编lau*_*tta的帖子

用pytest测试日志输出

我正在尝试使用pytest编写测试,该测试将检查特定功能是否在需要时向日志写警告。例如:

在module.py中:

import logging
LOGGER = logging.getLogger(__name__)

def run_function():
    if something_bad_happens:
        LOGGER.warning('Something bad happened!')
Run Code Online (Sandbox Code Playgroud)

在test_module.py中:

import logging
from module import run_function

LOGGER = logging.getLogger(__name__)

def test_func():
    LOGGER.info('Testing now.')
    run_function()
    ~ somehow get the stdout/log of run_function() ~
    assert 'Something bad happened!' in output
Run Code Online (Sandbox Code Playgroud)

I have seen that you can supposedly get the log or the stdout/stderr with pytest by passing capsys or caplog as an argument to the test, and then using either capsus.readouterr() or caplog.records to access the output. …

python testing logging unit-testing pytest

6
推荐指数
3
解决办法
3052
查看次数

标签 统计

logging ×1

pytest ×1

python ×1

testing ×1

unit-testing ×1