python - 将 py.test 的输出作为对象读取

标签 python unit-testing pytest python-unittest

早些时候,我在我的项目中使用了 python unittest,随之而来的是 unittest.TextTestRunnerunittest.defaultTestLoader.loadTestsFromTestCase。我出于以下原因使用它们,

  1. 使用调用单元测试运行方法的包装函数控制单元测试的执行。我不想要命令行方法。

  2. 从结果对象读取单元测试的输出并将结果上传到错误跟踪系统,这使我们能够生成一些关于代码稳定性的复杂报告。

最近决定切换到 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(报告)

阅读更多:Writing pytest plugins

所有这一切都可以很容易地完成,要么使用一个小插件作为一个简单的可安装库,要么作为一个伪插件conftest.py,它就在测试的目录之一附近.

关于python - 将 py.test 的输出作为对象读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46865816/

相关文章:

javascript - scope.$$childHead 是什么?

c# - RhinoMocks 中的 Moq 相当于 LastCall 的是什么?

Django UrlResolver,在运行时添加 url 以进行测试

python - 在上层目录中调用测试时查找 PyTest 装置的问题

python - 在 pytest 装置中导入应用程序时出错

python - 我如何传送(wormy.py)

python - scipy.optimize.leastsq 有界约束

python - 有没有办法在结构文件中进行滚动部署?

python - 当数据项中不存在元素时如何获取零值

python - conftest.py 可以_read_ pytest.ini 中的现有值吗?