Pytest使用钩子方法生成自定义测试报告

使用Pytest测试框架生成测试报告最常用的便是使用pytest-htmlallure-pytest两款插件了。
pytest-html简单(支持单html测试报告),allure-pytest则漂亮而强大。
当然想要使用自定义模板生成测试报告也非常简单,简单实现步骤如下:

  1. 介入Pytest运行流程,运行后自动生成HTML测试报告:使用Hooks方法
  2. 拿到运行结果统计数据:钩子方法pytest_terminal_summary的terminalreporter对象的stats属性中
  3. 渲染HTML报告模板生成测试报告:使用Jinjia2

经研究,Hooks方法pytest_terminal_summary及运行完毕生成命令行总结中包含的terminalreporter对象的stats属性中包含我们需要的测试结果统计。

钩子运行流程可以参考:https://www.cnblogs.com/superhin/p/11733499.html

使用Pytest的对象自省(对象.__dict__dir(对象))我们可以很方便的查看对象有哪些属性,在conftest.py文件中编写钩子函数如下:

# file: conftest.py
def pytest_terminal_summary(terminalreporter, exitstatus, config):
    from pprint import pprint
    pprint(terminalreporter.__dict__)  # Python自省,输出terminalreporter对象的属性字典

编写一些实例用例,运行后屏幕输出的terminalreporter对象相关属性如下:

{'_already_displayed_warnings': None,
 '_collect_report_last_write': 1629647274.594309,
 '_keyboardinterrupt_memo': None,
 '_known_types': ['failed',
                  'passed',
                  'skipped',
                  'deselected',
                  'xfailed',
                  'xpassed',
                  'warnings',
                  'error'],
 '_main_color': 'red',
 '_numcollected': 7,
 '_progress_nodeids_reported': {'testcases/test_demo.py::test_01',
                                'testcases/test_demo.py::test_02',
                                'testcases/test_demo.py::test_03',
                                'testcases/test_demo.py::test_04',
                                'testcases/test_demo.py::test_05',
                                'testcases/test_demo.py::test_06',
                                'testcases/test_demo2.py::test_02'},
 '_screen_width': 155,
 '_session':  testsfailed=2 testscollected=7>,
 '_sessionstarttime': 1629647274.580377,
 '_show_progress_info': 'progress',
 '_showfspath': None,
 '_tests_ran': True,
 '_tw': <_pytest._io.terminalwriter.TerminalWriter object at 0x10766ebb0>,
 'config': <_pytest.config.Config object at 0x106239610>,
 'currentfspath': None,
 'hasmarkup': True,
 'isatty': True,
 'reportchars': 'wfE',
 'startdir': local('/Users/superhin/项目/pythonProject1'),
 'startpath': PosixPath('/Users/superhin/项目/pythonProject1'),
 'stats': {'': [,
                ,
                ,
                ,
                ,
                ,
                ,
                ,
                ,
                ,
                ,
                ,
                ],
           'failed': [,
                      ],
           'passed': [,
                      ],
           'skipped': [],
           'xfailed': [],
           'xpassed': []}}

可以看到stats属性为字典格式,其中包含了setup/teardown状态,以及各种状态(passed,failed,skipped,xfailed,xpassed)等用例结果(TestReport)列表。
我进一步打印一个TestReport对向

# file: conftest.py
def pytest_terminal_summary(terminalreporter, exitstatus, config):
    from pprint import pprint
    # pprint(terminalreporter.__dict__)  # Python自省,输出terminalreporter对象的属性字典
    pprint(terminalreporter.stats['passed'][0].__dict__)  # 第一个通过用例的TestReport对象属性

打印结果如下:

{'duration': 0.00029346700000010273,
 'extra': [],
 'keywords': {'pythonProject1': 1, 'test_01': 1, 'testcases/test_demo.py': 1},
 'location': ('testcases/test_demo.py', 11, 'test_01'),
 'longrepr': None,
 'nodeid': 'testcases/test_demo.py::test_01',
 'outcome': 'passed',
 'sections': [('Captured stdout call', 'test01\n')],
 'user_properties': [],
 'when': 'call'}

我们自己定义报告模板,使用Jinjia2,将stats属性中的统计数据渲染生成自定义报告,完整代码如下:

Jinja2官方使用文档参考:http://doc.yonyoucloud.com/doc/jinja2-docs-cn/index.html

# file: conftest.py
from jinja2 import Template

html_tpl = '''


    
    {{title}}
    


    

{{title}}

{% for item in results %} {% endfor %}
函数名 用例id 状态 用例输出 执行时间
{{item.location[2]}} {{item.nodeid}} {{item.outcome.strip()}} {% if item.sections %}{{item.sections[0][1].strip()}}{% endif %} {{item.duration}}
''' def pytest_terminal_summary(terminalreporter, exitstatus, config): results = [] for status in ['passed', 'failed', 'skipped', 'xfailed', 'xpassed']: if status in terminalreporter.stats: results.extend(terminalreporter.stats[status]) html = Template(html_tpl).render(title='测试报告', results=results) with open('report.html', 'w', encoding='utf-8') as f: f.write(html)

在命令行运行pytest生成的测试报告report.html示例如下


Pytest自定义测试报告

你可能感兴趣的:(Pytest使用钩子方法生成自定义测试报告)