阅读py.test的输出为对象
问题描述:
早些时候,我在我的项目中使用python unittest
,并且它来到了unittest.TextTestRunner
和unittest.defaultTestLoader.loadTestsFromTestCase
。我使用它们的原因如下:阅读py.test的输出为对象
使用调用unittests的run方法的包装函数来控制unittest的执行。我不想要命令行方法。
从结果对象中读取unittest的输出并将结果上传到一个bug跟踪系统,该系统允许我们生成一些关于代码稳定性的复杂报告。
最近有决定改用py.test
的决定,我该怎么办上述使用py.test?我不想解析任何CLI/HTML来从py.test获取输出。我也不想在我的单元测试文件上写太多的代码来做到这一点。
有人可以帮助我吗?
答
它看起来像pytest可以让你launch from Python code而不是使用命令行。看起来你只是将相同的参数传递给命令行中的函数调用。
Pytest将创建resultlog format files,但该功能已被弃用。该文档建议使用在Test Anything协议中生成文件的pytest-tap plugin。
答
可以使用pytest的钩子拦截测试结果报告:
conftest.py
:
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_logreport(report):
yield
# Define when you want to report:
# when=setup/call/teardown,
# fields: .failed/.passed/.skipped
if report.when == 'call' and report.failed:
# Add to the database or an issue tracker or wherever you want.
print(report.longreprtext)
print(report.sections)
print(report.capstdout)
print(report.capstderr)
同样,你可以拦截这些钩子一个在需要的阶段注入你的代码(在某些情况下,与尝试,唯独身边yield
):
pytest_runtest_protocol(item, nextitem)
pytest_runtest_setup(item)
pytest_runtest_call(item)
pytest_runtest_teardown(item, nextitem)
pytest_runtest_makereport(item, call)
pytest_runtest_logreport(report)
所有这一切都可以轻松完成要么作为一个简单的安装库做了一个小小的插件,或者作为一个伪插件conftest.py
,它只是l在其中一个目录中进行测试。