【问题标题】:Pytest pass arbitrary information from testPytest 从测试中传递任意信息
【发布时间】:2017-09-08 10:51:11
【问题描述】:

我正在为 pytest 测试结果的自定义 HTML 报告编写一个 python 插件。我想在测试中存储一些任意测试信息(即一些python对象......),然后在制作报告时我想在报告中重用这些信息。到目前为止,我只提出了一些 hackish 解决方案。

我将request 对象传递给我的测试,并用我的数据填充其中的request.node._report_sections 部分。 然后将该对象传递给TestReport.sections 属性,该属性可通过钩子pytest_runtest_logreport 获得,最后我可以从中生成HTML,然后从sections 属性中删除我的所有对象。

在伪python代码中:

def test_answer(request):
    a = MyObject("Wooo")
    request.node._report_sections.append(("call","myobj",a))    
    assert False

def pytest_runtest_logreport(report):
    if report.when=="call":
        #generate html from report.sections content
        #clean report.sections list from MyObject objects
        #(Which by the way contains 2-tuples, i.e. ("myobj",a)) 

有没有更好的 pytest 方法来做到这一点?

【问题讨论】:

  • 后来有没有更好的解决方案?

标签: python html report pytest


【解决方案1】:

这种方式看起来不错。 我可以建议的改进:

考虑使用夹具来创建 MyObject 对象。然后您可以将request.node._report_sections.append(("call","myobj",a)) 放在夹具内,并使其在测试中不可见。像这样:

@pytest.fixture
def a(request):
    a_ = MyObject("Wooo")
    request.node._report_sections.append(("call","myobj",a_))
    return a_

def test_answer(a):
    ...

如果您在所有的测试中都有这个对象,另一个想法是实现其中一个钩子pytest_pycollect_makeitempytest_pyfunc_call,并在那里“种植”该对象首先。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    相关资源
    最近更新 更多