大概是三年前我自己设计了 XTestRunner 测试报告,主要是针对unittest 单元测试框架而设计。

记得当时主要是被一个网友安利说 UnitTestReport 好看,这我就非常不服气了,你可以质疑我的技术能力,但是不能质疑我的审美,于是重新设计了XTestRunner并发布了 1.0 版本。至今为止,XTestRunner仍然是 unittest 最漂亮的第三方测试报告。

然而, 网友墙裂建议针对 pytest 单元测试框架支持一波,我当时专心搞seldom框架,才没心情支持。现在,终于乘上了了 XTestRunner 的 pytest 版本。

为什么要选择 pytest-xhtml?

  • Allure报告:需要额外安装Allure命令行工具,启动服务过于重量级,看个报告还要每台电脑都安装Allure命令。
  • pytest-html:界面太丑,这个看脸的世界,丑就是原罪。

pytest-xhtml特点

  • pytest-xhtml 基于 XTestRunner 的设计风格,将现代Web UI设计理念引入测试报告领域,实现了功能与美学的完美平衡。 - 这句是AI生成的。

  • pytest-xhtml 基于 pytest-html 魔改UI, 功能使用上与 pytest-html 保持一致,除了命名上有差异。使用 pytest-xhtml的时候,请卸载 pytest-html

安装方式

  • pip命令安装
# 安装
pip install pytest-xhtml #下面的示例会用到
pip install pytest-req
pip install selenium

使用方式

  • 核心使用 - 与 pytest-html 完全一致
pytest --html=report.html

简单的单元测试

首先,配置 conftest.py文件,配置只是为了多显示两列内容,不配置也行。

import pytest
from datetime import datetime, timezone def pytest_xhtml_results_table_header(cells):
cells.insert(2, "<th>Description</th>")
cells.insert(1, '<th class="sortable time" data-column-type="time">Time</th>') def pytest_xhtml_results_table_row(report, cells):
cells.insert(2, f"<td>{report.description}</td>")
cells.insert(1, f'<td class="col-time">{datetime.now(timezone.utc)}</td>') @pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if hasattr(report, 'nodeid') and '::' in report.nodeid:
report.description = str(item.function.__doc__ or "No description")

然后,编写测试用例 test_sample.py

import pytest

# 简单的测试用例
def test_pass():
assert 1 + 1 == 2 def test_fail():
assert 1 + 1 == 3 def test_skip():
pytest.skip("这个测试被跳过") @pytest.mark.xfail
def test_xfail():
assert 1 + 1 == 3 @pytest.mark.xfail(reason="预期失败,但实际会通过")
def test_xpass():
"""这是一个 Unexpected passes 用例 - 预期失败但实际通过"""
assert 1 + 1 == 2 def test_error():
"""这是一个 Error 用例 - 测试执行时发生异常"""
# 故意引发一个异常来模拟错误
raise ValueError("模拟测试执行错误") @pytest.fixture
def error_fixture():
# 在fixture中引发异常,也会导致测试错误
raise RuntimeError("fixture中的错误") def test_error_with_fixture(error_fixture):
"""使用会出错的fixture的测试用例"""
assert True if __name__ == '__main__':
pytest.main(["-v", "--html=report.html", "test_sample.py"])

最后,运行测试用例。

pytest -v --html=report.html test_sample.py

HTTP接口测试

首先,配置 conftest.py文件,主要是为了显示接口调用日志信息。

import pytest
from datetime import datetime, timezone
from datetime import datetime, timezone
from pytest_req.log import log_cfg @pytest.fixture(scope="session", autouse=True)
def setup_log():
"""
setup log
"""
log_format = "<green>{time:YYYY-MM-DD HH:mm:ss}</> |<level> {level} | {message}</level>"
log_cfg.set_level(format=log_format) def pytest_xhtml_results_table_header(cells):
cells.insert(2, "<th>Description</th>")
cells.insert(1, '<th class="sortable time" data-column-type="time">Time</th>') def pytest_xhtml_results_table_row(report, cells):
cells.insert(2, f"<td>{report.description}</td>")
cells.insert(1, f'<td class="col-time">{datetime.now(timezone.utc)}</td>') @pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if hasattr(report, 'nodeid') and '::' in report.nodeid:
report.description = str(item.function.__doc__ or "No description")

