高颜值测试报告- 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公众号:程序员雨果,即可免费领取

相关推荐
学测绘的小杨16 小时前
CompassFusion:一个从 GNSS 到 GNSS/INS 组合导航的独立工程包
python
zzzzzz3101 天前
当产品经理说这个很简单:我用Python自动化处理奇葩需求的实战指南
python·pycharm·产品经理
雪隐1 天前
个人电脑玩AI-06让5060 Ti给你打工——不光能画画,Qwen3-TTS还能学人说话,连我老板都信了!
人工智能·后端·python
兵慌码乱1 天前
面向桌面端的资产管理系统分层架构设计与核心模块实现
python·系统架构·sqlite·pyqt5·数据库设计·桌面应用开发·mvc架构
hboot1 天前
AI工程师第三课 - 机器学习基础
python·scikit-learn·kaggle
顾林海2 天前
Agent入门阶段-编程基础-Python:流程控制
python·agent·ai编程
呱呱复呱呱2 天前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
曲幽2 天前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
荣码2 天前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
兵慌码乱2 天前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理