高颜值测试报告- XTestRunner

Modern style test report based on unittest framework.

基于unittest框架现代风格测试报告。

特点
  • 漂亮测试报告让你更愿意编写测试。
  • 支持单元Web UIAPI 各种类型的测试。
  • 支持Selenium运行失败/错误自动截图。
  • 支持失败重跑。
  • 支持标签黑、白名单。
  • 支持发邮件功能。
  • 支持多语言enzh-CN 等。
  • 支持HTML/XML不同格式的报告。

安装

  • pip安装

    pip install XTestRunner

使用文档

单元测试

XTestRunner基本用法,用于生成 HTML测试报告

测试用例

复制代码
# test_unit.py
import unittest
from XTestRunner import HTMLTestRunner
 
 
class TestDemo(unittest.TestCase):
    """测试用例说明"""
    
    def test_success(self):
        """执行成功"""
        self.assertEqual(2 + 3, 5)
    
    @unittest.skip("skip case")
    def test_skip(self):
        """跳过用例"""
        pass
    
    def test_fail(self):
        """失败用例"""
        self.assertEqual(5, 6)
    
    def test_error(self):
        """错误用例"""
        self.assertEqual(a, 6)
 
if __name__ == '__main__':
    suit = unittest.TestSuite()
    suit.addTests([
        TestDemo("test_success"),
        TestDemo("test_skip"),
        TestDemo("test_fail"),
        TestDemo("test_error")
    ])
    
    with(open('./result.html', 'wb')) as fp:
        runner = HTMLTestRunner(
            stream=fp,
            title='<project name>test report',
            description='describe: ... ',
            language='en',
        )
        runner.run(
            testlist=suit,
            rerun=2,
            save_last_run=False
        )

HTMLTestRunner类说明

stream: 指定报告的路径。

title: 报告的标题。

description: 报告的描述, 支持str、list两种类型。

language: 支持中文zh-CN, 默认en。

run()方法说明

testlist: 运行的测试套件。

rerun: 重跑次数。

save_last_run: 是否保存最后一个重跑结果。

运行测试

复制代码
> python test_unit.py
Selenium Web测试

针对Selenium Web自动化测试提供了失败/错误 自动截图功能。

注意

1.安装selenium

复制代码
> pip install selenium

2.注意:驱动必须定义为 driver, 否则无法生成截图。

测试用例

复制代码
import unittest
from XTestRunner import HTMLTestRunner
from selenium import webdriver
from selenium.webdriver.common.by import By
 
 
class SeTest(unittest.TestCase):
 
    @classmethod
    def setUpClass(cls) -> None:
        cls.driver = webdriver.Chrome()
        cls.base_url = "https://cn.bing.com/"
 
    @classmethod
    def tearDownClass(cls) -> None:
        cls.driver.quit()
 
    def test_success(self):
        """测试bing搜索:XTestRunner """
        self.driver.get(self.base_url)
        search = self.driver.find_element(By.ID, "sb_form_q")
        search.send_keys("XTestRunner")
        search.submit()
 
    def test_error(self):
        """测试bing搜索,定位失败 """
        self.driver.get(self.base_url)
        self.driver.find_element(By.ID, "sb_form_qxxx").send_keys("python")
 
    def test_fail(self):
        """测试bing搜索,断言失败 """
        self.driver.get(self.base_url)
        self.driver.find_element(By.ID, "sb_form_q").send_keys("unittest")
        self.assertEqual(self.driver.title, "unittest")
 
    def test_screenshots(self):
        """测试截图"""
        self.driver.get(self.base_url)
        # 元素截图
        elem = self.driver.find_element(By.ID, "sb_form_q")
        self.images.append(elem.screenshot_as_base64)
        # 竖屏截图
        self.images.append(self.driver.get_screenshot_as_base64())
        # 最大化截图
        self.driver.maximize_window()
        self.images.append(self.driver.get_screenshot_as_base64())
 
 
if __name__ == '__main__':
    report = "./selenium_result.html"
    with(open(report, 'wb')) as fp:
         unittest.main(testRunner=HTMLTestRunner(
            stream=fp,
            title='Selenium自动化测试报告',
            description=['类型:selenium', '操作系统:Windows', '浏览器:Chrome', '执行人:虫师']
        ))

测试报告

一个用例支持多张截图,不同的截图自动轮播,而且优化之后,不管是页面元素截图,横向、纵向图片都可以很好的展示。

API 接口测试

XTestRunner 当然也支持HTTP接口测试了。

  • 安装requests

    pip install requests

测试用例

复制代码
import requests
import unittest
from XTestRunner import HTMLTestRunner
 
class YouTest(unittest.TestCase):
 
    def test_get(self):
        """测试get接口 """
        r = requests.get("https://httpbin.org/get", params={"key":"value"})
        print(r.json())
 
    def test_post(self):
        """测试post接口 """
        r = requests.post("https://httpbin.org/post", data={"key":"value"})
        print(r.json())
 
    def test_put(self):
        """测试put接口 """
        r = requests.put("https://httpbin.org/put", data={"key":"value"})
        print(r.json())
 
    def test_delete(self):
        """测试delete接口 """
        r = requests.delete("https://httpbin.org/delete", data={"key":"value"})
        print(r.json())
 
 
