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

2024-04-17

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

I have setup and tearDown我的脚本中的方法。在setup,我需要获取测试名称,然后在tearDown我需要获取测试结果和测试执行时间。

我有办法做到这一点吗?


你可以,使用钩子。

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

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

In test_rest_author.py我有三个功能,startup, teardown and test_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

钩子pytest_runtest_protocol为给定的测试项实现 runtest_setup/call/teardown 协议,包括捕获异常和调用报告挂钩。当任何测试完成时都会调用它(例如startup or teardown或你的测试)。

如果运行脚本,您可以看到测试的结果和名称:

$ 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 钩子 https://pytest.org/latest/plugins.html#hook-specification-and-validation and 测试.py https://pytest.org/latest/plugins.html#conftest-py-local-per-directory-plugins).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在pytest运行时获取测试名称和测试结果 的相关文章

随机推荐