HTMLTestRunner.py

書天發表於2021-01-05

"""
A TestRunner for use with the Python unit testing framework. It
generates a HTML report to show the result at a glance.

The simplest way to use this is to invoke its main method. E.g.

import unittest
import HTMLTestRunner

... define your tests ...

if name == 'main':
HTMLTestRunner.main()

For more customization options, instantiates a HTMLTestRunner object.
HTMLTestRunner is a counterpart to unittest's TextTestRunner. E.g.

# output to a file
fp = file('my_report.html', 'wb')
runner = HTMLTestRunner.HTMLTestRunner(
stream=fp,
title='My unit test',
description='This demonstrates the report output by HTMLTestRunner.'
)

# Use an external stylesheet.
# See the Template_mixin class for more customizable options
runner.STYLESHEET_TMPL = ''

# run the test
runner.run(my_test_suite)


Copyright (c) 2004-2007, Wai Yip Tung
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • Neither the name Wai Yip Tung nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

URL: http://tungwaiyip.info/software/HTMLTestRunner.html

author = "Wai Yip Tung"
version = "0.8.2"

"""
Change History

Version 0.8.2

  • Show output inline instead of popup window (Viorel Lupu).

Version in 0.8.1

  • Validated XHTML (Wolfgang Borgert).
  • Added description of test classes and test cases.

Version in 0.8.0

  • Define Template_mixin class for customization.
  • Workaround a IE 6 bug that it does not treat <div> block as CDATA. <p>Version in 0.7.1</p> <ul> <li>Back port to Python 2.3 (Frank Horowitz).</li> <li>Fix missing scroll bars in detail log (Podi). """</li> </ul> <h2 id="TODO: color stderr">TODO: color stderr</h2> <h2 id="TODO: simplify javascript using ,ore than 1 class in the class attribute?">TODO: simplify javascript using ,ore than 1 class in the class attribute?</h2> <p>import datetime<br> import StringIO<br> import sys<br> import time<br> import unittest<br> from xml.sax import saxutils</p> <h2 id="------------------------------------------------------------------------">------------------------------------------------------------------------</h2> <h2 id="The redirectors below are used to capture output during testing. Output">The redirectors below are used to capture output during testing. Output</h2> <h2 id="sent to sys.stdout and sys.stderr are automatically captured. However">sent to sys.stdout and sys.stderr are automatically captured. However</h2> <h2 id="in some cases sys.stdout is already cached before HTMLTestRunner is">in some cases sys.stdout is already cached before HTMLTestRunner is</h2> <h2 id="invoked (e.g. calling logging.basicConfig). In order to capture those">invoked (e.g. calling logging.basicConfig). In order to capture those</h2> <h2 id="output, use the redirectors for the cached stream.">output, use the redirectors for the cached stream.</h2> <p>#</p> <h2 id="e.g.">e.g.</h2> <h2 id="&gt;&gt;&gt; logging.basicConfig(stream=HTMLTestRunner.stdout_redirector)">&gt;&gt;&gt; logging.basicConfig(stream=HTMLTestRunner.stdout_redirector)</h2> <h2 id="&gt;&gt;&gt;">&gt;&gt;&gt;</h2> <p>class OutputRedirector(object):<br> """ Wrapper to redirect stdout or stderr """<br> def <strong>init</strong>(self, fp):<br> self.fp = fp</p> <p>def write(self, s):<br> self.fp.write(s)</p> <p>def writelines(self, lines):<br> self.fp.writelines(lines)</p> <p>def flush(self):<br> self.fp.flush()</p> <p>stdout_redirector = OutputRedirector(sys.stdout)<br> stderr_redirector = OutputRedirector(sys.stderr)</p> <h2 id="----------------------------------------------------------------------">----------------------------------------------------------------------</h2> <h2 id="Template">Template</h2> <p>class Template_mixin(object):<br> """<br> Define a HTML template for report customerization and generation.</p> <p>Overall structure of an HTML report</p> <p>HTML<br> +------------------------+<br> | |<br> | </p> |<br> | |<br> | STYLESHEET |<br> | +----------------+ |<br> | | | |<br> | +----------------+ |<br> | |<br> | |<br> | |<br> | |<br> | |<br> | HEADING |<br> | +----------------+ |<br> | | | |<br> | +----------------+ |<br> | |<br> | REPORT |<br> | +----------------+ |<br> | | | |<br> | +----------------+ |<br> | |<br> | ENDING |<br> | +----------------+ |<br> | | | |<br> | +----------------+ |<br> | |<br> | |<br> | |<br> +------------------------+<br> """ <p>STATUS = {<br> 0: 'pass',<br> 1: 'fail',<br> 2: 'error',<br> }</p> <p>DEFAULT_TITLE = 'Unit Test Report'<br> DEFAULT_DESCRIPTION = ''</p> <p># ------------------------------------------------------------------------<br> # HTML Template</p> <p>HTML_TMPL = r"""&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br> &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" rel="nofollow" target="_blank">http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd</a>"&gt;<br> <br> </p> <br> <title>%(title)s</title> <br> <meta name="generator" content="%(generator)s"> <br> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <br> %(stylesheet)s<br> <br> <script language="javascript" type="text/javascript"><!-- output_list = Array(); /* level - 0:Summary; 1:Failed; 2:All */ function showCase(level) { trs = document.getElementsByTagName("tr"); for (var i = 0; i < trs.length; i++) { tr = trs[i]; id = tr.id; if (id.substr(0,2) == 'ft') { if (level < 1) { tr.className = 'hiddenRow'; } else { tr.className = ''; } } if (id.substr(0,2) == 'pt') { if (level > 1) { tr.className = ''; } else { tr.className = 'hiddenRow'; } } } } function showClassDetail(cid, count) { var id_list = Array(count); var toHide = 1; for (var i = 0; i < count; i++) { tid0 = 't' + cid.substr(1) + '.' + (i+1); tid = 'f' + tid0; tr = document.getElementById(tid); if (!tr) { tid = 'p' + tid0; tr = document.getElementById(tid); } id_list[i] = tid; if (tr.className) { toHide = 0; } } for (var i = 0; i < count; i++) { tid = id_list[i]; if (toHide) { document.getElementById('div_'+tid).style.display = 'none' document.getElementById(tid).className = 'hiddenRow'; } else { document.getElementById(tid).className = ''; } } } function showTestDetail(div_id){ var details_div = document.getElementById(div_id) var displayState = details_div.style.display // alert(displayState) if (displayState != 'block' ) { displayState = 'block' details_div.style.display = 'block' } else { details_div.style.display = 'none' } } function html_escape(s) { s = s.replace(/&/g,'&amp;'); s = s.replace(/</g,'&lt;'); s = s.replace(/>/g,'&gt;'); return s; } /* obsoleted by detail in <div> function showOutput(id, name) { var w = window.open("", //url name, "resizable,scrollbars,status,width=800,height=450"); d = w.document; d.write("<pre>"); d.write(html_escape(output_list[id])); d.write("\n"); d.write("<a href='javascript:window.close()'>close</a>\n"); d.write("</pre>\n"); d.close(); } */ --></div>

    %(heading)s
    %(report)s
    %(ending)s