1. # FileName : MyHTMLTestRunner.py
  2. # Author : wangyinghao
  3. # DateTime : 2019/1/9 21:04
  4. # SoftWare : PyCharm
  5. """
  6. A TestRunner for use with the Python unit testing framework. It
  7. generates a HTML report to show the result at a glance.
  8.  
  9. The simplest way to use this is to invoke its main method. E.g.
  10.  
  11. import unittest
  12. import HTMLTestRunner
  13.  
  14. ... define your tests ...
  15.  
  16. if __name__ == '__main__':
  17. HTMLTestRunner.main()
  18.  
  19. For more customization options, instantiates a HTMLTestRunner object.
  20. HTMLTestRunner is a counterpart to unittest's TextTestRunner. E.g.
  21.  
  22. # output to a file
  23. fp = file('my_report.html', 'wb')
  24. runner = HTMLTestRunner.HTMLTestRunner(
  25. stream=fp,
  26. title='My unit test',
  27. description='This demonstrates the report output by HTMLTestRunner.'
  28. )
  29.  
  30. # Use an external stylesheet.
  31. # See the Template_mixin class for more customizable options
  32. runner.STYLESHEET_TMPL = '<link rel="stylesheet" href="my_stylesheet.css" type="text/css">'
  33.  
  34. # run the test
  35. runner.run(my_test_suite)
  36.  
  37. ------------------------------------------------------------------------
  38. Copyright (c) 2004-2007, Wai Yip Tung
  39. All rights reserved.
  40.  
  41. Redistribution and use in source and binary forms, with or without
  42. modification, are permitted provided that the following conditions are
  43. met:
  44.  
  45. * Redistributions of source code must retain the above copyright notice,
  46. this list of conditions and the following disclaimer.
  47. * Redistributions in binary form must reproduce the above copyright
  48. notice, this list of conditions and the following disclaimer in the
  49. documentation and/or other materials provided with the distribution.
  50. * Neither the name Wai Yip Tung nor the names of its contributors may be
  51. used to endorse or promote products derived from this software without
  52. specific prior written permission.
  53.  
  54. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  55. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  56. TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  57. PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
  58. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  59. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  60. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  61. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  62. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  63. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  64. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  65. """
  66.  
  67. # URL: http://tungwaiyip.info/software/HTMLTestRunner.html
  68.  
  69. __author__ = "Wai Yip Tung, Findyou,Adil"
  70. __version__ = "0.8.2.3"
  71.  
  72. """
  73. Change History
  74. Version 0.8.2.1 -Findyou
  75. * 改为支持python3
  76.  
  77. Version 0.8.2.1 -Findyou
  78. * 支持中文,汉化
  79. * 调整样式,美化(需要连入网络,使用的百度的Bootstrap.js)
  80. * 增加 通过分类显示、测试人员、通过率的展示
  81. * 优化“详细”与“收起”状态的变换
  82. * 增加返回顶部的锚点
  83.  
  84. Version 0.8.2
  85. * Show output inline instead of popup window (Viorel Lupu).
  86.  
  87. Version in 0.8.1
  88. * Validated XHTML (Wolfgang Borgert).
  89. * Added description of test classes and test cases.
  90.  
  91. Version in 0.8.0
  92. * Define Template_mixin class for customization.
  93. * Workaround a IE 6 bug that it does not treat <script> block as CDATA.
  94.  
  95. Version in 0.7.1
  96. * Back port to Python 2.3 (Frank Horowitz).
  97. * Fix missing scroll bars in detail log (Podi).
  98. """
  99.  
  100. # TODO: color stderr
  101. # TODO: simplify javascript using ,ore than 1 class in the class attribute?
  102.  
  103. import datetime
  104. import io
  105. import sys
  106. import time
  107. import unittest
  108. from xml.sax import saxutils
  109. import sys
  110.  
  111. # ------------------------------------------------------------------------
  112. # The redirectors below are used to capture output during testing. Output
  113. # sent to sys.stdout and sys.stderr are automatically captured. However
  114. # in some cases sys.stdout is already cached before HTMLTestRunner is
  115. # invoked (e.g. calling logging.basicConfig). In order to capture those
  116. # output, use the redirectors for the cached stream.
  117. #
  118. # e.g.
  119. # >>> logging.basicConfig(stream=HTMLTestRunner.stdout_redirector)
  120. # >>>
  121.  
  122. class OutputRedirector(object):
  123. """ Wrapper to redirect stdout or stderr """
  124. def __init__(self, fp):
  125. self.fp = fp
  126.  
  127. def write(self, s):
  128. self.fp.write(s)
  129.  
  130. def writelines(self, lines):
  131. self.fp.writelines(lines)
  132.  
  133. def flush(self):
  134. self.fp.flush()
  135.  
  136. stdout_redirector = OutputRedirector(sys.stdout)
  137. stderr_redirector = OutputRedirector(sys.stderr)
  138.  
  139. # ----------------------------------------------------------------------
  140. # Template
  141.  
  142. class Template_mixin(object):
  143. """
  144. Define a HTML template for report customerization and generation.
  145.  
  146. Overall structure of an HTML report
  147.  
  148. HTML
  149. +------------------------+
  150. |<html> |
  151. | <head> |
  152. | |
  153. | STYLESHEET |
  154. | +----------------+ |
  155. | | | |
  156. | +----------------+ |
  157. | |
  158. | </head> |
  159. | |
  160. | <body> |
  161. | |
  162. | HEADING |
  163. | +----------------+ |
  164. | | | |
  165. | +----------------+ |
  166. | |
  167. | REPORT |
  168. | +----------------+ |
  169. | | | |
  170. | +----------------+ |
  171. | |
  172. | ENDING |
  173. | +----------------+ |
  174. | | | |
  175. | +----------------+ |
  176. | |
  177. | </body> |
  178. |</html> |
  179. +------------------------+
  180. """
  181.  
  182. STATUS = {
  183. 0: '通过',
  184. 1: '失败',
  185. 2: '错误',
  186. }
  187. # 默认测试标题
  188. DEFAULT_TITLE = 'UI测试报告'
  189. DEFAULT_DESCRIPTION = ''
  190. # 默认测试人员
  191. DEFAULT_TESTER = 'WangYIngHao'
  192.  
  193. # ------------------------------------------------------------------------
  194. # HTML Template
  195.  
  196. HTML_TMPL = r"""<?xml version="1.0" encoding="UTF-8"?>
  197. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  198. <html xmlns="http://www.w3.org/1999/xhtml">
  199. <head>
  200. <title>%(title)s</title>
  201. <meta name="generator" content="%(generator)s"/>
  202. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  203. <link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
  204. <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  205. <script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
  206. %(stylesheet)s
  207. </head>
  208. <body >
  209. <script language="javascript" type="text/javascript">
  210. output_list = Array();
  211.  
  212. /*level 调整增加只显示通过用例的分类 --Adil
  213. 0:Summary //all hiddenRow
  214. 1:Failed //pt hiddenRow, ft none
  215. 2:Pass //pt none, ft hiddenRow
  216. 3:Error // pt hiddenRow, ft none
  217. 4:All //pt none, ft none
  218. 下面设置 按钮展开逻辑 --Yang Yao Jun
  219. */
  220. function showCase(level) {
  221. trs = document.getElementsByTagName("tr");
  222. for (var i = 0; i < trs.length; i++) {
  223. tr = trs[i];
  224. id = tr.id;
  225. if (id.substr(0,2) == 'ft') {
  226. if (level == 2 || level == 0 ) {
  227. tr.className = 'hiddenRow';
  228. }
  229. else {
  230. tr.className = '';
  231. }
  232. }
  233. if (id.substr(0,2) == 'pt') {
  234. if (level < 2 || level ==3 ) {
  235. tr.className = 'hiddenRow';
  236. }
  237. else {
  238. tr.className = '';
  239. }
  240. }
  241. }
  242.  
  243. //加入【详细】切换文字变化 --Findyou
  244. detail_class=document.getElementsByClassName('detail');
  245. //console.log(detail_class.length)
  246. if (level == 3) {
  247. for (var i = 0; i < detail_class.length; i++){
  248. detail_class[i].innerHTML="收起"
  249. }
  250. }
  251. else{
  252. for (var i = 0; i < detail_class.length; i++){
  253. detail_class[i].innerHTML="详细"
  254. }
  255. }
  256. }
  257.  
  258. function showClassDetail(cid, count) {
  259. var id_list = Array(count);
  260. var toHide = 1;
  261. for (var i = 0; i < count; i++) {
  262. //ID修改 点 为 下划线 -Findyou
  263. tid0 = 't' + cid.substr(1) + '_' + (i+1);
  264. tid = 'f' + tid0;
  265. tr = document.getElementById(tid);
  266. if (!tr) {
  267. tid = 'p' + tid0;
  268. tr = document.getElementById(tid);
  269. }
  270. id_list[i] = tid;
  271. if (tr.className) {
  272. toHide = 0;
  273. }
  274. }
  275. for (var i = 0; i < count; i++) {
  276. tid = id_list[i];
  277. //修改点击无法收起的BUG,加入【详细】切换文字变化 --Findyou
  278. if (toHide) {
  279. document.getElementById(tid).className = 'hiddenRow';
  280. document.getElementById(cid).innerText = "详细"
  281. }
  282. else {
  283. document.getElementById(tid).className = '';
  284. document.getElementById(cid).innerText = "收起"
  285. }
  286. }
  287. }
  288.  
  289. function html_escape(s) {
  290. s = s.replace(/&/g,'&');
  291. s = s.replace(/</g,'<');
  292. s = s.replace(/>/g,'>');
  293. return s;
  294. }
  295. </script>
  296. %(heading)s
  297. %(report)s
  298. %(ending)s
  299.  
  300. </body>
  301. </html>
  302. """
  303. # variables: (title, generator, stylesheet, heading, report, ending)
  304.  
  305. # ------------------------------------------------------------------------
  306. # Stylesheet
  307. #
  308. # alternatively use a <link> for external style sheet, e.g.
  309. # <link rel="stylesheet" href="$url" type="text/css">
  310.  
  311. STYLESHEET_TMPL = """
  312. <style type="text/css" media="screen">
  313. body { font-family: Microsoft YaHei,Tahoma,arial,helvetica,sans-serif;padding: 20px; font-size: 80%; }
  314. table { font-size: 100%; }
  315.  
  316. /* -- heading ---------------------------------------------------------------------- */
  317. .heading {
  318. margin-top: 0ex;
  319. margin-bottom: 1ex;
  320. }
  321.  
  322. .heading .description {
  323. margin-top: 4ex;
  324. margin-bottom: 6ex;
  325. }
  326.  
  327. /* -- report ------------------------------------------------------------------------ */
  328. #total_row { font-weight: bold; }
  329. .passCase { color: #5cb85c; }
  330. .failCase { color: #d9534f; font-weight: bold; }
  331. .errorCase { color: #f0ad4e; font-weight: bold; }
  332. .hiddenRow { display: none; }
  333. .testcase { margin-left: 2em; }
  334. </style>
  335. """
  336.  
  337. # ------------------------------------------------------------------------
  338. # Heading
  339. #
  340.  
  341. HEADING_TMPL = """<div class='heading'>
  342. <h1 style="font-family: Microsoft YaHei">%(title)s</h1>
  343. %(parameters)s
  344. <p class='description'>%(description)s</p>
  345. </div>
  346.  
  347. """ # variables: (title, parameters, description)
  348.  
  349. HEADING_ATTRIBUTE_TMPL = """<p class='attribute'><strong>%(name)s : </strong> %(value)s</p>
  350. """ # variables: (name, value)
  351.  
  352. # ------------------------------------------------------------------------
  353. # Report
  354. #
  355. # 汉化,加美化效果 --Yang Yao Jun
  356. #
  357. # 这里涉及到了 Bootstrap 前端技术,Bootstrap 按钮 资料介绍详见:http://www.runoob.com/bootstrap/bootstrap-buttons.html
  358. #
  359. REPORT_TMPL = """
  360. <p id='show_detail_line'>
  361. <a class="btn btn-primary" href='javascript:showCase(0)'>通过率 [%(passrate)s ]</a>
  362. <a class="btn btn-success" href='javascript:showCase(2)'>通过[ %(Pass)s ]</a>
  363. <a class="btn btn-warning" href='javascript:showCase(3)'>错误[ %(error)s ]</a>
  364. <a class="btn btn-danger" href='javascript:showCase(1)'>失败[ %(fail)s ]</a>
  365. <a class="btn btn-info" href='javascript:showCase(4)'>所有[ %(count)s ]</a>
  366. </p>
  367. <table id='result_table' class="table table-condensed table-bordered table-hover">
  368. <colgroup>
  369. <col align='left' />
  370. <col align='right' />
  371. <col align='right' />
  372. <col align='right' />
  373. <col align='right' />
  374. <col align='right' />
  375. </colgroup>
  376. <tr id='header_row' class="text-center success" style="font-weight: bold;font-size: 14px;">
  377. <td>用例集/测试用例</td>
  378. <td>总计</td>
  379. <td>通过</td>
  380. <td>错误</td>
  381. <td>失败</td>
  382. <td>详细</td>
  383. </tr>
  384. %(test_list)s
  385. <tr id='total_row' class="text-center active">
  386. <td>总计</td>
  387. <td>%(count)s</td>
  388. <td>%(Pass)s</td>
  389. <td>%(error)s</td>
  390. <td>%(fail)s</td>
  391. <td>通过率:%(passrate)s</td>
  392. </tr>
  393. </table>
  394. """ # variables: (test_list, count, Pass, fail, error ,passrate)
  395.  
  396. REPORT_CLASS_TMPL = r"""
  397. <tr class='%(style)s warning'>
  398. <td>%(desc)s</td>
  399. <td class="text-center">%(count)s</td>
  400. <td class="text-center">%(Pass)s</td>
  401. <td class="text-center">%(error)s</td>
  402. <td class="text-center">%(fail)s</td>
  403. <td class="text-center"><a href="javascript:showClassDetail('%(cid)s',%(count)s)" class="detail" id='%(cid)s'>详细</a></td>
  404. </tr>
  405. """ # variables: (style, desc, count, Pass, fail, error, cid)
  406.  
  407. #失败 的样式,去掉原来JS效果,美化展示效果 -Findyou
  408. REPORT_TEST_WITH_OUTPUT_TMPL = r"""
  409. <tr id='%(tid)s' class='%(Class)s'>
  410. <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
  411. <td colspan='5' align='center'>
  412. <!--默认收起错误信息 -Findyou
  413. <button id='btn_%(tid)s' type="button" class="btn btn-danger btn-xs collapsed" data-toggle="collapse" data-target='#div_%(tid)s'>%(status)s</button>
  414. <div id='div_%(tid)s' class="collapse"> -->
  415.  
  416. <!-- 默认展开错误信息 -Findyou -->
  417. <button id='btn_%(tid)s' type="button" class="btn btn-danger btn-xs" data-toggle="collapse" data-target='#div_%(tid)s'>%(status)s</button>
  418. <div id='div_%(tid)s' class="collapse in" style='text-align: left; color:red;cursor:pointer'>
  419. <pre>
  420. %(script)s
  421. </pre>
  422. </div>
  423. </td>
  424. </tr>
  425. """ # variables: (tid, Class, style, desc, status)
  426.  
  427. # 通过 的样式,加标签效果 -Findyou
  428. REPORT_TEST_NO_OUTPUT_TMPL = r"""
  429. <tr id='%(tid)s' class='%(Class)s'>
  430. <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
  431. <td colspan='5' align='center'><span class="label label-success success">%(status)s</span></td>
  432. </tr>
  433. """ # variables: (tid, Class, style, desc, status)
  434.  
  435. REPORT_TEST_OUTPUT_TMPL = r"""
  436. %(id)s: %(output)s
  437. """ # variables: (id, output)
  438.  
  439. # ------------------------------------------------------------------------
  440. # ENDING
  441. #
  442. # 增加返回顶部按钮 --Findyou
  443. ENDING_TMPL = """<div id='ending'> </div>
  444. <div style=" position:fixed;right:50px; bottom:30px; width:20px; height:20px;cursor:pointer">
  445. <a href="#"><span class="glyphicon glyphicon-eject" style = "font-size:30px;" aria-hidden="true">
  446. </span></a></div>
  447. """
  448.  
  449. # -------------------- The end of the Template class -------------------
  450.  
  451. TestResult = unittest.TestResult
  452.  
  453. class _TestResult(TestResult):
  454. # note: _TestResult is a pure representation of results.
  455. # It lacks the output and reporting ability compares to unittest._TextTestResult.
  456.  
  457. def __init__(self, verbosity=1):
  458. TestResult.__init__(self)
  459. self.stdout0 = None
  460. self.stderr0 = None
  461. self.success_count = 0
  462. self.failure_count = 0
  463. self.error_count = 0
  464. self.verbosity = verbosity
  465.  
  466. # result is a list of result in 4 tuple
  467. # (
  468. # result code (0: success; 1: fail; 2: error),
  469. # TestCase object,
  470. # Test output (byte string),
  471. # stack trace,
  472. # )
  473. self.result = []
  474. #增加一个测试通过率 --Findyou
  475. self.passrate=float(0)
  476.  
  477. def startTest(self, test):
  478. TestResult.startTest(self, test)
  479. # just one buffer for both stdout and stderr
  480. self.outputBuffer = io.StringIO()
  481. stdout_redirector.fp = self.outputBuffer
  482. stderr_redirector.fp = self.outputBuffer
  483. self.stdout0 = sys.stdout
  484. self.stderr0 = sys.stderr
  485. sys.stdout = stdout_redirector
  486. sys.stderr = stderr_redirector
  487.  
  488. def complete_output(self):
  489. """
  490. Disconnect output redirection and return buffer.
  491. Safe to call multiple times.
  492. """
  493. if self.stdout0:
  494. sys.stdout = self.stdout0
  495. sys.stderr = self.stderr0
  496. self.stdout0 = None
  497. self.stderr0 = None
  498. return self.outputBuffer.getvalue()
  499.  
  500. def stopTest(self, test):
  501. # Usually one of addSuccess, addError or addFailure would have been called.
  502. # But there are some path in unittest that would bypass this.
  503. # We must disconnect stdout in stopTest(), which is guaranteed to be called.
  504. self.complete_output()
  505.  
  506. def addSuccess(self, test):
  507. self.success_count += 1
  508. TestResult.addSuccess(self, test)
  509. output = self.complete_output()
  510. self.result.append((0, test, output, ''))
  511. if self.verbosity > 1:
  512. sys.stderr.write('ok ')
  513. sys.stderr.write(str(test))
  514. sys.stderr.write('\n')
  515. else:
  516. sys.stderr.write('.')
  517.  
  518. def addError(self, test, err):
  519. self.error_count += 1
  520. TestResult.addError(self, test, err)
  521. _, _exc_str = self.errors[-1]
  522. output = self.complete_output()
  523. self.result.append((2, test, output, _exc_str))
  524. if self.verbosity > 1:
  525. sys.stderr.write('E ')
  526. sys.stderr.write(str(test))
  527. sys.stderr.write('\n')
  528. else:
  529. sys.stderr.write('E')
  530.  
  531. def addFailure(self, test, err):
  532. self.failure_count += 1
  533. TestResult.addFailure(self, test, err)
  534. _, _exc_str = self.failures[-1]
  535. output = self.complete_output()
  536. self.result.append((1, test, output, _exc_str))
  537. if self.verbosity > 1:
  538. sys.stderr.write('F ')
  539. sys.stderr.write(str(test))
  540. sys.stderr.write('\n')
  541. else:
  542. sys.stderr.write('F')
  543.  
  544. class HTMLTestRunner(Template_mixin):
  545. """
  546. """
  547. def __init__(self, stream=sys.stdout, verbosity=1,title=None,description=None,tester=None):
  548. self.stream = stream
  549. self.verbosity = verbosity
  550. if title is None:
  551. self.title = self.DEFAULT_TITLE
  552. else:
  553. self.title = title
  554. if description is None:
  555. self.description = self.DEFAULT_DESCRIPTION
  556. else:
  557. self.description = description
  558. if tester is None:
  559. self.tester = self.DEFAULT_TESTER
  560. else:
  561. self.tester = tester
  562.  
  563. self.startTime = datetime.datetime.now()
  564.  
  565. def run(self, test):
  566. "Run the given test case or test suite."
  567. result = _TestResult(self.verbosity)
  568. test(result)
  569. self.stopTime = datetime.datetime.now()
  570. self.generateReport(test, result)
  571. print('\nTime Elapsed: %s' % (self.stopTime-self.startTime), file=sys.stderr)
  572. return result
  573.  
  574. def sortResult(self, result_list):
  575. # unittest does not seems to run in any particular order.
  576. # Here at least we want to group them together by class.
  577. rmap = {}
  578. classes = []
  579. for n,t,o,e in result_list:
  580. cls = t.__class__
  581. if cls not in rmap:
  582. rmap[cls] = []
  583. classes.append(cls)
  584. rmap[cls].append((n,t,o,e))
  585. r = [(cls, rmap[cls]) for cls in classes]
  586. return r
  587.  
  588. #替换测试结果status为通过率 --Findyou
  589. def getReportAttributes(self, result):
  590. """
  591. Return report attributes as a list of (name, value).
  592. Override this to add custom attributes.
  593. """
  594. startTime = str(self.startTime)[:19]
  595. duration = str(self.stopTime - self.startTime)
  596. status = []
  597. status.append('共 %s' % (result.success_count + result.failure_count + result.error_count))
  598. if result.success_count: status.append('通过 %s' % result.success_count)
  599. if result.failure_count: status.append('失败 %s' % result.failure_count)
  600. if result.error_count: status.append('错误 %s' % result.error_count )
  601. if status:
  602. status = ','.join(status)
  603. self.passrate = str("%.2f%%" % (float(result.success_count) / float(result.success_count + result.failure_count + result.error_count) * 100))
  604. else:
  605. status = 'none'
  606. return [
  607. ('测试人员', self.tester),
  608. ('开始时间',startTime),
  609. ('合计耗时',duration),
  610. ('测试结果',status + ",通过率= "+self.passrate),
  611. ]
  612.  
  613. def generateReport(self, test, result):
  614. report_attrs = self.getReportAttributes(result)
  615. generator = 'HTMLTestRunner %s' % __version__
  616. stylesheet = self._generate_stylesheet()
  617. heading = self._generate_heading(report_attrs)
  618. report = self._generate_report(result)
  619. ending = self._generate_ending()
  620. output = self.HTML_TMPL % dict(
  621. title = saxutils.escape(self.title),
  622. generator = generator,
  623. stylesheet = stylesheet,
  624. heading = heading,
  625. report = report,
  626. ending = ending,
  627. )
  628. self.stream.write(output.encode('utf8'))
  629.  
  630. def _generate_stylesheet(self):
  631. return self.STYLESHEET_TMPL
  632.  
  633. #增加Tester显示 -Findyou
  634. def _generate_heading(self, report_attrs):
  635. a_lines = []
  636. for name, value in report_attrs:
  637. line = self.HEADING_ATTRIBUTE_TMPL % dict(
  638. name = saxutils.escape(name),
  639. value = saxutils.escape(value),
  640. )
  641. a_lines.append(line)
  642. heading = self.HEADING_TMPL % dict(
  643. title = saxutils.escape(self.title),
  644. parameters = ''.join(a_lines),
  645. description = saxutils.escape(self.description),
  646. tester= saxutils.escape(self.tester),
  647. )
  648. return heading
  649.  
  650. #生成报告 --Findyou添加注释
  651. def _generate_report(self, result):
  652. rows = []
  653. sortedResult = self.sortResult(result.result)
  654. for cid, (cls, cls_results) in enumerate(sortedResult):
  655. # subtotal for a class
  656. np = nf = ne = 0
  657. for n,t,o,e in cls_results:
  658. if n == 0: np += 1
  659. elif n == 1: nf += 1
  660. else: ne += 1
  661.  
  662. # format class description
  663. if cls.__module__ == "__main__":
  664. name = cls.__name__
  665. else:
  666. name = "%s.%s" % (cls.__module__, cls.__name__)
  667. doc = cls.__doc__ and cls.__doc__.split("\n")[0] or ""
  668. desc = doc and '%s: %s' % (name, doc) or name
  669.  
  670. row = self.REPORT_CLASS_TMPL % dict(
  671. style = ne > 0 and 'errorClass' or nf > 0 and 'failClass' or 'passClass',
  672. desc = desc,
  673. count = np+nf+ne,
  674. Pass = np,
  675. fail = nf,
  676. error = ne,
  677. cid = 'c%s' % (cid+1),
  678. )
  679. rows.append(row)
  680.  
  681. for tid, (n,t,o,e) in enumerate(cls_results):
  682. self._generate_report_test(rows, cid, tid, n, t, o, e)
  683.  
  684. report = self.REPORT_TMPL % dict(
  685. test_list = ''.join(rows),
  686. count = str(result.success_count+result.failure_count+result.error_count),
  687. Pass = str(result.success_count),
  688. fail = str(result.failure_count),
  689. error = str(result.error_count),
  690. passrate =self.passrate,
  691. )
  692. return report
  693.  
  694. def _generate_report_test(self, rows, cid, tid, n, t, o, e):
  695. # e.g. 'pt1.1', 'ft1.1', etc
  696. has_output = bool(o or e)
  697. # ID修改点为下划线,支持Bootstrap折叠展开特效 - Findyou
  698. tid = (n == 0 and 'p' or 'f') + 't%s_%s' % (cid+1,tid+1)
  699. name = t.id().split('.')[-1]
  700. doc = t.shortDescription() or ""
  701. desc = doc and ('%s: %s' % (name, doc)) or name
  702. tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL
  703.  
  704. # utf-8 支持中文 - Findyou
  705. # o and e should be byte string because they are collected from stdout and stderr?
  706. if isinstance(o, str):
  707. # TODO: some problem with 'string_escape': it escape \n and mess up formating
  708. # uo = unicode(o.encode('string_escape'))
  709. # uo = o.decode('latin-1')
  710. uo = o
  711. else:
  712. uo = o
  713. if isinstance(e, str):
  714. # TODO: some problem with 'string_escape': it escape \n and mess up formating
  715. # ue = unicode(e.encode('string_escape'))
  716. # ue = e.decode('latin-1')
  717. ue = e
  718. else:
  719. ue = e
  720.  
  721. script = self.REPORT_TEST_OUTPUT_TMPL % dict(
  722. id = tid,
  723. output = saxutils.escape(uo+ue),
  724. )
  725.  
  726. row = tmpl % dict(
  727. tid = tid,
  728. Class = (n == 0 and 'hiddenRow' or 'none'),
  729. style = n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'passCase'),
  730. desc = desc,
  731. script = script,
  732. status = self.STATUS[n],
  733. )
  734. rows.append(row)
  735. if not has_output:
  736. return
  737.  
  738. def _generate_ending(self):
  739. return self.ENDING_TMPL
  740.  
  741. ##############################################################################
  742. # Facilities for running tests from the command line
  743. ##############################################################################
  744.  
  745. # Note: Reuse unittest.TestProgram to launch test. In the future we may
  746. # build our own launcher to support more specific command line
  747. # parameters like test title, CSS, etc.
  748. class TestProgram(unittest.TestProgram):
  749. """
  750. A variation of the unittest.TestProgram. Please refer to the base
  751. class for command line parameters.
  752. """
  753. def runTests(self):
  754. # Pick HTMLTestRunner as the default test runner.
  755. # base class's testRunner parameter is not useful because it means
  756. # we have to instantiate HTMLTestRunner before we know self.verbosity.
  757. if self.testRunner is None:
  758. self.testRunner = HTMLTestRunner(verbosity=self.verbosity)
  759. unittest.TestProgram.runTests(self)
  760.  
  761. main = TestProgram
  762.  
  763. ##############################################################################
  764. # Executing this module from the command line
  765. ##############################################################################
  766.  
  767. if __name__ == "__main__":
  768. main(module=None)

