前言
- 本篇继续学习Hooks函数之pytest_terminal_summary统计测试结果
使用示例
- 在conftest.py中写入如下代码,用于手机测试结果
# -*- coding: utf-8 -*- # @Time : 2022/4/9 # @Author : 大海 import time from _pytest import terminal def pytest_terminal_summary(terminalreporter, exitstatus, config): """统计测试结果""" print(terminalreporter.stats) print("total:", terminalreporter._numcollected) print('passed:', len(terminalreporter.stats.get('passed', []))) print('failed:', len(terminalreporter.stats.get('failed', []))) print('error:', len(terminalreporter.stats.get('error', []))) print('skipped:', len(terminalreporter.stats.get('skipped', []))) # terminalreporter._sessionstarttime 会话开始时间 duration = time.time() - terminalreporter._sessionstarttime print('total times:', duration, 'seconds')
- 在test_67.py 文件中,写入如下代码
# -*- coding: utf-8 -*- # @Time : 2022/4/9 # @Author : 大海 import os import pytest def test_1(): print("测试用例1111") assert 1 == 1 @pytest.mark.skip("跳过") def test_2(): print("测试用例22222") assert 1 == 1 def test_3(): print("测试用例3333") def test_4(): print("测试用例44444444") assert 1 == 2 if __name__ == '__main__': os.system('pytest -s test_67.py')
- 运行test_67.py 查看运行结果
测试结果写入文件
- 修改conftest.py文件代码,内容如下
# -*- coding: utf-8 -*- # @Time : 2022/4/9 # @Author : 大海 import time from _pytest import terminal def pytest_terminal_summary(terminalreporter, exitstatus, config): '''收集测试结果''' # print(terminalreporter.stats) total = terminalreporter._numcollected passed= len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown']) failed=len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown']) error=len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown']) skipped=len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown']) successful = len(terminalreporter.stats.get('passed', []))/terminalreporter._numcollected*100 # terminalreporter._sessionstarttime 会话开始时间 duration = time.time() - terminalreporter._sessionstarttime print('total times: %.2f' % duration, 'seconds') with open("./result.txt", "w") as fp: fp.write("TOTAL=%s" % total+"\n") fp.write("PASSED=%s" % passed+"\n") fp.write("FAILED=%s" % failed+"\n") fp.write("ERROR=%s" % error+"\n") fp.write("SKIPPED=%s" % skipped+"\n") fp.write("SUCCESSFUL=%.2f%%" % successful+"\n") fp.write("TOTAL_TIMES=%.2fs" % duration)