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