将NoseXUnit生成的XML以报表的形式显示~
郭元凯
2023-12-01
# -*- coding:gbk -*-
from xml.etree import ElementTree
import datetime
def gettestresult():
filename='C:/Users/Pan/Desktop/test/test.xml'
etree = ElementTree.parse(filename)
root = etree.getroot()
#测试结果汇总
resulttotal = {}
resulttotal['ALL'] = root.get('tests')
resulttotal['NG'] = root.get('failures')
resulttotal['Block'] = root.get('errors')
resulttotal['NT'] = root.get('skip')
resulttotal['PASS'] = int(resulttotal['ALL'])-int(resulttotal['NT'])-int(resulttotal['NG'])-int(resulttotal['Block'])
#详细数据
results = []
for testnode in root:
result = {}
result['modulename'] = testnode.get('classname')
result['testcasename'] = testnode.get('name')
result['usetime'] = testnode.get('time')
try:
result['info_type'] = testnode[0].get('type')
result['info_message'] = testnode[0].get('message')
result['info_text'] = testnode[0].text
if testnode[0].tag == 'failure':
result['result'] = '未通过'
elif testnode[0].tag == 'error':
result['result'] = '阻塞'
else:
result['result'] = '未测试'
except:
result['info_type'] = ''
result['info_message'] = ''
result['info_text'] = ''
result['result'] = u'通过'
#通过映射表一一对应
result['taskname'] = ''
results.append(result)
return resulttotal,results
def buildhtml():
filee = open('test.html','w')
#头部
filee.write('''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>%(title)s</title>
</head>
<body>
'''%({'title':u'TestReport'}))
#测试结果汇总数据表表头
filee.write('''
<br>
<table width="500" border="1">
<tr>
<td>测试时间:</td>
<td colspan="4">%(datetime)s</td>
</tr>
<tr>
<td width="100">用例总数</td>
<td width="100">通过数</td>
<td width="100">失败数</td>
<td width="100">阻塞数</td>
<td width="100">未测试数</td>
</tr>
'''%({'datetime':datetime.datetime.today()}))
#测试结果汇总数据表内容
filee.write('''
<tr>
<td>%(ALL)s</td>
<td>%(PASS)s</td>
<td>%(NG)s</td>
<td>%(Block)s</td>
<td>%(NT)s</td>
</tr>
</table>
'''%(gettestresult()[0]))
#详细数据数据表表头
filee.write('''
<br>
<table width="1350" border="1">
<tr>
<td width="100" rowspan="2">模块</td>
<td width="100" rowspan="2">用例</td>
<td width="100" rowspan="2">耗时</td>
<td width="100" rowspan="2">测试任务</td>
<td width="100" rowspan="2">运行结果</td>
<td colspan="3">备注</td>
</tr>
<tr>
<td width="100">类型</td>
<td width="150">信息</td>
<td width="700">详细说明</td>
</tr>
''')
#详细数据数据表内容
for atestresult in gettestresult()[1]:
filee.write('''
<tr>
<td>%(modulename)s</td>
<td>%(testcasename)s</td>
<td>%(usetime)s</td>
<td>%(taskname)s</td>
<td>%(result)s</td>
<td>%(info_type)s</td>
<td>%(info_message)s</td>
<td>%(info_text)s</td>
</tr>
'''%(atestresult))
#尾部
filee.write('''
</table>
</body>
</html>
''')
filee.close()
if __name__ == '__main__':
buildhtml()