Python 自动化测试:pytest + Allure 生成精美测试报告

一、环境准备
  1. 安装必要库:
pip install pytest allure-pytest

  1. 安装 Allure 命令行工具:
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

三、运行测试并生成报告
  1. 执行测试并生成原始数据:
pytest --alluredir=./allure-results

  1. 生成 HTML 报告:
allure serve ./allure-results

四、定制化报告(高级用法)
  1. 添加测试步骤装饰器:
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)

  1. 添加严重级别:
@allure.severity(allure.severity_level.CRITICAL)
def test_critical_function():
    assert True

  1. 附加测试数据:
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']]
    }
}

最佳实践建议

  1. 使用 @pytest.fixture 管理测试资源
  2. 结合 allure.dynamic 动态生成用例标题
  3. 定期清理历史报告数据
  4. 使用标签系统分类测试场景
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