然后,编写测试用例test_req.py


def test_post_method(post):
"""
test post request
"""
s = post('https://httpbin.org/post', data={'key': 'value'})
assert s.status_code == 200 def test_get_method(get):
"""
test get request
"""
payload = {'key1': 'value1', 'key2': 'value2'}
s = get("https://httpbin.org/get", params=payload)
assert s.status_code == 200 ...

最后,运行测试用例。

pytest -v --html=report.html test_sample.py

Selenium UI测试

首先,配置 conftest.py文件, 主要是为了实现截图展示。

import pytest
from datetime import datetime, timezone
from selenium import webdriver @pytest.fixture
def driver():
"""提供 WebDriver 实例用于测试"""
driver = webdriver.Edge()
yield driver
driver.quit() def pytest_xhtml_results_table_header(cells):
cells.insert(2, "<th>Description</th>")
cells.insert(1, '<th class="sortable time" data-column-type="time">Time</th>') def pytest_xhtml_results_table_row(report, cells):
cells.insert(2, f"<td>{report.description}</td>")
cells.insert(1, f'<td class="col-time">{datetime.now(timezone.utc)}</td>') @pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result() # 只为测试用例添加描述,不处理收集阶段的报告
if hasattr(report, 'nodeid') and '::' in report.nodeid:
report.description = str(item.function.__doc__ or "No description") # 当测试失败时添加截图
if report.when == "call" and report.failed:
# 获取当前测试的 driver fixture
driver = item.funcargs.get('driver')
if driver:
# 使用 base64 编码获取截图
screenshot_base64 = driver.get_screenshot_as_base64() # 将截图添加到报告额外信息中 - 使用 pytest-xhtml 期望的格式
if not hasattr(report, 'extras'):
report.extras = [] # 使用 pytest-xhtml 支持的格式
report.extras.append({
'name': 'Screenshot',
'format_type': 'image', # 必需字段
'content': screenshot_base64, # base64 内容
'mime_type': 'image/png', # 必需字段
'extension': 'png' # 必需字段
})

然后,编写测试用例test_req.py

from time import sleep
from selenium.webdriver.common.by import By def test_bing_search_fail(driver):
"""测试 Bing 搜索功能"""
# 访问 Bing 搜索页面
driver.get("https://www.bing.com")
sleep(2)
assert driver.title == "pytest-xhtml - 搜索11" ...

最后,运行测试用例。

pytest -v --html=report.html test_selenium.py

最后说明

pytest-xhtml 调样式前后花费了一周(晚上)时间,相比较 XTestRunner 缺失一些统计图表。后面再慢慢增加吧!功能上可以完全替代 pytest-html 了,快去体验一下吧!