效果:

Python3 HTMLTestRunner自动化测试报告美化的更多相关文章

  1. Python2 HTMLTestRunner自动化测试报告美化

    python2 的测试报告美化,需要的同学直接用 #coding=utf-8 """ A TestRunner for use with the Python unit ...

  2. HTMLTESTRunner自动化测试报告增加截图功能

    我们都知道HTMLTESTRunner自动化测试报告,是Unittest单元测试框架报告,那么在做ui测试的时候就有点不适用了. 我们需要出错截图功能. 以下是我改的,增加了截图功能,先展示界面,再展 ...

  3. HTMLTestRunner 自动化测试报告

    http://tungwaiyip.info/software/HTMLTestRunner.html下载,将下载后的文件放在python的Lib目录下 # -*- coding:utf-8 -*- ...

  4. HTMLTestRunner测试报告美化

    前言 ​最近小伙伴们在学玩python,,看着那HTMLTestRunner生成的测试报告,左右看不顺眼,终觉得太丑.搜索了一圈没有找到合适的美化报告,于是忍不住自已动手进行了修改,因习惯python ...

  5. Python+Selenium----使用HTMLTestRunner.py生成自动化测试报告1(使用IDLE)

    1.说明 自动化测试报告是一个很重要的测试数据,网上看了一下,使用HTMLTestRunner.py生成自动化测试报告使用的比较多,但是呢,小白刚刚入手,不太懂,看了很多博客,终于生成了一个测试报告, ...

  6. Python+Selenium----使用HTMLTestRunner.py生成自动化测试报告2(使用PyCharm )

    1.说明 在我前一篇文件(Python+Selenium----使用HTMLTestRunner.py生成自动化测试报告1(使用IDLE ))中简单的写明了,如何生产测试报告,但是使用IDLE很麻烦, ...

  7. Python3+HTMLTestRunner+SMTP生成测试报告后发送邮件

    在前一篇https://www.cnblogs.com/zhengyihan1216/p/11549820.html 中记录了如何生成html格式的报告, 这篇记录下怎么将测试报告通过邮件发出 1.对 ...

  8. Python&Selenium借助HTMLTestRunner生成自动化测试报告

    一.摘要 本篇博文介绍Python和Selenium进行自动化测试时,借助著名的HTMLTestRunner生成自动化测试报告 HTMLTestRunner.py百度很多,版本也很多,自行搜索下载放到 ...

  9. Python&Selenium借助html-testRunner生成自动化测试报告

    一.摘要 本博文将介绍Python和Selenium进行自动化测试时,借助html-testRunner 生成自动化测试报告 安装命令:pip install html-testRunner 二.测试 ...

