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

部署运行你感兴趣的模型镜像

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

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


环境准备
  1. 安装Python 3.8+
    # 验证安装
    python --version
    
  2. 安装依赖库
    pip install pytest allure-pytest
    
  3. 安装Allure命令行工具
    • 下载Allure
    • 镜像下载Allure
    • 解压并配置环境变量(以Mac/Linux为例):
      # 解压
      unzip allure-commandline-*.zip  
      # 添加到PATH
      export PATH=$PATH:/path/to/allure/bin
      

项目结构

创建基础目录:

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

编写测试用例
  1. 创建基础测试(tests/test_login.py
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
import pytest

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

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

Allure高级用法
  1. 添加测试步骤
import allure

def test_with_steps():
    with allure.step("打开登录页"):
        print("导航到登录页面")
    
    with allure.step("输入用户名"):
        assert True
    
    with allure.step("验证结果"):
        allure.attach("截图", "image/png")
  1. 添加分类标签
@allure.feature("登录模块")
@allure.story("成功场景")
def test_categories():
    allure.epic("用户认证系统")
    allure.tag("smoke")
  1. 添加失败截图(需配合Selenium)
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. 中文乱码

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

集成到CI/CD

Jenkins配置示例:

  1. 安装Allure Jenkins Plugin
  2. 添加构建后步骤:
    [Pytest命令] 
    pytest --alluredir=$WORKSPACE/reports/allure_raw
    
    [Report Path] 
    $WORKSPACE/reports/allure_raw
    

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值