早些时候,我在我的项目中使用了 python unittest
,随之而来的是 unittest.TextTestRunner
和 unittest.defaultTestLoader.loadTestsFromTestCase
。我出于以下原因使用它们,
使用调用单元测试运行方法的包装函数控制单元测试的执行。我不想要命令行方法。
从结果对象读取单元测试的输出并将结果上传到错误跟踪系统,这使我们能够生成一些关于代码稳定性的复杂报告。
最近决定切换到 py.test
,我如何使用 py.test 执行上述操作?我不想解析任何 CLI/HTML 来获取 py.test 的输出。我也不想在我的单元测试文件上写太多代码来执行此操作。
有人可以帮我解决这个问题吗?
最佳答案
可以使用pytest的hook拦截测试结果上报:
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)
同样,您可以拦截其中一个 Hook 以在所需阶段注入(inject)您的代码(在某些情况下,使用 yield
周围的 try-except):
pytest_runtest_protocol(item, nextitem)
pytest_runtest_setup(item)
pytest_runtest_call(item)
pytest_runtest_teardown(item, nextitem)
pytest_runtest_makereport(项目,调用)
pytest_runtest_logreport(报告)
所有这一切都可以很容易地完成,要么使用一个小插件作为一个简单的可安装库,要么作为一个伪插件conftest.py
,它就在测试的目录之一附近.
关于python - 将 py.test 的输出作为对象读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46865816/