欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python3.x安装HTMLTestRunner和使用

程序员文章站 2022-04-15 21:58:10
笔者:风起怨江南 出处:https://www.cnblogs.com/mengjinxiang 笔者原创,文章欢迎转载,如果喜欢请点赞+关注,感谢支持! 前言:最近一直在其他博客论坛上写Python的相关技术博客->https://blog.csdn.net/JackMengJin,计划还是在博客 ......

笔者:风起怨江南 出处: 笔者原创,文章欢迎转载,如果喜欢请点赞+关注,感谢支持!

 

前言:最近一直在其他博客论坛上写python的相关技术博客->https://blog.csdn.net/jackmengjin,计划还是在博客园上写一些关于安装、排错、爬坑等等一些零散的技术点,这样感觉好一点(轻微强迫症患者= =)。

 

操作:

1.什么是htmltestrunner?

在网上(包括在python官方文库)找不到htmltestrunner相关解释资料。其实htmltestrunner是一个第三方的unittest html报告库,关于unittest在python官方文库上很容易找到:,下面是截取的部分说明:

unittest 单元测试框架是受到 junit 的启发,与其他语言中的主流单元测试框架有着相似的风格。其支持测试自动化,配置共享和关机代码测试。支持将测试样例聚合到测试集中,并将测试与报告框架独立。

为了实现这些,unittest 通过面向对象的方式支持了一些重要的概念。

测试脚手架

test fixture 表示为了开展一项或多项测试所需要进行的准备工作,以及所有相关的清理操作。举个例子,这可能包含创建临时或代理的数据库、目录,再或者启动一个服务器进程。

测试用例

一个测试用例是一个独立的测试单元。它检查输入特定的数据时的响应。 unittest 提供一个基类: testcase ,用于新建测试用例。

测试套件

test suite 是一系列的测试用例,或测试套件,或两者皆有。它用于归档需要一起执行的测试。

测试运行器(test runner)

test runner 是一个用于执行和输出测试结果的组件。这个运行器可能使用图形接口、文本接口,或返回一个特定的值表示运行测试的结果。

unittest 模块提供了一系列创建和运行测试的工具。这一段落演示了这些工具的一小部分,但也足以满足大部分用户的需求。

这是一段简短的代码,来测试三种字符串方法:

import unittest

class teststringmethods(unittest.testcase):

    def test_upper(self):
        self.assertequal('foo'.upper(), 'foo')

    def test_isupper(self):
        self.asserttrue('foo'.isupper())
        self.assertfalse('foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertequal(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertraises(typeerror):
            s.split(2)

if __name__ == '__main__':
    unittest.main()

 

通过以上资料可以看到unittest能够输出txt格式的文本执行报告,但是文本报告太过简陋,是不是想要更加高大上的html报告?

但unittest自己可没有带html报告,我们只能求助于外部的库了——htmltestrunner.py。

2.下载htmltestrunner.py

为什么是下载htmltestrunner.py而不直接是htmltestrunner呢?

揭晓答案前我们先用常规手段下载htmltestrunner:

  • 通过pycharm下载htmltestrunner

python3.x安装HTMLTestRunner和使用

确保使用的是豆瓣源下载后,点击安装:

python3.x安装HTMLTestRunner和使用

果然报错...,为什么会报错呢?

python3.x安装HTMLTestRunner和使用

  • 通过pip下载htmltestrunner

这里我再尝试下使用pip下载:

python3.x安装HTMLTestRunner和使用

结果发现不管怎么尝试,都是不行:)

于是我查了下资料,得到了一个结论:原因其实就是htmltestrunner是python标准库的unittest模块的扩展,无法通过pip安装。

那么我们要怎么使用和下载htmltestrunner呢?

其实解决方法很简单,需要通过手动下载htmltestrunner.py文件,放在python目录lib文件夹下即可:

python3.x安装HTMLTestRunner和使用

由于当前python2.x绝大多数情况下不再使用,这里之将支持python3.x的htmltestrunner.py文件放上来:

