2017-10-21 105 views
1

早些时候,我在我的项目中使用python unittest,并且它来到了unittest.TextTestRunnerunittest.defaultTestLoader.loadTestsFromTestCase。我使用它们的原因如下:阅读py.test的输出为对象

  1. 使用调用unittests的run方法的包装函数来控制unittest的执行。我不想要命令行方法。

  2. 从结果对象中读取unittest的输出并将结果上传到一个bug跟踪系统,该系统允许我们生成一些关于代码稳定性的复杂报告。

最近有决定改用py.test的决定,我该怎么办上述使用py.test?我不想解析任何CLI/HTML来从py.test获取输出。我也不想在我的单元测试文件上写太多的代码来做到这一点。

有人可以帮助我吗?

回答

2

可以使用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)

了解更多:Writing pytest plugins

所有这一切都可以轻松完成要么作为一个简单的安装库做了一个小小的插件,或者作为一个伪插件conftest.py,它只是l在其中一个目录中进行测试。