如何在pytest运行时获取测试名称和测试结果 [英] How to get test name and test result during run time in pytest
问题描述
我想在运行时获取测试名称和测试结果.
I want to get the test name and test result during runtime.
我的脚本中有 setup
和 tearDown
方法.在setup
中需要获取测试名称,在tearDown
中需要获取测试结果和测试执行时间.
I have setup
and tearDown
methods in my script. In setup
, I need to get the test name, and in tearDown
I need to get the test result and test execution time.
有没有办法做到这一点?
Is there a way I can do this?
推荐答案
你可以,使用钩子.
我的测试目录中有这些文件:
I have these files in my test directory:
./rest/
├── conftest.py
├── __init__.py
└── test_rest_author.py
在test_rest_author.py
中我有三个函数,startup
、teardown
和test_tc15
,但我只想要显示 test_tc15
的结果和名称.
In test_rest_author.py
I have three functions, startup
, teardown
and test_tc15
, but I only want to show the result and name for test_tc15
.
创建一个 conftest.py
文件(如果您还没有)并添加:
Create a conftest.py
file if you don't have one yet and add this:
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
或 teardown
或您的测试).
The hook pytest_runtest_protocol
implements the runtest_setup/call/teardown protocol for the given test item, including capturing exceptions and calling reporting hooks. It is called when any test finishes (like startup
or teardown
or your test).
如果你运行你的脚本,你可以看到测试的结果和名称:
If you run your script you can see the result and name of the test:
$ 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 和 的文档href="https://pytest.org/latest/plugins.html#conftest-py-local-per-directory-plugins)" rel="noreferrer">conftest.py.
See also the docs on pytest hooks and conftest.py.
这篇关于如何在pytest运行时获取测试名称和测试结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!