if __name__ == '__main__':
    report = "./reports/api_result.html"
    with(open(report, 'wb')) as fp:
        unittest.main(testRunner=HTMLTestRunner(
            stream=fp,
            title='Seldom自动化测试报告',
            description=['类型:API', '地址:https://httpbin.org/', '执行人:虫师']
        ))

测试报告

通过print() 可以讲接口信息打印到报告中展示。

邮件功能

XTestRunner 支持邮件功能。

复制代码
import unittest
from XTestRunner import HTMLTestRunner
from XTestRunner import SMTP
...
 
if __name__ == '__main__':
    report = "./reports/send_email_result.html"
    with(open(report, 'wb')) as fp:
        unittest.main(testRunner=HTMLTestRunner(
            stream=fp,
            title='测试发送邮件',
            description=['类型:测试发送邮件', '执行人:虫师']
        ))
    # 发邮件功能
    # 使用126邮箱发送时password应为授权码而非用户密码,须在邮箱客户端设置开启授权码
    # 使用gmail邮箱发送时password为用户密码,须在gmail客户端开启安全性较低的应用的访问权限
    smtp = SMTP(user="sender@qq.com", password="xxx", host="smtp.qq.com")
    smtp.sender(to="fnngj@126.com", subject="XTestRunner测试邮件", attachments=report)

邮件展示

支持黑白名单

可以通过黑白名单选择要执行(或跳过)的用例。

支持白黑名单

白名单:whitelist="base" 只有使用@label("base")装饰的用例执行

黑名单:blacklist="slow" 只有使用@label("slow")装饰的用例不被执行

测试用例

复制代码
import unittest
from XTestRunner import label
from XTestRunner import HTMLTestRunner
 
 
class LabelTest(unittest.TestCase):
 
    @label("base")
    def test_label_base(self):
        self.assertEqual(1+1, 2)
 
    @label("slow")
    def test_label_slow(self):
        self.assertEqual(1, 2)
 
    def test_no_label(self):
        self.assertEqual(2+3, 5)
 
 
if __name__ == '__main__':
    report = './reports/label_result.html'
    with(open(report, 'wb')) as fp:
        unittest.main(testRunner=HTMLTestRunner(
            stream=fp,
            title='<project name>test report',
            description='describe: ... ',
            whitelist=["base"],  # 设置白名单
            # blacklist=["slow"],  # 设置黑名单
        ))

注意:

白名单和黑名单不要同时用,以免产生冲突。

XML格式报告

虽然,HTML报告的颜值很高,但有时需要提取测试数据,比如保存到数据库,这个时候从HTML报告中提取数据是非常麻烦的,所以,XTestRunner 支持XML格式的报告。

复制代码
import unittest
from XTestRunner import XMLTestRunner
 
#...
 
if __name__ == '__main__':
    # 定义报告
    report = "./xml_result.xml"
    with(open(report, 'wb')) as fp:
        unittest.main(testRunner=XMLTestRunner(output=fp))

报告展示

总结:

感谢每一个认真阅读我文章的人!!!

作为一位过来人也是希望大家少走一些弯路,如果你不想再体验一次学习时找不到资料,没人解答问题,坚持几天便放弃的感受的话,在这里我给大家分享一些自动化测试的学习资源,希望能给你前进的路上带来帮助。

文档获取方式:

复制代码
加入我的软件测试交流群:632880530免费获取~(同行大佬一起学术交流,每晚都有大佬直播分享技术知识点)

这份文档,对于想从事【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴我走过了最艰难的路程,希望也能帮助到你!

以上均可以分享,只需要你搜索vx公众号:程序员雨果,即可免费领取

相关推荐
神仙别闹3 小时前
基于 C++ 实现(控制台)学生成绩管理系统
开发语言·c++
Y幽谷客3 小时前
Python加载本地大模型(Qwen3.5 8B)
python·大模型
伞伞悦读3 小时前
【第36期】Python 目录与路径详解:pathlib、文件遍历、创建、复制、移动和删除风险
开发语言·python
线上放牧人4 小时前
Windows删除图标缓存
windows·python·pyqt
qq_5470261794 小时前
Python 变量和简单数据类型
python
智搜广告5 小时前
智搜广告:科技行业AI回答优化公司如何破局
大数据·python·elasticsearch·geo
IpdataCloud6 小时前
AI智能体调用工具怎么核验来源IP?归属地、网络类型与代理风险识别(含Python代码)
数据库·python·tcp/ip
2601_966949656 小时前
只拿到股票代码还不够:量化程序到底还需要哪些标的信息?——从数据建模开始理解股票元数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
蒸鱼Yuzheng6 小时前
Python 游戏测试开发怎么准备:日志解析、接口校验、并发与可维护性
自动化测试·python·测试开发·面试题·游戏测试
m0_734571766 小时前
深入理解5g <十八>传输块tbsize的计算
开发语言·5g