如何才能让用例自动运行完之后,生成一张直观可看易懂的测试报告呢?

小编使用的是unittest的一个扩展HTMLTestRunner

  • 环境准备

使用之前,我们需要下载HTMLTestRunner.py文件

点击HTMLTestRunner后进入的是一个写满代码的网页,小编推荐操作:右键 --> 另存为,文件名称千万不要改

python3使用上述HTMLTestRunner可能会报错,可以替换如下文件

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

HTMLTestRunner

  • 使用

接下来,小编将以登录网易邮箱为例,生成一份最基础的测试报告。小伙伴们copy走代码验证时一定记得修改账号密码哦。

目录结构如下:

将HTMLTestRunner.py文件存放到package包下,将test_login.py存放到testcase目录下,用于编写测试用例,建立testreport包,用于存放测试报告,在email目录下建立run_test.py,用于执行测试

HTMLTestRunner的使用方法在代码注释中介绍和解释

【test_login.py】

  1. from selenium import webdriver
  2. import unittest,time
  3.  
  4. class Login(unittest.TestCase):
  5. def setUp(self):
  6. #打开百度,搜索“163网易邮箱”,登录
  7. driver=webdriver.Firefox()
  8. driver.implicitly_wait(5)
  9. self.driver=driver
  10. driver.get("https://www.baidu.com/")
  11.  
  12. driver.find_element_by_id("kw").send_keys("163邮箱登录")
  13. driver.find_element_by_id("su").click()
  14.  
  15. name = driver.find_element_by_id("op_email3_username")
  16. password = driver.find_element_by_class_name("op_email3_password")
  17. login = driver.find_element_by_css_selector(".c-btn")
  18.  
  19. #如下操作可以使setUp中的变量被其他模块调用
  20. self.name=name
  21. self.password=password
  22. self.login=login
  23.  
  24. def tearDown(self):
  25. self.driver.quit()
  26.  
  27. def switch_window(self):
  28. #切换窗口
  29. for handle in self.driver.window_handles:
  30. self.driver.switch_to.window(handle)
  31. #j增加等待时间,可以提高测试用例执行的健壮性
  32. time.sleep(2)
  33. time.sleep(3)
  34.  
  35. #成功登录
  36. def test_right_login(self):
  37. #账号密码自行填写
  38. self.name.send_keys("xxx")
  39. self.password.send_keys("xxx")
  40. self.login.click()
  41.  
  42. self.switch_window()
  43. #t通过新窗口的title验证用例是否通过
  44. self.assertEqual(self.driver.title,"网易邮箱6.0版","登录失败")
  45.  
  46. #密码为空登录
  47. def test_null_psw_login(self):
  48. self.name.send_keys("xxx")
  49. time.sleep(3)
  50. self.login.click()
  51. self.switch_window()
  52. # t通过新窗口的title验证用例是否通过
  53. self.assertEqual(self.driver.title,"网易帐号中心 > 用户验证","未跳转至用户验证界面")

【run_test.py】

  1. #导入HTMLTestRunner的包
  2. from package import HTMLTestRunner
  3. #导入test_login的包,执行测试用例时需使用
  4. from testcase.test_login import *
  5.  
  6. #定义要执行的测试用例的路径
  7. test_dir = './testcase'
  8. #定义要执行的测试用例的路径和名称格式
  9. #test_*.py的意思是,./testcase路径下文件名称格式为test_*.py的文件,*为任意匹配,路径下有多少的test_*.py格式的文件,就依次执行几个
  10. discover = unittest.defaultTestLoader.discover(test_dir, pattern='test_*.py')
  11. #定义测试报告的名称和存储位置
  12. filename = './testreport/loginReport.html'
  13.  
  14. #开始执行
  15. if __name__ == '__main__':
  16.  
  17. suit=unittest.TestSuite()
  18. suit.addTest(Login("test_right_login"))
  19. suit.addTest(Login("test_null_psw_login"))
  20.  
  21. #以wb(可写的二进制文件)形式,打开文件,若文件不存在,则先执行创建,再执行打开
  22. fp = open(filename, 'wb')
  23. #调用HTMLTestRunner生成报告
  24. runner = HTMLTestRunner.HTMLTestRunner(
  25. # 指定测试报告的文件
  26. stream=fp,
  27. # 测试报告的标题
  28. title=u"登录网易邮箱测试报告",
  29. # 测试报告的副标题
  30. description=u'用例执行情况(win7 64位)'
  31. )
  32. #执行用例
  33. runner.run(discover)
  • 报告展示

