pytest+allure生成测试报告入门

演示如何使用 pytest + allure 生成支持中文的测试报告。

1. 安装依赖

pip install pytest
pip install allure-pytest

2. 运行测试并生成 Allure 原始结果

pytest

运行后会在 allure-results 目录下生成原始测试结果。

3. 安装 Allure 命令行工具,此工具需要java的支持,所以先安装java

  • 推荐方式:前往 Allure 官方下载页面 下载并安装 Allure。
  • Windows 用户可直接下载 zip 包,解压后将 bin 目录添加到环境变量 PATH。

4. 生成并打开 Allure 报告

allure generate allure-results -o allure-report --clean
allure open allure-report

5. 目录结构

├── pytest.ini
├── tests/
│   └── test_sample.py

5.1 pytest.ini

[pytest]
addopts = --alluredir=allure-results
testpaths = tests
python_files = test_*.py
log_cli = true
log_cli_level = INFO
# 避免中文输出乱码
console_output_style = classic

5.2 test_sample.py

import pytest
import allure

@allure.severity(allure.severity_level.CRITICAL)  # 严重等级
@allure.tag("核心功能", "支付")                  # 标签
@allure.link("https://example.com/api-docs", name="接口文档")  # 文档链接
@allure.issue("BUG-1234", "支付超时问题")          # 关联的问题单
@allure.testcase("TC-001", "支付流程测试用例")      # 关联的测试用例
@allure.epic("示例项目")                         # 系统级别分类
@allure.feature("计算功能")                      # 功能模块分类
@allure.story("加法场景")                        # 具体用户故事
@allure.title("加法用例 - 正常情况")               # 测试用例标题
@allure.description("""
### 描述内容-md
""")
def test_add():
    """加法测试:1 + 1 = 2"""
    with allure.step("步骤1:计算 1 + 1"):
        result = 1 + 1
    with allure.step("步骤2:断言结果等于2"):
        assert result == 2, "加法结果应为2"

@allure.epic("示例项目")
@allure.feature("计算功能")
@allure.story("除法场景")
@allure.title("除法用例 - 异常情况")
def test_divide_zero():
    """除法测试:1 / 0 应抛出异常"""
    with allure.step("步骤1:尝试计算 1 / 0"):
        with pytest.raises(ZeroDivisionError):
            _ = 1 / 0
    with allure.step("步骤2:断言抛出 ZeroDivisionError"):
        assert True

5.3

核心装饰器
‌  @allure.description()‌:添加测试用例描述 ‌
  ‌@allure.title()‌:指定测试用例标题 ‌
  ‌@allure.step()‌:记录测试步骤 ‌
  ‌@allure.attach()‌:添加附件 ‌
分类与标记
‌  @allure.epic()‌:表示大型功能模块 ‌
  ‌@allure.feature()‌:表示功能模块 ‌
  ‌@allure.story()‌:表示具体场景 ‌
  ‌@allure.issue()‌:关联问题跟踪系统 ‌
  ‌@allure.testcase()‌:关联测试用例管理工具 ‌
  ‌@allure.link()‌:添加外部链接 ‌
  ‌@allure.severity()‌:标记测试用例级别 ‌
其他功能
‌  @pytest.mark.parametrize‌:参数化测试 ‌
  ‌@pytest.mark.skip()‌:跳过测试 ‌
  ‌@pytest.mark.xfail()‌:预期失败测试 ‌

6. 参考截图

image

posted @ 2025-06-28 14:38  朝阳1  阅读(93)  评论(0)    收藏  举报