2017-04-12 116 views
0

我寫了pytest測試結果自定義HTML報告巨蟒插件任意信息。我想在測試中存儲一些任意的測試信息(i.o.一些python對象...),然後在製作報告時我想在報告中重複使用這些信息。到目前爲止,我只是遇到了一些駭人聽聞的解決方案。Pytest通過從測試

我將request對象傳遞給我的測試,並用我的數據填充request.node._report_sections部分。然後 這個對象傳遞給TestReport.sections屬性,它是通過掛鉤pytest_runtest_logreport可得到的,從中我終於可以生成HTML,然後我從sections屬性中刪除我的所有對象。

在pseudopythoncode:

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做到這一點?

回答

0

這種方式似乎確定。 改進我可以建議:

考慮使用夾具來創建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之一,並在「工廠」的對象有第一名。