繁体   English   中英

pytest-html 带有测试结果输出的自定义结果表

[英]pytest-html Customizing Result table with output from test results

我正在尝试使用 pytest 进行 API 自动化。 我想将 status_code 作为使用 pytest-html 生成的报告 html 中的列之一包含在内。 我在测试函数的一个变量中收集了 status_code。 但是如何将它传递给 conftest.h 中的钩子。

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

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 的值,最后一行的代码应该是什么。

我参考了下面的堆栈,但第二个选项不清楚要调用哪个函数。 如何向pytest 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

现在在 html 结果表钩子中

@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
    #access your variable like below
    cells.insert(2, html.td(report._status_code))

结论

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM