美文网首页自动化
基于nose-html-report定制测试报告

基于nose-html-report定制测试报告

作者: 佛系小懒 | 来源:发表于2020-02-06 19:41 被阅读0次

    环境准备

    参考文章

    pip3.5 install nose-html-report 

    安装目录文件:

    ├── __init__.py

    ├── __pycache__

    │   └── __init__.cpython-35.pyc

    └── templates

    ├── report2.jinja2

    └── report.html

    主要修改 __init__.py文件及测试报告模板文件report2.jinja2

    jinja2模板有自己的语法,参见 链接

    对于jinja中的语法:

    if elif else endif  条件语法 

    {% if not test.failed %}

    {% set test_status="Pass" %}

    {% elif test.failed and test.type == 'skipped' %}

    {% set test_status="Skip" %}

    {% elif test.failed and test.type != 'skipped' %}

    {% set test_status="Fail" %}

    {%- else -%}

    {% set test_status="Error" %}

    {%- endif %}

    for语法

    {% for test in group.tests %}

    {%- endfor -%}

    测试报告定制的实现主要包括如下类

    class OutputRedirector(object):  # 输出重定向类,包含一个文件对象fp,主要包括如下方法

    def write(self, s):   

    def writelines(self, lines):

    def flush(self):

    def readall(self):

    class Group(object):  # 测试用例组,主要包括如下两个对象

    self.stats = {'errors': 0, 'failures': 0, 'passes': 0, 'skipped': 0} # 用例组的结果状态统计

    self.tests = [] # 用例组中具体测试用例统计

    class HtmlReport(Plugin):  # 测试报告插件

    主要包括startTest、begin、complete_test_output、 complete_global_output、report、addSuccess、addError、addFailure等方法,具体实现如下:

    def __init__(self, verbosity=1): #全局变量、报告统计数据初始化

        super(HtmlReport, self).__init__()

        self.global_stdout0 = None

        self.global_stderr0 = None

        self.test_stdout0 = None

        self.test_stderr0 = None

        self.testOutputBuffer = StringIO.StringIO()

        self.globalOutputBuffer = StringIO.StringIO()

        self.stdout_redirector = OutputRedirector(sys.stdout)

        self.stderr_redirector = OutputRedirector(sys.stderr)

        self.test_stdout_redirector = OutputRedirector(sys.stdout)

        self.test_stderr_redirector = OutputRedirector(sys.stderr)

        self.verbosity = verbosity

    def startTest(self, test):   # 重定向输出初始化

        # just one buffer for both stdout and stderr

        self.testOutputBuffer = StringIO.StringIO()

        self.test_stdout_redirector.fp = self.testOutputBuffer

        self.test_stderr_redirector.fp = self.testOutputBuffer

        self.test_stdout0 = sys.stdout

        self.test_stderr0 = sys.stderr

        sys.stdout = self.test_stdout_redirector

        sys.stderr = self.test_stderr_redirector

        self.test_start_time = datetime.now()

    def complete_test_output(self, err_msg='', traceback=''): 

    # 测试完成后的断开重定向链接同时返回缓存数据

    """

    Disconnect output redirection and return buffer.

    Safe to call multiple times.

    """

    if self.test_stdout0:

        sys.stdout = self.test_stdout0

        sys.stderr = self.test_stderr0

        self.test_stdout0 = None

        self.test_stderr0 = None

    self.globalOutputBuffer.write(self.testOutputBuffer.getvalue())

    self.globalOutputBuffer.write(err_msg)

    self.globalOutputBuffer.write(traceback)

    return self.testOutputBuffer.getvalue()

    def begin(self): # 测试用例执行

        # just one buffer for both stdout and stderr

        # self.outputBuffer = StringIO.StringIO()

        self.stdout_redirector.fp = self.globalOutputBuffer

        self.stderr_redirector.fp = self.globalOutputBuffer

        self.global_stdout0 = sys.stdout

        self.global_stderr0 = sys.stderr

        sys.stdout = self.stdout_redirector

        sys.stderr = self.stderr_redirector

    def complete_global_output(self):  # 所有测试用例执行后的操作

        """

        Disconnect output redirection and return buffer.

        Safe to call multiple times.

        """

        if self.global_stdout0:

            sys.stdout = self.global_stdout0

            sys.stderr = self.global_stderr0

            self.global_stdout0 = None

            self.global_stderr0 = None

        return self.globalOutputBuffer.getvalue()

    def options(self, parser, env): 通过nosetests运行测试用例时携带的命令选项  

    def configure(self, options, config):  通过命令配置进行实际配置加载(加载指定报告模板)

    def report(self, stream): # 基于模板,对模板中的变量进行赋值,写测试报告   通过report_data,以group为单位,对测试结果结果进行传递,group中包含stats及tests对象,分别记录该测试组中测试运行状态及具体用例信息

        """Writes an Xunit-formatted XML file

        The file includes a report of test errors and failures.

        """

        self.stats['total'] = sum(self.stats.values())

        for group in self.report_data.values():

            group.stats['total'] = sum(group.stats.values())

        self.report_file.write(self.jinja.get_template(os.path.basename(self.report_template_filename)).render(

            report=self.report_data,

            stats=self.stats,

            start_time = str(self.test_start_time)[:19],

            rawoutput=self._format_output(self.complete_global_output()),

            duration_time = self.test_duration_time - datetime.resolution

        ))

        self.report_file.close()

        if self.config.verbosity > 1:

            stream.writeln("-" * 70)

            stream.writeln("HTML: %s" % self.report_file.name)

    def addSuccess(self, test):   # 测试成功 返回的状态信息及用例详情

        name = id_split(test.id())

        group = self.report_data[name[0]]

        self.stats['passes'] += 1

        group.stats['passes'] += 1

        group.tests.append({

            'name': name[-1],

            'failed': False,

            'output': self._format_output(self.complete_test_output()),

            'shortDescription': test.shortDescription(),

            'time': str(datetime.now() - self.test_start_time),

        })

    def addError(self, test, err, capt=None):    # 测试失败 返回的状态信息及用例详情、错误信息等

        """Add error output to Xunit report.

        """

        exc_type, exc_val, tb = err

        tb = ''.join(traceback.format_exception(

            exc_type,

            exc_val if isinstance(exc_val, exc_type) else exc_type(exc_val),

            tb

        ))

        name = id_split(test.id())

        group = self.report_data[name[0]]

        if issubclass(err[0], SkipTest):

            type = 'skipped'

            self.stats['skipped'] += 1

            group.stats['skipped'] += 1

        else:

            type = 'error'

            self.stats['errors'] += 1

            group.stats['errors'] += 1

        group.tests.append({

            'name': name[-1],

            'failed': True,

            'type': type,

            'errtype': nice_classname(err[0]),

            'message': exc_message(err),

            'tb': self._format_output(tb),

            'output': self._format_output(self.complete_test_output(exc_message(err), tb)),

            'shortDescription': test.shortDescription(),

            'time': str(datetime.now() - self.test_start_time),

        })

    def addFailure(self, test, err, capt=None):    # 测试失败 返回的状态信息及用例详情、失败详情

        """Add failure output to Xunit report.

        """

        exc_type, exc_val, tb = err

        tb = ''.join(traceback.format_exception(

            exc_type,

            exc_val if isinstance(exc_val, exc_type) else exc_type(exc_val),

            tb

        ))

        name = id_split(test.id())

        group = self.report_data[name[0]]

        self.stats['failures'] += 1

        group.stats['failures'] += 1

        group.tests.append({

            'name': name[-1],

            'failed': True,

            'errtype': nice_classname(err[0]),

            'message': exc_message(err),

            'tb': self._format_output(tb),

            'output': self._format_output(self.complete_test_output(exc_message(err), tb)),

            'shortDescription': test.shortDescription(),

            'time': str(datetime.now() - self.test_start_time),

        })

    def _format_output(self, o): #指定编码

        if isinstance(o, str):

            # return o.decode('latin-1')

            return o.decode('UTF-8')

        else:

            return o

    相关文章

      网友评论

        本文标题:基于nose-html-report定制测试报告

        本文链接:https://www.haomeiwen.com/subject/txwuxhtx.html