高颜值测试报告 pytest-xhtml的更多相关文章

  1. 高颜值测试报告- XTestRunner

    Modern style test report based on unittest framework. 基于unittest框架现代风格测试报告. 特点 漂亮测试报告让你更愿意编写测试. 支持单元 ...

  2. Python3+selenium+BaiduAI识别并下载花瓣网高颜值妹子图片

    一.说明 1.1 背景说明 上周在“Python3使用百度人脸识别接口识别高颜值妹子图片”中自己说到在成功判断颜值后,下截图片并不是什么难点. 直观感觉上确实如此,你判断的这个url适不适合下载,适合 ...

  3. Python3+BaiduAI识别高颜值妹子图片

    一.在百度云平台创建应用 为什么要到百度云平台创建应用,首先来说是为了获取获取access_token时需要的API Key和Secret Key 至于为什么需要API Key和Secret Key才 ...

  4. 刷抖音太累,教你用Python把高颜值的小姐姐都爬下来慢慢看

    前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: 星安果.AirPython 目 标 场 景 相信大家平时刷抖音短视频 ...

  5. ES6基础与解构赋值(高颜值弹框小案例!)

    let只作用在当前块级作用域内使用let或者const声明的变量,不能再被重新声明let不存在`变量提升` console.log(dad); var dad = '我是爸爸!';//预定义undef ...

  6. 这么高颜值的Kubernetes管理工具Lens,难道还不能C位出道吗

    1 前言 欢迎访问南瓜慢说 www.pkslow.com获取更多精彩文章! Docker & Kubernetes相关文章:容器技术 一直使用官方的Kubernetes Dashboard来管 ...

  7. IDEA高颜值之最吸引小姐姐插件集合!让你成为人群中最靓的那个崽!

    经常有小伙伴会来找TJ君,可能觉得TJ君比较靠谱,要TJ君帮忙介绍女朋友.TJ君一直觉得程序猿是天底下最可爱的一个群体,只不过有时候不善于表达自己的优秀,所以TJ君今天准备介绍几款酷炫实用的IDEA插 ...

  8. 高颜值,类似Fliqlo的翻页时钟-BdTab新标签页插件组件

    起因: 很多用户在使用BdTab插件时,反馈说希望添加一个时钟的功能, 而BdTab又是组件模块化的插件,于是在空余时间就用html+js+css写了一款高颜值的分页时钟 源码如下: 需要其他网页组件 ...

  9. pytest+allure高端测试报告

    1.下载jdk,搭建jdk环境 下载JDK  http://www.oracle.com/technetwork/java/javase/downloads/index.html 2.下载allure ...

  10. 一次Dapper高并发测试报告记录. 结果....

    一直听说dapper的数据处理能力很强. 我也一直很喜欢. 不过最近的一次压力测试却出乎我的意料.... 好久没写东西,感觉自己都不知道怎么表达自己的意思了.   另外 这次的测试也是自己才开始的 . ...

随机推荐

  1. Tcode:PFAL说明

    Short text HR: ALE Distribution of HR Master Data Description. Scenario 1: Distribution of HR Master ...

  2. DotTrace系列:1. 理解四大经典的诊断类型(上)

    一:背景 1. 讲故事 在所有与 .NET相关的JetBrains产品中,我觉得 DotTrace 是最值得深入学习和研究的一款,个人觉得它的优点如下: 跨平台诊断 (Windows,Linux,Ma ...

  3. Java源码分析系列笔记-1.JMM模型之先谈硬件

    目录 1. 冯诺依曼体系结构 2. 高速缓存 2.1. 工作原理 2.2. 存储器层次结构 2.3. 局部性原理 3. 缓存一致性/可见性问题 3.1. 如何解决 3.1.1. 总线加锁 3.1.2. ...

  4. UFT 关于excel及datatable的处理

    1. excel 2. datatable

  5. 用termius或者cmd等都能够连接上服务器,但是用vscode连接不上???

    最近实验室的服务器进行重装更新了,开始使用wsl,现在直接装Linux系统的Ubantu.服务器的ip.端口.个人名字都没有变.也就相当于之前在termius等远程连接的软件上都能够连上. 我习惯用v ...

  6. 视频音频对嘴--Wav2Lip

    之前介绍了将图片加音频进行对嘴处理,生成新的视频:基础版: https://www.cnblogs.com/cj8988/p/18952604 进阶版(加表情) :https://www.cnblog ...

  7. Jquery 选择html 标签获取值

    https://zhidao.baidu.com/question/299628455.html 这个问题包含两个方面:jquery选择器(即针对你指定的那个input元素)和获取内容(即获得输入的值 ...

  8. 华为机试题 Redraiment

    简介 动态规划问题. 对于贪心无法解决的问题, 要第一时间想到动态规划问题的解法. 但是对于动态规划问题, 你要想的是使用dp[] 还是 dp[][] 其中每个dp元素表示的意义 这题的dp[i] 表 ...

  9. 使用类似于raspberry的方式登录ubuntu20.04--vnc

    简介 我看过最好的教程是 https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-vnc-on-ub ...

  10. 最好的Transformer讲解:The Illustrated Transformer + The Annotated Transformer

    The Illustrated Transformer https://jalammar.github.io/illustrated-transformer/ The Annotated Transf ...