"""
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 = '<link rel="stylesheet" href="my_stylesheet.css" type="text/css">'

    # 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 <script> block as cdata.

version in 0.7.1
* back port to python 2.3 (frank horowitz).
* fix missing scroll bars in detail log (podi).
"""

# todo: color stderr
# todo: simplify javascript using ,ore than 1 class in the class attribute?

import datetime
#2.7版本为 import stringio
import io
import sys
import time
import unittest
from xml.sax import saxutils


# ------------------------------------------------------------------------
# the redirectors below are used to capture output during testing. output
# sent to sys.stdout and sys.stderr are automatically captured. however
# in some cases sys.stdout is already cached before htmltestrunner is
# invoked (e.g. calling logging.basicconfig). in order to capture those
# output, use the redirectors for the cached stream.
#
# e.g.
#   >>> logging.basicconfig(stream=htmltestrunner.stdout_redirector)
#   >>>

class outputredirector(object):
    """ wrapper to redirect stdout or stderr """
    def __init__(self, fp):
        self.fp = fp

    def write(self, s):
        self.fp.write(s)

    def writelines(self, lines):
        self.fp.writelines(lines)

    def flush(self):
        self.fp.flush()

stdout_redirector = outputredirector(sys.stdout)
stderr_redirector = outputredirector(sys.stderr)



# ----------------------------------------------------------------------
# template