Python自动化测试框架——生成测试报告的更多相关文章

  1. 【转】推荐4个不错的Python自动化测试框架

    之前,开发团队接手一个项目并开始开发时,除了项目模块的实际开发之外,他们不得不为这个项目构建一个自动化测试框架.一个测试框架应该具有最佳的测试用例.假设(assumptions).脚本和技术来运行每一 ...

  2. Selenium WebDriver + python 自动化测试框架

    目标 组内任何人都可以进行自动化测试用例的编写 完全分离测试用例和自动化测试代码,就像写手工测试用例一下,编写excel格式的测试用例,包括步骤.检查点,然后执行自动化工程,即可执行功能自动化测试用例 ...

  3. python自动化测试框架unittest

    对于刚学习python自动化测试的小伙伴来说,unittest是一个非常适合的框架: 通过unittest,可以管理测试用例的执行,自动生成简单的自动化测试报告: 首先我们尝试编写编写一个最简单的un ...

  4. (原创)Python 自动化测试框架详解

    自己折腾了一个python的自动化测试框架,梳理了一下流程,简单分享一下. 项目背景 B/S架构,进行用户界面的自动化测试 工具选择 python开发的自动化测试框架,足够灵活,可以随时根据需求进行变 ...

  5. python自动化测试框架

    一.环境准备 1.python开发环境, python3.7 2.setuptools基础工具包 3.pip安装包管理工具 4.selenium自动化测试工具  chrom驱动下载地址: http:/ ...

  6. Python+自动化测试框架的设计编写

    Python之一个简单的自动化测试框架:https://baijiahao.baidu.com/s?id=1578211870226409536&wfr=spider&for=pc h ...

  7. 解除你学习Python自动化测试框架的所有疑惑,开启学习直通车

    学习框架第一步 前言 很多同学学完Python基础后出现迷茫......有同感的小伙伴,点赞关注........ 学习完Python还要学习什么? 什么是自动化测试框架? 如何搭建自动化测试框架? 甚 ...

  8. Python自动化 unittest生成测试报告(HTMLTestRunner)03

    批量执行完用例后,生成的测试报告是文本形式的,不够直观,为了更好的展示测试报告,最好是生成HTML格式的. unittest里面是不能生成html格式报告的,需要导入一个第三方的模块:HTMLTest ...

  9. python + pytest + allure生成测试报告

    pytest结合allure生成测试报告 环境搭建 要安装java环境,版本要是jdk1.8的,配置好java环境变量,不然输入allure命令会报错,JAVA_HOME环境,自行配置 安装allur ...

随机推荐

  1. android 在一个应用中启动另一个应用

    在程序开发过程当中,常遇到需要启动另一个应用程序的情况,比如在点击软件的一个按钮可以打开地图软件. 如果既有包名又有主类的名字,那就好 办了, 直接像下面就行: [html]  Intent inte ...

  2. python 通过setup.py安装和卸载python软件包

    安装:sudo python setup.py install 卸载:sudo python setup.py install --record log sudo cat log | sudo xar ...

  3. noip 2018 Day2 T1 旅行

    暴力删边,暴力枚举 #include <bits/stdc++.h> using namespace std; #define MAXM 5010 inline int read() { ...

  4. 跟我一起玩Win32开发(11):使用控件——先来耍一下按钮

    用户通过控件与应用程序交互,在吹牛之前,先介绍一个工具,这是官方的工具,使用它,你可以预览常用控件的外观.样式,以及对控进行操作时接收和发送哪些消息.下载地址如下: http://www.micros ...

  5. 模板——扩展欧几里得算法(求ax+by=gcd的解)

    Bryce1010模板 /**** *扩展欧几里得算法 *返回d=gcd(a,b),和对应等式ax+by=d中的x,y */ long long extend_gcd(long long a,long ...

  6. 洛谷 P1072 Hankson 的趣味题 || 打质数表的分解质因数

    方法就是枚举,根据b0和b1可以大大减小枚举范围,方法类似这个http://blog.csdn.net/hehe_54321/article/details/76021615 将b0和b1都分解质因数 ...

  7. 排序二叉树 HDOJ 5444 Elven Postman

    题目传送门 题意:给出线性排列的树,第一个数字是根节点,后面的数如果当前点小或相等往左走,否则往右走,查询一些点走的路径 分析:题意略晦涩,其实就是排序二叉树!1<<1000 普通数组开不 ...

  8. 18.3.2从Class上获取信息(构造器)

    获取构造器信息 package d18_3_1; import java.lang.reflect.Constructor; import java.util.Arrays; /** * 获取构造器的 ...

  9. dos 下 批量替换 只支持txt

    首先必须存成 bat 格式,其次识别不了word 1.bat ##替换12 成12*3 @echo offsetlocal enabledelayedexpansionfor /F "tok ...

  10. vue 模拟后台数据(加载本地json文件)调试

    首先创建一个本地json文件,放在项目中如下 { "runRedLight":{ "CurrentPage": 1, "TotalPages" ...