Files
mes-demo/vendor/HTMLTestRunner.py

113 lines
3.7 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""Python3 兼容的精简版 HTMLTestRunner。
经典的 HTMLTestRunner 是 Py2 时代的第三方单文件实现,无法直接在 Py3 运行;
这里按同样的接口
(HTMLTestRunner(stream=fp, title=..., description=...).run(suite))
重新实现了一个精简版:输出带汇总统计 + 用例明细的 HTML 报告。
"""
import html
import sys
import time
import unittest
class _Result(unittest.TestResult):
def __init__(self):
super().__init__()
self.rows = [] # (name, doc, status, detail, duration)
def _record(self, test, status, detail=''):
doc = (test.shortDescription() or '').strip()
self.rows.append((str(test), doc, status, detail))
def addSuccess(self, test):
super().addSuccess(test)
self._record(test, '通过')
def addFailure(self, test, err):
super().addFailure(test, err)
self._record(test, '失败', self._exc_info_to_string(err, test))
def addError(self, test, err):
super().addError(test, err)
self._record(test, '错误', self._exc_info_to_string(err, test))
_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>{title}</title>
<style>
body {{ font-family: -apple-system, "Helvetica Neue", Arial, sans-serif; margin: 2em; }}
h1 {{ font-size: 1.4em; }}
table {{ border-collapse: collapse; width: 100%; margin-top: 1em; }}
th, td {{ border: 1px solid #ccc; padding: 6px 10px; font-size: 13px; text-align: left; }}
th {{ background: #f5f5f5; }}
.pass {{ color: #1a7f37; }} .fail {{ color: #cf222e; }} .error {{ color: #bf8700; }}
pre {{ white-space: pre-wrap; font-size: 12px; color: #666; }}
</style>
</head>
<body>
<h1>{title}</h1>
<p>{description}</p>
<p>开始时间:{start} 耗时:{duration:.2f}s 
总计:<strong>{total}</strong> 
<span class="pass">通过 {passed}</span> 
<span class="fail">失败 {failed}</span> 
<span class="error">错误 {errors}</span></p>
<table>
<tr><th>用例</th><th>说明</th><th>结果</th><th>详情</th></tr>
{rows}
</table>
</body>
</html>
"""
_ROW = ('<tr><td>{name}</td><td>{doc}</td>'
'<td class="{cls}">{status}</td><td>{detail}</td></tr>')
class HTMLTestRunner:
"""与 Py2 版 HTMLTestRunner 相同的调用接口。"""
def __init__(self, stream, title='测试报告', description=''):
self.stream = stream
self.title = title
self.description = description
def run(self, suite):
result = _Result()
start_time = time.time()
suite.run(result)
duration = time.time() - start_time
status_cls = {'通过': 'pass', '失败': 'fail', '错误': 'error'}
rows = []
for name, doc, status, detail in result.rows:
detail_html = ''
if detail:
detail_html = '<pre>{0}</pre>'.format(html.escape(detail))
rows.append(_ROW.format(
name=html.escape(name), doc=html.escape(doc),
cls=status_cls[status], status=status, detail=detail_html))
page = _TEMPLATE.format(
title=html.escape(self.title),
description=html.escape(self.description),
start=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time)),
duration=duration,
total=result.testsRun,
passed=len(result.rows) - len(result.failures) - len(result.errors),
failed=len(result.failures),
errors=len(result.errors),
rows='\n'.join(rows),
)
# stream 兼容二进制 / 文本两种打开方式
try:
self.stream.write(page.encode('utf-8'))
except TypeError:
self.stream.write(page)
return result