class template_mixin(object):
    """
    define a html template for report customerization and generation.

    overall structure of an html report

    html
    +------------------------+
    |<html>                  |
    |  <head>                |
    |                        |
    |   stylesheet           |
    |   +----------------+   |
    |   |                |   |
    |   +----------------+   |
    |                        |
    |  </head>               |
    |                        |
    |  <body>                |
    |                        |
    |   heading              |
    |   +----------------+   |
    |   |                |   |
    |   +----------------+   |
    |                        |
    |   report               |
    |   +----------------+   |
    |   |                |   |
    |   +----------------+   |
    |                        |
    |   ending               |
    |   +----------------+   |
    |   |                |   |
    |   +----------------+   |
    |                        |
    |  </body>               |
    |</html>                 |
    +------------------------+
    """

    status = {
    0: 'pass',
    1: 'fail',
    2: 'error',
    }

    default_title = 'unit test report'
    default_description = ''

    # ------------------------------------------------------------------------
    # html template

    html_tmpl = r"""<?xml version="1.0" encoding="utf-8"?>
<!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>%(title)s</title>
    <meta name="generator" content="%(generator)s"/>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    %(stylesheet)s
</head>
<body>
<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();
}
*/
--></script>

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

</body>
</html>
"""
    # variables: (title, generator, stylesheet, heading, report, ending)


    # ------------------------------------------------------------------------
    # stylesheet
    #
    # alternatively use a <link> for external style sheet, e.g.
    #   <link rel="stylesheet" href="$url" type="text/css">

    stylesheet_tmpl = """
<style type="text/css" media="screen">
body        { font-family: verdana, arial, helvetica, sans-serif; font-size: 80%; }
table       { font-size: 100%; }
pre         { }

/* -- heading ---------------------------------------------------------------------- */
h1 {
    font-size: 16pt;
    color: gray;
}
.heading {
    margin-top: 0ex;
    margin-bottom: 1ex;
}

.heading .attribute {
    margin-top: 1ex;
    margin-bottom: 0;
}

.heading .description {
    margin-top: 4ex;
    margin-bottom: 6ex;
}

/* -- css div popup ------------------------------------------------------------------------ */
a.popup_link {
}

a.popup_link:hover {
    color: red;
}

.popup_window {
    display: none;
    position: relative;
    left: 0px;
    top: 0px;
    /*border: solid #627173 1px; */
    padding: 10px;
    background-color: #e6e6d6;
    font-family: "lucida console", "courier new", courier, monospace;
    text-align: left;
    font-size: 8pt;
    width: 500px;
}

}
/* -- report ------------------------------------------------------------------------ */
#show_detail_line {
    margin-top: 3ex;
    margin-bottom: 1ex;
}
#result_table {
    width: 80%;
    border-collapse: collapse;
    border: 1px solid #777;
}
#header_row {
    font-weight: bold;
    color: white;
    background-color: #777;
}
#result_table td {
    border: 1px solid #777;
    padding: 2px;
}
#total_row  { font-weight: bold; }
.passclass  { background-color: #6c6; }
.failclass  { background-color: #c60; }
.errorclass { background-color: #c00; }
.passcase   { color: #6c6; }
.failcase   { color: #c60; font-weight: bold; }
.errorcase  { color: #c00; font-weight: bold; }
.hiddenrow  { display: none; }
.testcase   { margin-left: 2em; }


/* -- ending ---------------------------------------------------------------------- */
#ending {
}

</style>
"""



    # ------------------------------------------------------------------------
    # heading
    #

    heading_tmpl = """<div class='heading'>
<h1>%(title)s</h1>
%(parameters)s
<p class='description'>%(description)s</p>
</div>

""" # variables: (title, parameters, description)

    heading_attribute_tmpl = """<p class='attribute'><strong>%(name)s:</strong> %(value)s</p>
""" # variables: (name, value)



    # ------------------------------------------------------------------------
    # report
    #

    report_tmpl = """
<p id='show_detail_line'>show
<a href='javascript:showcase(0)'>summary</a>
<a href='javascript:showcase(1)'>failed</a>
<a href='javascript:showcase(2)'>all</a>
</p>
<table id='result_table'>
<colgroup>
<col align='left' />
<col align='right' />
<col align='right' />
<col align='right' />
<col align='right' />
<col align='right' />
</colgroup>
<tr id='header_row'>
    <td>test group/test case</td>
    <td>count</td>
    <td>pass</td>
    <td>fail</td>
    <td>error</td>
    <td>view</td>
</tr>
%(test_list)s
<tr id='total_row'>
    <td>total</td>
    <td>%(count)s</td>
    <td>%(pass)s</td>
    <td>%(fail)s</td>
    <td>%(error)s</td>
    <td>&nbsp;</td>
</tr>
</table>
""" # variables: (test_list, count, pass, fail, error)

    report_class_tmpl = r"""
<tr class='%(style)s'>
    <td>%(desc)s</td>
    <td>%(count)s</td>
    <td>%(pass)s</td>
    <td>%(fail)s</td>
    <td>%(error)s</td>
    <td><a href="javascript:showclassdetail('%(cid)s',%(count)s)">detail</a></td>
</tr>
""" # variables: (style, desc, count, pass, fail, error, cid)


    report_test_with_output_tmpl = r"""
<tr id='%(tid)s' class='%(class)s'>
    <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
    <td colspan='5' align='center'>

    <!--css div popup start-->
    <a class="popup_link" onfocus='this.blur();' href="javascript:showtestdetail('div_%(tid)s')" >
        %(status)s</a>

    <div id='div_%(tid)s' class="popup_window">
        <div style='text-align: right; color:red;cursor:pointer'>
        <a onfocus='this.blur();' onclick="document.getelementbyid('div_%(tid)s').style.display = 'none' " >
           [x]</a>
        </div>
        <pre>
        %(script)s
        </pre>
    </div>
    <!--css div popup end-->

    </td>
</tr>
""" # variables: (tid, class, style, desc, status)


    report_test_no_output_tmpl = r"""
<tr id='%(tid)s' class='%(class)s'>
    <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
    <td colspan='5' align='center'>%(status)s</td>
</tr>
""" # variables: (tid, class, style, desc, status)


    report_test_output_tmpl = r"""
%(id)s: %(output)s
""" # variables: (id, output)



    # ------------------------------------------------------------------------
    # ending
    #

    ending_tmpl = """<div id='ending'>&nbsp;</div>"""

