我想在运行时获取测试名称和测试结果.
我的脚本中有方法setup和tearDown方法.在setup,我需要获取测试名称,并且tearDown我需要获得测试结果并测试执行时间.
有没有办法可以做到这一点?
小智 14
你可以用钩子.
我在我的测试目录中有这些文件:
./rest/
??? conftest.py
??? __init__.py
??? test_rest_author.py
Run Code Online (Sandbox Code Playgroud)
在test_rest_author.py我有三个功能,startup,teardown和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
Run Code Online (Sandbox Code Playgroud)
钩子pytest_runtest_protocol为给定的测试项实现runtest_setup/call/teardown协议,包括捕获异常和调用报告钩子.任何测试结束时(如startup或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 =======
Run Code Online (Sandbox Code Playgroud)
另请参阅pytest hooks和conftest.py上的文档.
unittest.TestCase.id() 这将返回完整的详细信息,包括类名、方法名。由此我们可以提取测试方法名称。可以通过检查执行测试过程中是否出现异常来获取测试结果。如果测试失败,那么将会出现异常,如果 sys.exc_info() 返回 None 则测试通过,否则测试将失败。
| 归档时间: |
|
| 查看次数: |
7672 次 |
| 最近记录: |