Python Pytest从测试中传递任意信息

Python Pytest从测试中传递任意信息,python,html,report,pytest,Python,Html,Report,Pytest,我正在为pytest测试结果的定制HTML报告编写一个python插件。我想在测试中存储一些任意的测试信息(I.o.一些python对象…),然后在生成报告时,我想在报告中重用这些信息。到目前为止,我只提出了一点简单的解决方案 我将request对象传递给我的测试,并用我的数据填充request.node.\u report\u sections部分。 然后将此对象传递到TestReport.sections属性,该属性可通过hookpytest\u runtest\u logreport获得,

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

我将
request
对象传递给我的测试,并用我的数据填充
request.node.\u report\u sections
部分。 然后将此对象传递到
TestReport.sections
属性,该属性可通过hook
pytest\u runtest\u logreport
获得,最后我可以从中生成HTML,然后从
sections
属性中删除所有对象

在伪Python代码中:

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

有更好的pytest方法吗?

这种方法似乎还可以。 我可以提出以下改进建议:

考虑使用装置来创建MyObject对象。然后您可以将
request.node.\u report\u 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\u pycollect\u makeitem
pytest\u pyfunc\u call
,并首先“植入”该对象。

之后您有更好的解决方案吗?
@pytest.fixture
def a(request):
    a_ = MyObject("Wooo")
    request.node._report_sections.append(("call","myobj",a_))
    return a_

def test_answer(a):
    ...