随机推荐

  1. C#之razor

    学习的文章在这里:http://www.cnblogs.com/yang_sy/archive/2013/08/26/ASPNET_MVC_RAZOR_ENGINE.html 1.视图开始文件_Vie ...

  2. VM安装centOS6.9

    1.首先要下载一个centos的iso镜像,用VMware创建一个空白硬盘. 2.创建完毕再设置里面挂载iso的centos系统文件. 3.进入到这个页面: 说明: ①install or upgra ...

  3. POJ 3280 Cheapest Palindrome(区间dp)

    dp[i][j]表示处理完i到j的花费,如果s[i] == s[j] 则不需要处理,否则处理s[i]或s[j], 对一个字符ch,加上ch或删掉ch对区间转移来说效果是一样的,两者取min. #inc ...

  4. 基于Dockerfile 构建redis5.0.0(包括持久化)及RedisDestopManager 监控

    一 创建Dockerfile [root@zxmrlc docker]# mkdir redis [root@zxmrlc docker]# cd redis && touch Doc ...

  5. php xdebug扩展无法进入断点问题

    Waiting for incoming connection with ide key 看到这句话就恶心 这两天搞php运行环境搞的头大,好在现在终于调通了,可以正常进入断点了 现在记录一下,避免下 ...

  6. SyntaxError: Non-ASCII character ‘\xe5′ in file和在代码中插入中文,python中文注释

    SyntaxError: Non-ASCII character '\xe7' in file 出现这种错误的原因是程序中的编码出问题了,只要在程序的最前面加上 #coding: utf-8 重新保存 ...

  7. 完结篇OO总结

    目录 前言 一.第四单元两次架构设计 二.架构设计及OO方法理解的演进 三.测试理解与实践的演进 四.课程收获 五.改进建议 前言 持续了17周的OO终于走向了尾声,想想寒假的时候连类都不知道是什么, ...

  8. 配置dubbo架构的maven项目

    1. 拆分工程 1)将表现层工程独立出来: e3-manager-web 2)将原来的e3-manager改为如下结构 e3-manager |--e3-manager-dao |--e3-manag ...

  9. kindeditor 上传图片失败问题总结

    1.近段时间一直在处理kindeditor上传图片失败的问题,前期一直以为是前端的问题,利用谷歌控制台,打断点,修改方法,一直都找不到解决方案,直到查看服务器配置,才发现: WEB 1号服务器 /da ...

  10. Dynemic Web Project中使用servlet的 doGet()方法接收来自浏览器客户端发送的add学生信息形成json字符串输出到浏览器并保存到本地磁盘文件

    package com.swift.servlet; import java.io.FileOutputStream;import java.io.IOException;import java.io ...