python - 如何修改特定测试的失败报告

标签 python pytest

我有自定义 fixture ,它在测试期间收集有关对数据库查询的信息,如果测试失败使用该 fixture ,我想将 fixture 收集的信息添加到报告中。我该怎么做?

更新

它的样子:

from contextlib import contextmanager
import db
import pytest

def make_cursor_handler():
    ...
    return cursor_handler, list_with_log

@contextmanager
def wrap_cursor():
    old_handler = db.cursor_handler
    db.cursor_handler, list_with_log = make_cursor_handler()
    yield list_with_log
    db.cursor_handler = old_handler

@pytest.yield_fixture
def cursor_fixture():
    with wrap_cursor() as log:
        yield log #How would I print it inside error report without including it in assert message?

最佳答案

您可以使用 pytest-capturelog 捕获测试中写入的所有日志消息,包括在设置和拆卸期间。因此,无论您记录什么,都是报告的一部分,这可能非常有用(我们确实在我受雇的公司中使用它;尽管我们使用 nose,它可以在没有任何插件 AFAIK 的情况下处理它)。

pip install pytest-capturelog

然后你可以在测试期间的任何地方记录消息(设置、拆卸、固定装置、辅助函数),pytest-capturelog 应该处理它:

import logging

log = logging.getLogger(__name__)

def setup_function(function):
    log.info("setup log message")

def test_it():
    log.info("test log message")
    assert False

结果(见Captured log):

==================== test session starts =====================
platform linux2 -- Python 2.7.4 -- py-1.4.20 -- pytest-2.5.2
plugins: capturelog
collected 1 items 

file.py F

========================== FAILURES ==========================
__________________________ test_it ___________________________

    def test_it():
        log.info("test log message")
>       assert False
E       assert False

file.py:10: AssertionError
------------------------ Captured log ------------------------
file.py                      6 INFO     setup log message
file.py                      9 INFO     test log message
================== 1 failed in 0.01 seconds ==================

关于python - 如何修改特定测试的失败报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21798412/

相关文章:

python - 如何在 python 中加载带有缓冲区的文件?

python - 为什么 numpy.trapz() 返回零?

python pyautogui 无法打印@

python - 如何在pytest中测试类层次结构?

python - 使用 pytest 并行运行具有多个配置的单个测试

python - 检查提供给另一个可调用参数的参数

python - 如何在 pandas DataFrame 中重复单元格

python - 如何使用 BeautifulSoup 抓取 YouTube 评论

python - pytest 使用变量自省(introspection)断言消息自定义

python - 如何在收集阶段从 pytest 插件写入控制台?