使用Pytest測(cè)試框架生成測(cè)試報(bào)告最常用的便是使用pytest-html
和allure-pytest
兩款插件了缀踪。
pytest-html簡(jiǎn)單(支持單html測(cè)試報(bào)告)闭翩,allure-pytest
則漂亮而強(qiáng)大挣郭。
當(dāng)然想要使用自定義模板生成測(cè)試報(bào)告也非常簡(jiǎn)單,簡(jiǎn)單實(shí)現(xiàn)步驟如下:
- 介入Pytest運(yùn)行流程疗韵,運(yùn)行后自動(dòng)生成HTML測(cè)試報(bào)告:使用Hooks方法
- 拿到運(yùn)行結(jié)果統(tǒng)計(jì)數(shù)據(jù):鉤子方法pytest_terminal_summary的terminalreporter對(duì)象的stats屬性中
- 渲染HTML報(bào)告模板生成測(cè)試報(bào)告:使用Jinjia2
經(jīng)研究兑障,Hooks方法pytest_terminal_summary及運(yùn)行完畢生成命令行總結(jié)中包含的terminalreporter對(duì)象的stats屬性中包含我們需要的測(cè)試結(jié)果統(tǒng)計(jì)。
鉤子運(yùn)行流程可以參考:https://www.cnblogs.com/superhin/p/11733499.html
使用Pytest的對(duì)象自式锻簟(對(duì)象.__dict__
或dir(對(duì)象)
)我們可以很方便的查看對(duì)象有哪些屬性流译,在conftest.py文件中編寫鉤子函數(shù)如下:
# file: conftest.py
def pytest_terminal_summary(terminalreporter, exitstatus, config):
from pprint import pprint
pprint(terminalreporter.__dict__) # Python自省,輸出terminalreporter對(duì)象的屬性字典
編寫一些實(shí)例用例者疤,運(yùn)行后屏幕輸出的terminalreporter對(duì)象相關(guān)屬性如下:
{'_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': <Session pythonProject1 exitstatus=<ExitCode.TESTS_FAILED: 1> 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/項(xiàng)目/pythonProject1'),
'startpath': PosixPath('/Users/superhin/項(xiàng)目/pythonProject1'),
'stats': {'': [<TestReport 'testcases/test_demo.py::test_01' when='setup' outcome='passed'>,
<TestReport 'testcases/test_demo.py::test_01' when='teardown' outcome='passed'>,
<TestReport 'testcases/test_demo.py::test_02' when='setup' outcome='passed'>,
<TestReport 'testcases/test_demo.py::test_02' when='teardown' outcome='passed'>,
<TestReport 'testcases/test_demo.py::test_03' when='setup' outcome='passed'>,
<TestReport 'testcases/test_demo.py::test_03' when='teardown' outcome='passed'>,
<TestReport 'testcases/test_demo.py::test_04' when='teardown' outcome='passed'>,
<TestReport 'testcases/test_demo.py::test_05' when='setup' outcome='passed'>,
<TestReport 'testcases/test_demo.py::test_05' when='teardown' outcome='passed'>,
<TestReport 'testcases/test_demo.py::test_06' when='setup' outcome='passed'>,
<TestReport 'testcases/test_demo.py::test_06' when='teardown' outcome='passed'>,
<TestReport 'testcases/test_demo2.py::test_02' when='setup' outcome='passed'>,
<TestReport 'testcases/test_demo2.py::test_02' when='teardown' outcome='passed'>],
'failed': [<TestReport 'testcases/test_demo.py::test_02' when='call' outcome='failed'>,
<TestReport 'testcases/test_demo.py::test_03' when='call' outcome='failed'>],
'passed': [<TestReport 'testcases/test_demo.py::test_01' when='call' outcome='passed'>,
<TestReport 'testcases/test_demo2.py::test_02' when='call' outcome='passed'>],
'skipped': [<TestReport 'testcases/test_demo.py::test_04' when='setup' outcome='skipped'>],
'xfailed': [<TestReport 'testcases/test_demo.py::test_05' when='call' outcome='skipped'>],
'xpassed': [<TestReport 'testcases/test_demo.py::test_06' when='call' outcome='passed'>]}}
可以看到stats屬性為字典格式福澡,其中包含了setup/teardown狀態(tài),以及各種狀態(tài)(passed驹马,failed革砸,skipped,xfailed糯累,xpassed)等用例結(jié)果(TestReport)列表算利。
我進(jìn)一步打印一個(gè)TestReport對(duì)向
# file: conftest.py
def pytest_terminal_summary(terminalreporter, exitstatus, config):
from pprint import pprint
# pprint(terminalreporter.__dict__) # Python自省,輸出terminalreporter對(duì)象的屬性字典
pprint(terminalreporter.stats['passed'][0].__dict__) # 第一個(gè)通過用例的TestReport對(duì)象屬性
打印結(jié)果如下:
{'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'}
我們自己定義報(bào)告模板寇蚊,使用Jinjia2笔时,將stats屬性中的統(tǒng)計(jì)數(shù)據(jù)渲染生成自定義報(bào)告,完整代碼如下:
Jinja2官方使用文檔參考:http://doc.yonyoucloud.com/doc/jinja2-docs-cn/index.html
# file: conftest.py
from jinja2 import Template
html_tpl = '''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
<style>
table {border-spacing: 0;}
th {background-color: #ccc}
td {padding: 5px; border: 1px solid #ccc;}
</style>
</head>
<body>
<h2>{{title}}</h2>
<table>
<tr> <th>函數(shù)名</th> <th>用例id</th> <th>狀態(tài)</td> <th>用例輸出</th> <th>執(zhí)行時(shí)間</th> </tr>
{% for item in results %}
<tr>
<td>{{item.location[2]}}</td>
<td>{{item.nodeid}}</td>
<td>{{item.outcome.strip()}}</td>
<td>{% if item.sections %}{{item.sections[0][1].strip()}}{% endif %}</td>
<td>{{item.duration}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>'''
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='測(cè)試報(bào)告', results=results)
with open('report.html', 'w', encoding='utf-8') as f:
f.write(html)
在命令行運(yùn)行pytest生成的測(cè)試報(bào)告report.html示例如下