# -------------------- the end of the template class -------------------


testresult = unittest.testresult

class _testresult(testresult):
    # note: _testresult is a pure representation of results.
    # it lacks the output and reporting ability compares to unittest._texttestresult.

    def __init__(self, verbosity=1):
        testresult.__init__(self)
        self.stdout0 = none
        self.stderr0 = none
        self.success_count = 0
        self.failure_count = 0
        self.error_count = 0
        self.verbosity = verbosity

        # result is a list of result in 4 tuple
        # (
        #   result code (0: success; 1: fail; 2: error),
        #   testcase object,
        #   test output (byte string),
        #   stack trace,
        # )
        self.result = []


    def starttest(self, test):
        testresult.starttest(self, test)
        # just one buffer for both stdout and stderr
        # 2.7版本为 self.outputbuffer = stringio.stringio()
        self.outputbuffer = io.stringio()
        stdout_redirector.fp = self.outputbuffer
        stderr_redirector.fp = self.outputbuffer
        self.stdout0 = sys.stdout
        self.stderr0 = sys.stderr
        sys.stdout = stdout_redirector
        sys.stderr = stderr_redirector


    def complete_output(self):
        """
        disconnect output redirection and return buffer.
        safe to call multiple times.
        """
        if self.stdout0:
            sys.stdout = self.stdout0
            sys.stderr = self.stderr0
            self.stdout0 = none
            self.stderr0 = none
        return self.outputbuffer.getvalue()


    def stoptest(self, test):
        # usually one of addsuccess, adderror or addfailure would have been called.
        # but there are some path in unittest that would bypass this.
        # we must disconnect stdout in stoptest(), which is guaranteed to be called.
        self.complete_output()


    def addsuccess(self, test):
        self.success_count += 1
        testresult.addsuccess(self, test)
        output = self.complete_output()
        self.result.append((0, test, output, ''))
        if self.verbosity > 1:
            sys.stderr.write('ok ')
            sys.stderr.write(str(test))
            sys.stderr.write('\n')
        else:
            sys.stderr.write('.')

    def adderror(self, test, err):
        self.error_count += 1
        testresult.adderror(self, test, err)
        _, _exc_str = self.errors[-1]
        output = self.complete_output()
        self.result.append((2, test, output, _exc_str))
        if self.verbosity > 1:
            sys.stderr.write('e  ')
            sys.stderr.write(str(test))
            sys.stderr.write('\n')
        else:
            sys.stderr.write('e')

    def addfailure(self, test, err):
        self.failure_count += 1
        testresult.addfailure(self, test, err)
        _, _exc_str = self.failures[-1]
        output = self.complete_output()
        self.result.append((1, test, output, _exc_str))
        if self.verbosity > 1:
            sys.stderr.write('f  ')
            sys.stderr.write(str(test))
            sys.stderr.write('\n')
        else:
            sys.stderr.write('f')


