我正在尝试使用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. …