pytest-html自定义结果表,包含测试结果的输出

时间:2019-03-14 11:53:30

标签: python pytest python-unittest pytest-html

我正在尝试使用pytest进行API自动化。我想将status_code作为使用pytest-html生成的报告html中的列之一。我在测试函数的一个变量中收集了status_code。但是如何传递它以引起争执。

我的单元测试文件包含以下代码。

class Test1(unittest.TestCase):
    def test1_cust_list_page(self):
        cust_list_resp = requests.post(BASE_URL+customer_list_ep,json=cust_page_payload,headers=headers,params=cust_list_params)
        print(cust_list_resp.status_code)
        status_code = cust_list_resp.status_code
        assert cust_list_resp.status_code==200

我的conftest文件具有以下代码:

from datetime import datetime
from py.xml import html
import pytest

@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    cells.insert(2, html.th('Status_code'))
    cells.insert(1, html.th('Time', class_='sortable time', col='time'))
    cells.pop()

@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
    cells.insert(2, html.td(report.status_code))
    cells.insert(1, html.td(datetime.utcnow(), class_='col-time'))
    cells.pop()

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    report.status_code = str(item.function.)

如果我想从test1_cust_list_page单元测试中调用status_code的值,那么最后一行中的代码应该是什么。

我指的是下面的堆栈,但是第二个选项不清楚要调用哪个函数。 How to add additional variable to pytest html report

1 个答案:

答案 0 :(得分:-1)

在测试用例中使用一个额外的参数,例如

>>> import subprocess
>>> proc = subprocess.Popen(["some program", "some args"], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
>>> proc.stdin.write("hello world".encode())
>>> proc.stdin.close()
>>> print(proc.stdout.read().decode())

>>> 

现在在html结果表挂钩中

def test1_cust_list_page(self, request)
     #---other piece of code written here---
     #assign the variable the value within the test as
     request.node._status_code=cust_list_resp.status_code
     #in the above statement you created a variable _status_code

结论

  

conftest.py文件的report._status_code中包含的值与测试文件中的request.node._status_code相同