使用pytest進(jìn)行單元測(cè)試時(shí),遇到了需要測(cè)試日志輸出的情況,查看了文檔
https://docs.pytest.org/en/latest/how-to/capture-stdout-stderr.html
https://docs.pytest.org/en/latest/how-to/logging.html
然后試了一下,捕捉logger.info可以用caplog,獲取print輸出可用capsys,Demo如下:
- a.py
import logging
logger = logging.getLogger(__name__)
LOG_INFO = "I'm a teapot"
PRINT_MSG = "No thing to do."
def function_with_logger(msg=None):
if msg is None:
msg = LOG_INFO
logger.info(msg)
def function_include_print():
print(PRINT_MSG)
- test_a.py
import logging
from a import LOG_INFO, PRINT_MSG, function_include_print, function_with_logger
def test_logger(caplog):
caplog.set_level(logging.INFO)
function_with_logger()
log_messages = [record.message for record in caplog.records]
assert LOG_INFO in log_messages
caplog.clear()
function_with_logger("foo")
assert "foo" in caplog.text
def test_print(capsys):
function_include_print()
captured = capsys.readouterr()
assert PRINT_MSG in captured.out
- 驗(yàn)證:文章來源:http://www.zghlxwxcb.cn/news/detail-846479.html
pytest test_a.py
文章來源地址http://www.zghlxwxcb.cn/news/detail-846479.html
到了這里,關(guān)于Python單元測(cè)試pytest捕獲日志輸出的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!