51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 1002|回复: 0
打印 上一主题 下一主题

[原创] 如何简化Pytest生成HTML测试报告?

[复制链接]
  • TA的每日心情
    无聊
    10 小时前
  • 签到天数: 978 天

    连续签到: 3 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2022-9-9 14:45:15 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    背景
      最近开发有关业务场景的功能时,涉及的API接口比较多,需要自己模拟多个业务场景的自动化测试(暂时不涉及性能测试),并且在每次测试完后能够生成一份测试报告。
      考虑到日常使用Python自带的UnitTest,所以先从官方文档下手,了解到有相关的TestTextRunner:https://docs.python.org/zh-cn/3/ ... test.TextTestRunner
      自带的TextTestRunner每次能把测试结果输出到流中的测试运行器,可以简单根据verbosity调整每次测试结果输出的信息,但是都太基础了,如果我想在测试过程中打印一些请求参数或者docstring,看了一下UnitTest内置的方法,实现过程可能会比较繁琐。
      然后在网上找了一下轮子工具、html-testrunner、beautifulreport,这些工具生成的网页css、js都是使用公网的CDN,由于内网环境,不适合。
      后面看了一些技术文章很多都是使用Pytest,之前有相关Pytest的基础使用经验,大概了解一下,决定根据Pytest+pytest-html满足当前测试场景。
      模块安装
    pip install pytest
    pip install pytest-html

    方案设计
      pytest.ini
      首先定义pytest.ini(pytest的基础配置文件,和测试文件在同一目录,使用pytest命令时会先读取该文件):
    1. [pytest]
    2. log_cli = True
    3. log_cli_level = INFO
    复制代码
    备注:开启日志消息打印,设置日志记录捕获的最低消息级别为INFO。
      conftest.py
      设置conftest.py(没有自己创建,同样是和测试文件同个目录下,用于pytest-html生成测试报告的配置文件):
    1. # --*-- coding: utf-8 --*--
    2. from datetime import datetime
    3. from py.xml import html
    4. import pytest
    5. def pytest_html_report_title(report):
    6.     report.title = "测试报告"
    7. def pytest_html_results_table_header(cells):
    8.     cells.insert(2, html.th("Description"))
    9.     cells.insert(1, html.th("Time", class_="sortable time", col="time"))
    10.     cells.pop()
    11. def pytest_html_results_table_row(report, cells):
    12.     cells.insert(2, html.td(report.description))
    13. def pytest_html_results_table_row(report, cells):
    14.     cells.insert(2, html.td(report.description))
    15.     cells.insert(1, html.td(datetime.utcnow(), class_="col-time"))
    16.     cells.pop()
    17. @pytest.hookimpl(hookwrapper=True)
    18. def pytest_runtest_makereport(item, call):
    19.     outcome = yield
    20.     report = outcome.get_result()
    21.     report.description = str(item.function.__doc__)
    复制代码
    通过设置钩子函数分别修改测试报告的列,添加描述列、测试用例耗时时间列、删除链接列,我这里是直接参考官方文档中给出的示例:https://pytest-html.readthedocs. ... lf-contained-report,有兴趣的可以研究一下。
      测试用例
      根据Pytest的官方文档,Pytest同样是支持UnitTest的功能,所以可以在原有的基础上直接运行Pytest:
    1. # -*- coding: utf-8 -*-
    2. # @Author: linshukai
    3. # @Desc: pytestc测试用例
    4. # @Date: 20220827
    5. import unittest
    6. import pytest
    7. import logging
    8. import requests
    9. class TestString(unittest.TestCase):
    10.     def test_upper_method(self):
    11.         """
    12.         测试字符串大写
    13.         """
    14.         self.assertEqual("linshukai".upper(), "LINSHUKAI")
    15.         logging.info("测试linshukai")
    16.     def test_lower_method(self):
    17.         """
    18.         测试字符串小写
    19.         """
    20.         self.assertEqual( "ZhangSan".lower(), "zhangsan")
    21.         logging.info("测试ZhangSan")
    22.     def test_count_method(self):
    23.         """
    24.         测试字符串长度统计
    25.         """
    26.         self.assertEqual( len("zhangsan"), 8)
    27.         logging.info("测试Zhangsan")
    28. class TestString2(unittest.TestCase):
    29.     def test_get_html(self):
    30.         """
    31.         测试请求网页状态码是否正常
    32.         """
    33.         response = requests.get("http://www.baidu.com")
    34.         self.assertEqual(response.status_code, 500)
    35. if __name__ == "__main__":
    36.     pytest.main(["pytest_example.py", "--html=report.html", "--self-contained-html"])
    复制代码
    备注:简单写了几个测试用例,需要特别说明的是可以通过pytest.main()方法,直接在Python代码中调用Pytest,所以我每次只需要执行这个脚本就行,当然也可以选择在命令行界面通过Pytest命令调用指定测试文件执行指定测试用例。
      另外一个地方需要注意的是--self-contained-html这个参数主要是针对pytest-html模块,由于默认pytest-html中生成测试报告的网页和CSS文件都是分开来存储的,如果想直接将css文件合并到html中,这样分享测试报告的时候也更加方便,所以只需要加入这个参数即可--self-contained-html。
      预期效果

    预期会出现的问题
    Pytest中使用requests,抛出错误,但不影响测试结果,抛出的异常:
    Windows fatal exception: code 1073807366

    解决方式,降低Pytest为4.6.11版本后,异常就不会抛出,但是pytest-html需要6.0版本上的Pytest,由于不影响测试结果,更加完善的解决方法后续再研究。






    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

    x
    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /2 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-7-3 19:23 , Processed in 0.066412 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表