代码改变世界

pytest自定义动态添加描述信息

2019-07-22 14:26  _天枢  阅读(2499)  评论(4编辑  收藏  举报

先上效果图:

 

修改pytest-html报告,分三部分.

pytest执行目录新建conftest.py文件

import pytest
from py._xmlgen import html
from datetime import datetime
"""
Summary部分在此设置
"""
@pytest.mark.optionalhook
def pytest_html_results_summary(prefix, summary, postfix):
    #Get configure content.
    prefix.extend([html.p("测试人: 测试组")])



"""
Environment部分在此设置
"""
def pytest_configure(config):
    
    config._metadata['测试地址'] = xxxxxxxx#


"""
Results部分在此设置.
"""
@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    cells.insert(2, html.th('Description'))
    cells.insert(3, html.th('Time', class_='sortable time', col='time'))
    # cells.insert(1,html.th("Test_nodeid"))
    cells.pop()

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

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    report.description = str(item.function.__doc__)
    report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape")   #设置编码显示中文

 

下面说一下怎么样动态更改描述部分:

pytest-html默认获取的是测试方法的__doc__属性,也就是,测试函数下的注释   如下的"""  """中的内容.

    def data(self, request):
        """
        fixture parameters.
        """

 

要动态传参__doc__内容也是可以的.可以通过__doc__动态修改描述.

普通方法:   方法名.__doc__='fixture parameters.'

实例方法:   self.方法名.__func__.__doc__='fixture parameters.'     实例方法必须加__func__否则是只读的.

class TestCaseExecution(object):
    """
    Use the python pytest framework.
    """
    def setup_class(self):
        pass
    

    def teardown_class(self):
        pass


    param_list = load_case_data()

    
    @pytest.fixture(scope='session', params=param_list)
    def data(self, request):
        """
        fixture parameters.
        """
        return request.param
    
    def testcase(self, data):
        self.testcase.__func__.__doc__ = data[0]['Desc']
        #Execution the YAML test case.
        exec_test_case(data)
        

 

使用此方法,动态传入描述.

self.testcase.__func__.__doc__ = data[0]['Desc']