Python + Pytest + Allure 自动化测试报告教程

Python + Pytest + Allure 自动化测试报告教程

从零开始搭建完整的测试报告生成系统,包含详细步骤和代码示例。


环境准备
  1. 安装Python 3.8+

    bash 复制代码
    # 验证安装
    python --version
  2. 安装依赖库

    bash 复制代码
    pip install pytest allure-pytest
  3. 安装Allure命令行工具

    • 下载Allure

    • 镜像下载Allure

    • 解压并配置环境变量(以Mac/Linux为例):

      bash 复制代码
      # 解压
      unzip allure-commandline-*.zip  
      # 添加到PATH
      export PATH=$PATH:/path/to/allure/bin

项目结构

创建基础目录:

plaintext 复制代码
project/  
├── tests/  
│   ├── test_login.py   # 测试用例  
│   └── conftest.py     # 共享配置  
├── reports/            # 报告输出目录  
└── pytest.ini          # 配置文件

编写测试用例
  1. 创建基础测试(tests/test_login.py)
python 复制代码
import pytest

def test_login_success():
    assert "admin" == "admin", "用户名验证成功"

def test_login_fail():
    assert "user" != "admin", "用户名验证失败"

@pytest.mark.parametrize("input", ["a", "b", "c"])
def test_parametrized(input):
    assert len(input) == 1
  1. 添加钩子函数(tests/conftest.py)
python 复制代码
import pytest

@pytest.fixture(scope="session")
def setup():
    print("全局初始化")
    yield
    print("全局清理")
  1. 配置Pytest(pytest.ini)
ini 复制代码
[pytest]
addopts = -v --alluredir=./reports/allure_raw
testpaths = tests

运行测试并生成报告
  1. 执行测试
bash 复制代码
pytest  # 自动生成原始数据到reports/allure_raw
  1. 生成HTML报告
bash 复制代码
allure generate ./reports/allure_raw -o ./reports/html --clean
  1. 本地查看报告
bash 复制代码
allure open ./reports/html  # 自动打开浏览器

Allure高级用法
  1. 添加测试步骤
python 复制代码
import allure

def test_with_steps():
    with allure.step("打开登录页"):
        print("导航到登录页面")
    
    with allure.step("输入用户名"):
        assert True
    
    with allure.step("验证结果"):
        allure.attach("截图", "image/png")
  1. 添加分类标签
python 复制代码
@allure.feature("登录模块")
@allure.story("成功场景")
def test_categories():
    allure.epic("用户认证系统")
    allure.tag("smoke")
  1. 添加失败截图(需配合Selenium)
python 复制代码
from selenium import webdriver

def test_screenshot():
    driver = webdriver.Chrome()
    try:
        driver.get("https://example.com")
        assert "Example" in driver.title
    except:
        allure.attach(driver.get_screenshot_as_png(), name="失败截图", attachment_type=allure.attachment_type.PNG)
        raise
    finally:
        driver.quit()

常见问题解决
  1. Allure命令未找到

    • 检查环境变量:echo $PATH
    • 重启终端
  2. 报告无数据

    • 确认--alluredir路径正确
    • 检查pytest执行是否报错
  3. 中文乱码

    bash 复制代码
    # 设置Java编码
    export JAVA_TOOL_OPTIONS="-Dfile.encoding=UTF-8"

集成到CI/CD

Jenkins配置示例:

  1. 安装Allure Jenkins Plugin

  2. 添加构建后步骤:

    plaintext 复制代码
    [Pytest命令] 
    pytest --alluredir=$WORKSPACE/reports/allure_raw
    
    [Report Path] 
    $WORKSPACE/reports/allure_raw
相关推荐
饮水桶_T2 小时前
JAVA IO流笔记
开发语言·数据结构·算法
duansamve3 小时前
Python3+Flask+PostgreSQL18+Vue3项目生产环境用docker如何部署?
python·docker·flask
特立独行的猫A3 小时前
少 3 个环节、少 1 次 ABI、少 3500 行代码:cj-tauri 与 Ionic/Capacitor 的鸿蒙桥接机制对比
java·后端·python
特立独行的猫A3 小时前
cj-tauri vs Rust/Tauri 同款播放器实测:编译 21 秒 vs 11 分钟,磁盘 12 MB vs 1.2 GB
java·后端·python
duansamve4 小时前
详解Flask中Session和Cookie
python·flask
Felven4 小时前
C. Brr Brrr Patapim
c语言·开发语言
威哥爱编程5 小时前
模拟面试智能体开发实战 04:面试聊到哪算哪?用状态机把整场面试编排起来
python·agent·harmonyos
威哥爱编程5 小时前
模拟面试智能体开发实战 03:AI 面试官太客气?人设 Prompt 让它像个真考官
python·agent·harmonyos
量化分析码农5 小时前
股票数据接口返回字段逐项解析:从在线验证到 Python 数据校验
python
Dmz丶6 小时前
前端转 AI 100 天 Day 42:跨模型对比实战——用数据选模型,不靠“听说”
python