一、为什么要用 Allure 注解?
在接口自动化中,单纯的"跑通用例"价值有限;有结构、有可读性的测试报告才能真正帮你:
- 向测试经理汇报结果
- 辅助定位失败用例
- 体现你的测试思路
- 在面试中展示专业度
Allure 的装饰器,本质上就是把你的测试设计可视化。
二、Allure 最常用的 5 个装饰器(高频必掌握)
✅ 1️⃣ @allure.feature() ------ 一级模块(骨架)
作用:定义测试的一级分类,相当于"系统模块"。
什么时候用?
👉 每个测试类都建议写
python
@allure.feature("登录模块")
class TestLogin:
pass
报告结构示例:
📁 登录模块
📁 订单模块
📁 支付模块
📁 OpenAPI
规范建议(企业风格)
feature 一般按系统功能划分,比如:
python
@allure.feature("登录模块")
@allure.feature("用户模块")
@allure.feature("订单模块")
@allure.feature("OpenAPI")
面试可说:
"我们基于 Allure feature 进行模块化分层管理测试用例。"
✅ 2️⃣ @allure.story() ------ 二级场景
作用:细化 feature 下的测试场景。
推荐写法:
python
@allure.story("登录成功")
def test_login_success():
pass
@allure.story("登录失败 - 密码错误")
def test_login_wrong_pwd():
pass
报告层级:
登录模块
├── 登录成功
├── 登录失败 - 密码错误
└── 登录失败 - 账号不存在
最佳实践(很重要):
| story | 对应用例 |
|---|---|
| 登录成功 | 正向用例 |
| 登录失败 - 参数异常 | 反向用例 |
| 登录失败 - 账号问题 | 边界用例 |
👉 story = 你的测试思路的可视化。
✅ 3️⃣ @allure.title() ------ 用例可读标题(非常重要)
如果你不用 title:
python
def test_login_001():
pass
Allure 显示:
test_login_001
老板看不懂,也不专业。
改成:
python
@allure.title("登录成功:正确账号密码")
def test_login_success():
pass
Allure 显示:
登录成功:正确账号密码
👉 可读性提升 10 倍。
✅ 4️⃣ allure.dynamic.title() ------ 参数化必备
如果你这样写参数化:
python
@pytest.mark.parametrize("account,pwd,expect", [
("user1", "123456", "success"),
("user1", "111111", "password error"),
])
def test_login_param(account, pwd, expect):
pass
Allure 会显示:
test_login_param[0]
test_login_param[1]
很糟糕。
👉 推荐写法:
python
@pytest.mark.parametrize("account,pwd,expect", [
("user1", "123456", "success"),
("user1", "111111", "password error"),
])
def test_login_param(account, pwd, expect):
allure.dynamic.title(f"登录测试:{account} -> {expect}")
报告效果:
登录测试:user1 -> success
登录测试:user1 -> password error
📌 记住规则:
| 场景 | 用什么 |
|---|---|
| 普通单条用例 | @allure.title() |
| 参数化多条用例 | allure.dynamic.title()(强烈推荐) |
✅ 5️⃣ @allure.step() ------ 关键步骤(接口测试加分项)
在接口自动化中,这个非常重要。
python
@allure.step("发送登录请求")
def test_login_success():
response = request_util.post("/public/login", json=payload)
allure.step("校验返回码为 200")
assert response.status_code == 200
allure.step("校验返回体包含 token")
assert "token" in response.json()
Allure 展示:
✔ 发送登录请求
✔ 校验返回码为 200
✔ 校验返回体包含 token
👉 相当于把你的测试逻辑写进报告。
三、最小可用规范(如果只能选 3 个)
👉 必用三件套:
@allure.feature✅@allure.story✅@allure.title✅
👉 进阶加分:
- 参数化 →
allure.dynamic.title - 复杂接口 →
@allure.step
四、企业级标准模板(你可以直接抄)
python
@allure.feature("登录模块")
class TestLogin:
@allure.story("登录成功")
@allure.title("登录成功:正确账号密码")
@allure.severity(allure.severity_level.CRITICAL)
def test_login_success(self, request_util, test_data):
user = test_data['users']['test_user']
with allure.step("发送登录请求"):
resp = request_util.post("/public/login", json={
"account": user["account"],
"password": user["password"]
})
with allure.step("校验状态码"):
assert resp.status_code == 200
with allure.step("校验返回 token"):
assert "token" in resp.json()
这套写法非常像大厂风格,你以后简历、项目、面试都能用得上。
五、总结
feature= 模块骨架story= 测试场景title= 可读性门面dynamic.title= 参数化利器step= 接口测试的灵魂
👉 好的测试,不只是"跑通",更要"看懂"。