【发布时间】:2019-04-07 02:17:43
【问题描述】:
我正在尝试使用 pytest 编写一个测试,以检查特定函数是否在需要时将警告写入日志。例如:
在module.py中:
import logging
LOGGER = logging.getLogger(__name__)
def run_function():
if something_bad_happens:
LOGGER.warning('Something bad happened!')
在 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
我已经看到,您可以通过将 capsys 或 caplog 作为参数传递给测试,然后使用 capsus.readouterr() 或 caplog.records 访问输出。
但是,当我尝试这些方法时,我只看到“正在测试。”,而不是“发生了不好的事情!”。似乎无法从test_func() 访问在对run_function() 的调用中发生的日志记录输出?
如果我尝试更直接的方法,例如sys.stdout.getvalue(),也会发生同样的事情。这令人困惑,因为run_function() 正在写入终端,所以我认为可以从stdout...访问?
基本上,有谁知道我如何访问“发生了不好的事情!”来自test_func()?
【问题讨论】:
标签: python unit-testing testing logging pytest