class htmltestrunner(template_mixin):
    """
    """
    def __init__(self, stream=sys.stdout, verbosity=1, title=none, description=none):
        self.stream = stream
        self.verbosity = verbosity
        if title is none:
            self.title = self.default_title
        else:
            self.title = title
        if description is none:
            self.description = self.default_description
        else:
            self.description = description

        self.starttime = datetime.datetime.now()


    def run(self, test):
        "run the given test case or test suite."
        result = _testresult(self.verbosity)
        test(result)
        self.stoptime = datetime.datetime.now()
        self.generatereport(test, result)
        print(sys.stderr,'\ntime elapsed=%s' %(self.stoptime-self.starttime))
        #2.7版本 print >>sys.stderr, '\ntime elapsed: %s' % (self.stoptime-self.starttime)
        return result



    def sortresult(self, result_list):
        # unittest does not seems to run in any particular order.
        # here at least we want to group them together by class.
        rmap = {}
        classes = []
        for n,t,o,e in result_list:
            cls = t.__class__
            # 2.7版本 if not rmap.has_key(cls)
            if not cls in rmap:
                rmap[cls] = []
                classes.append(cls)
            rmap[cls].append((n,t,o,e))
        r = [(cls, rmap[cls]) for cls in classes]
        return r


    def getreportattributes(self, result):
        """
        return report attributes as a list of (name, value).
        override this to add custom attributes.
        """
        starttime = str(self.starttime)[:19]
        duration = str(self.stoptime - self.starttime)
        status = []
        if result.success_count: status.append('pass %s'    % result.success_count)
        if result.failure_count: status.append('failure %s' % result.failure_count)
        if result.error_count:   status.append('error %s'   % result.error_count  )
        if status:
            status = ' '.join(status)
        else:
            status = 'none'
        return [
            ('start time', starttime),
            ('duration', duration),
            ('status', status),
        ]


    def generatereport(self, test, result):
        report_attrs = self.getreportattributes(result)
        generator = 'htmltestrunner %s' % __version__
        stylesheet = self._generate_stylesheet()
        heading = self._generate_heading(report_attrs)
        report = self._generate_report(result)
        ending = self._generate_ending()
        output = self.html_tmpl % dict(
            title = saxutils.escape(self.title),
            generator = generator,
            stylesheet = stylesheet,
            heading = heading,
            report = report,
            ending = ending,
        )
        self.stream.write(output.encode('utf8'))


    def _generate_stylesheet(self):
        return self.stylesheet_tmpl


    def _generate_heading(self, report_attrs):
        a_lines = []
        for name, value in report_attrs:
            line = self.heading_attribute_tmpl % dict(
                    name = saxutils.escape(name),
                    value = saxutils.escape(value),
                )
            a_lines.append(line)
        heading = self.heading_tmpl % dict(
            title = saxutils.escape(self.title),
            parameters = ''.join(a_lines),
            description = saxutils.escape(self.description),
        )
        return heading


    def _generate_report(self, result):
        rows = []
        sortedresult = self.sortresult(result.result)
        for cid, (cls, cls_results) in enumerate(sortedresult):
            # subtotal for a class
            np = nf = ne = 0
            for n,t,o,e in cls_results:
                if n == 0: np += 1
                elif n == 1: nf += 1
                else: ne += 1

            # format class description
            if cls.__module__ == "__main__":
                name = cls.__name__
            else:
                name = "%s.%s" % (cls.__module__, cls.__name__)
            doc = cls.__doc__ and cls.__doc__.split("\n")[0] or ""
            desc = doc and '%s: %s' % (name, doc) or name

            row = self.report_class_tmpl % dict(
                style = ne > 0 and 'errorclass' or nf > 0 and 'failclass' or 'passclass',
                desc = desc,
                count = np+nf+ne,
                pass = np,
                fail = nf,
                error = ne,
                cid = 'c%s' % (cid+1),
            )
            rows.append(row)

            for tid, (n,t,o,e) in enumerate(cls_results):
                self._generate_report_test(rows, cid, tid, n, t, o, e)

        report = self.report_tmpl % dict(
            test_list = ''.join(rows),
            count = str(result.success_count+result.failure_count+result.error_count),
            pass = str(result.success_count),
            fail = str(result.failure_count),
            error = str(result.error_count),
        )
        return report


    def _generate_report_test(self, rows, cid, tid, n, t, o, e):
        # e.g. 'pt1.1', 'ft1.1', etc
        has_output = bool(o or e)
        tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid+1,tid+1)
        name = t.id().split('.')[-1]
        doc = t.shortdescription() or ""
        desc = doc and ('%s: %s' % (name, doc)) or name
        tmpl = has_output and self.report_test_with_output_tmpl or self.report_test_no_output_tmpl

        # o and e should be byte string because they are collected from stdout and stderr?
        if isinstance(o,str):
            uo = e
            # todo: some problem with 'string_escape': it escape \n and mess up formating
            # uo = unicode(o.encode('string_escape'))
            # 2.7版本uo = o.decode('latin-1')
        else:
            uo = o
        if isinstance(e,str):
            ue = e
            # todo: some problem with 'string_escape': it escape \n and mess up formating
            # ue = unicode(e.encode('string_escape'))
            # 2.7 版本 ue = e.decode('latin-1')

        else:
            ue = e

        script = self.report_test_output_tmpl % dict(
            id = tid,
            output = saxutils.escape(uo+ue),
        )

        row = tmpl % dict(
            tid = tid,
            class = (n == 0 and 'hiddenrow' or 'none'),
            style = n == 2 and 'errorcase' or (n == 1 and 'failcase' or 'none'),
            desc = desc,
            script = script,
            status = self.status[n],
        )
        rows.append(row)
        if not has_output:
            return

    def _generate_ending(self):
        return self.ending_tmpl


