Python 自动化测试:pytest+Allure 生成精美测试报告
·
Python 自动化测试:pytest + Allure 生成精美测试报告
一、环境准备
- 安装必要库:
pip install pytest allure-pytest
- 安装 Allure 命令行工具:
- 下载地址
- 配置环境变量(例:Mac/Linux):
export PATH=$PATH:/path/to/allure/bin
二、创建测试用例
test_sample.py 示例:
import pytest
def test_addition():
assert 1 + 1 == 2
def test_subtraction():
assert 5 - 3 == 2
@pytest.mark.parametrize("a,b,expected", [(2, 3, 5), (10, 20, 30)])
def test_parametrized(a, b, expected):
assert a + b == expected
三、运行测试并生成报告
- 执行测试并生成原始数据:
pytest --alluredir=./allure-results
- 生成 HTML 报告:
allure serve ./allure-results
四、定制化报告(高级用法)
- 添加测试步骤装饰器:
import allure
@allure.step("验证加法运算:{0} + {1} = {2}")
def verify_addition(a, b, result):
assert a + b == result
def test_custom_step():
verify_addition(3, 5, 8)
- 添加严重级别:
@allure.severity(allure.severity_level.CRITICAL)
def test_critical_function():
assert True
- 附加测试数据:
def test_with_attachment():
allure.attach("测试数据", "name,age\nJohn,30\nAlice,25", allure.attachment_type.CSV)
五、报告效果说明
生成的 Allure 报告包含:
- 交互式仪表盘(通过率、趋势图)
- 测试套件树形结构
- 用例执行时长分析
- 参数化测试数据展示
- 截图/附件查看功能
- 历史趋势对比
六、持续集成集成
在 CI 脚本中添加:
# Jenkins 示例
stage('Generate Report') {
steps {
sh 'allure generate allure-results -o allure-report'
allure includeProperties: false,
jdk: '',
results: [[path: 'allure-results']]
}
}
最佳实践建议:
- 使用
@pytest.fixture管理测试资源- 结合
allure.dynamic动态生成用例标题- 定期清理历史报告数据
- 使用标签系统分类测试场景
更多推荐
所有评论(0)