pytest - 如何在 pytest 运行时获取测试名称和测试结果

标签 pytest

我想在运行时获取测试名称和测试结果。

我有 setuptearDown我的脚本中的方法。在 setup ,我需要获取测试名称,并在 tearDown我需要得到测试结果和测试执行时间。

有没有办法我可以做到这一点?

最佳答案

你可以,用一个钩子(Hook)。

我的测试目录中有这些文件:

./rest/
├── conftest.py
├── __init__.py
└── test_rest_author.py

test_rest_author.py我有三个功能,startup , teardowntest_tc15 ,但我只想显示 test_tc15 的结果和名称.

创建 conftest.py如果您还没有文件,请添加以下内容:
import pytest
from _pytest.runner import runtestprotocol

def pytest_runtest_protocol(item, nextitem):
    reports = runtestprotocol(item, nextitem=nextitem)
    for report in reports:
        if report.when == 'call':
            print '\n%s --- %s' % (item.name, report.outcome)
    return True

钩子(Hook)pytest_runtest_protocol为给定的测试项实现 runtest_setup/call/teardown 协议(protocol),包括捕获异常和调用报告 Hook 。当任何测试完成时调用它(如 startupteardown 或您的测试)。

如果您运行脚本,您可以看到测试的结果和名称:
$ py.test ./rest/test_rest_author.py
====== test session starts ======
/test_rest_author.py::TestREST::test_tc15 PASSED
test_tc15 --- passed
======== 1 passed in 1.47 seconds =======

另请参阅 pytest hooks 上的文档和 conftest.py .

关于pytest - 如何在 pytest 运行时获取测试名称和测试结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14121657/

相关文章:

python - Pytest 仅运行具有特定标记属性的测试

django - Pytest 使用 django_db 和 rest 框架

python - 如何设置使用 pipelinev 运行 pytest 的 GitHub 操作?

python - Pytest 根据 mark.parameterize 值选择测试?

python - 如何避免在 PyTest 中从 session 范围固定装置中改变对象?

python - Pytest/假设未按预期匹配字符串

python - pytest:使用关键字选项(-k)时,不处理目录样式字符串

python - 如何在pytest中monkeypatch动态类属性

python - 使用 pytest 测试 aiohttp 和 mongo

python - 如何确定哪个单元测试涵盖了函数或方法