专栏进度:08 / 10 (自动化实战专题)
Allure 是一款支持多语言、多框架的开源报告工具。它的强大之处不仅在于颜值,更在于它能记录测试步骤、附件、历史趋势、严重级别以及自动截屏。
一、 环境准备
安装 Python 插件:pip install allure-pytest
安装 Allure 命令行工具:
Windows: scoop install allure (或下载 zip 包配置环境变量)
Mac: brew install allure
二、 基础实战:生成你的第一份 Allure 报告
在 Pytest 运行命令中加入参数:
Bash
bash
# 1. 运行并收集数据(存入 temp 目录)
pytest --alluredir=./temp
# 2. 生成并打开报告
allure serve ./temp
三、 深度定制:把报告做成"交互式文档"
原生报告很空洞。我们可以通过 Allure 提供的装饰器,在代码中注入"灵魂"。
- 业务逻辑结构化
Python
python
import allure
import pytest
@allure.epic("我的电商系统")
@allure.feature("购物车模块")
class TestCart:
@allure.story("添加商品到购物车")
@allure.severity(allure.severity_level.CRITICAL) # 标记严重程度
@allure.description("测试用户在登录状态下,将单件商品成功加入购物车")
def test_add_to_cart(self):
with allure.step("第一步:搜索商品"):
print("搜索商品逻辑")
with allure.step("第二步:点击加入购物车"):
# 模拟添加操作
allure.attach("商品ID: 1001", name="参数详情")
with allure.step("第三步:验证购物车数量"):
assert 1 == 1
- 失败自动截图(UI 自动化的神技)
在 conftest.py 中利用钩子函数,实现只要报错就自动把 Playwright 的截图塞进报告。
Python
python
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
if rep.when == "call" and rep.failed:
# 获取 playwright 页面对象(假设你封装在 fixture 里)
page = item.funcargs.get("page")
if page:
allure.attach(page.screenshot(), name="失败截图", attachment_type=allure.attachment_type.PNG)
四、 Allure 的三大硬核价值
历史趋势图:报告能显示最近 20 次测试的通过率趋势。如果曲线陡降,说明代码质量在滑坡。
分类统计:它可以把 Bug 按照"产品缺陷"、"环境问题"、"脚本错误"进行分类。
参数回溯:配合数据驱动(YAML),Allure 能清晰展示每一组测试数据对应的执行结果。
五、 避坑指南:报告管理的"坑"
历史记录丢失:allure serve 默认是临时的。在 CI/CD 环境中,需要把 allure-results/history 目录持久化,否则看不了趋势图。
报告体积过大:如果每个用例都塞几个视频和几十张图,报告加载会极慢。对策:仅在 failed 时附加图片,passed 时只留日志。
中文乱码:在某些老旧 Jenkins 环境中,Allure 的中文标签可能乱码。对策:确保系统环境变量 JAVA_TOOL_OPTIONS 设置为 -Dfile.encoding=UTF8。