##############################################################################
# facilities for running tests from the command line
##############################################################################

# note: reuse unittest.testprogram to launch test. in the future we may
# build our own launcher to support more specific command line
# parameters like test title, css, etc.
class testprogram(unittest.testprogram):
    """
    a variation of the unittest.testprogram. please refer to the base
    class for command line parameters.
    """
    def runtests(self):
        # pick htmltestrunner as the default test runner.
        # base class's testrunner parameter is not useful because it means
        # we have to instantiate htmltestrunner before we know self.verbosity.
        if self.testrunner is none:
            self.testrunner = htmltestrunner(verbosity=self.verbosity)
        unittest.testprogram.runtests(self)

main = testprogram

##############################################################################
# executing this module from the command line
##############################################################################

if __name__ == "__main__":
    main(module=none)

至于两者文件具体有什么差异,有兴趣的童鞋可以自行搜索,本文不再展开细说。

3.如何使用htmltestrunner?

首先先确定可以使用htmltestrunner:

python3.x安装HTMLTestRunner和使用

没报错?那继续,打开pycharm,把下面这块代码复制粘贴进去:

import unittest
import htmltestrunner
class testadd(unittest.testcase):
    def setup(self):
        pass
    def test_add1(self):
        self.assertequal(2 + 3 + 10,15)
    def test_add2(self):
        self.assertequal(10 + 150,160)
    def test_add3(self):
        #一处出错,查看测试结果
        self.assertequal(2 * 5 * 7, 40)
    def teardown(self):
        pass
def suite():
    suitetest=unittest.testsuite()
    suitetest.addtest(testadd("test_add1"))
    suitetest.addtest(testadd("test_add2"))
    suitetest.addtest(testadd("test_add3"))
    return suitetest
if __name__=="__main__":
   # 存放路径在e盘目录下
   filepath='e:\\pyresult.html'
   fp=open(filepath,'wb')
   #定义测试报告的标题与描述
   runner = htmltestrunner.htmltestrunner(stream=fp,title=u'我是风起怨江南的测试报告标题',description=u'我是风起怨江南的测试报告描述')
   runner.run(suite())
   fp.close()

运行,查看结果:

g:\helloworld\python\pycharm\jackmeng\scripts\python.exe g:/helloworld/python/pycharm/jackmeng/htmltestrunner_demo.py
<_io.textiowrapper name='<stderr>' mode='w' encoding='utf-8'> 
time elapsed=0:00:00.000948
..f

python3.x安装HTMLTestRunner和使用

那么e盘下到底有没有生成html测试报告文件呢?

答案自然是生成了:

python3.x安装HTMLTestRunner和使用

点开看看测试报告:

 

python3.x安装HTMLTestRunner和使用

测试结果自然不言而喻:完美!


以上便是《python3.x安装htmltestrunner和使用》的所有内容,关于《风起怨江南》在博客园在里,我更多会写一下程序安装啊、排错啊、甚至一些小程序等等,未来一定会有更多精彩的博文,所以赶紧点赞关注收藏一波吧!

当然,如果想获得更多免费的学习资料请加我的个人微信公众号——风起怨江南,最后还是感谢大家关注和支持!