pytest+allure实践

本文详细介绍了如何在Python环境下安装和配置pytest、pytest-allure-adaptor,以及如何生成和查看Allure测试报告。包括安装依赖、配置pytest.ini文件、处理常见问题等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用的软件版本 python 3.6.5
pycharm 2017 3.3
pytest 4.0.2
pytest-allure-adaptor 1.7.0
pytest的安装:
1.1. windows下:
pip install pytest 4.0.2
安装pytest-allure-adaptor插件
2.1. windows下:
pip install pytest-allure-adaptor
注意:一定要先操作1步骤,在操作2步骤,且pytest版本选4.0.2,如果直接运行pip install pytest,可能会发生在pycharm的terminal中运行pytest -s -q --alluredir=./allure-results命令时找不到路径,无法执行成功的情况
3.allure的安装:
3.1. windows下:
前情提示: allure是基于Java的一个程序,需要Java1.8的环境,没有安装需要去安装一下。
Windows下不能直接安装,点击此链接下载压缩包

https://dl.bintray.com/qameta/generic/io/qameta/allure/allure/2.7.0/allure-2.7.0.zip

下载之后,将压缩包解压到一个磁盘中,我这里用的是D盘
在这里插入图片描述
3.2. 配置allure的环境变量
在这里插入图片描述

<think>我们被要求使用Python的pytest框架结合Allure生成测试报告进行测试开发。根据引用内容,我们可以整理出以下关键步骤和知识点: 1. **环境安装**: - 安装pytest:`pip install pytest` - 安装allure-pytest插件:`pip install allure-pytest` - 安装Allure命令行工具(需要下载并配置环境变量)[^1][^4] 2. **测试用例编写规则**(引用[3]): - 测试模块(文件)命名:以`test_`开头或以`_test.py`结尾。 - 测试函数命名:以`test_`开头。 - 测试类命名:建议以`Test`开头(虽然不是强制,但常见)。 3. **运行测试并生成Allure报告**: - 使用pytest运行测试并生成Allure结果数据:`pytest --alluredir=allure-results`(其中`allure-results`是存放结果的目录)[^2][^4]。 - 生成Allure报告:`allure generate allure-results -o allure-report --clean`(将结果数据生成HTML报告到`allure-report`目录)[^5]。 - 打开报告:`allure open allure-report`[^5]。 4. **自动化脚本**(引用[5]): - 可以编写一个Python脚本(如`run_case.py`)来执行整个流程(激活虚拟环境、运行测试、生成报告、打开报告)。 5. **Allure的特性**: - Allure报告支持丰富的特性,如步骤(step)、严重性(severity)、描述(description)等,这些可以通过在测试用例中添加装饰器来实现。 下面是一个完整的实战教程,包括测试用例编写、运行和生成报告。 ### 步骤1:创建项目结构 假设项目结构如下: ``` project_root/ ├── test_case/ # 存放测试用例 │ └── test_sample.py # 测试用例文件 ├── conftest.py # pytest的配置文件(可选) ├── run_case.py # 运行测试并生成报告的脚本 └── requirements.txt # 依赖包列表 ``` ### 步骤2:编写测试用例 在`test_sample.py`中编写简单的测试用例: ```python import pytest def test_addition(): assert 1 + 1 == 2 def test_subtraction(): assert 5 - 3 == 2 @pytest.mark.skip(reason="示例跳过测试") def test_skip(): assert True ``` ### 步骤3:编写运行脚本 在`run_case.py`中编写脚本,用于执行测试并生成报告(参考引用[5]并修改): ```python import subprocess import sys # 判断操作系统 WIN = sys.platform.startswith('win') def main(): # 步骤:1.运行测试并生成allure原始数据;2.生成报告;3.打开报告 commands = [ "pytest --alluredir=allure-results --clean-alluredir", # 运行测试并清除之前的结果 "allure generate allure-results -o allure-report --clean", # 生成报告,并清除之前的报告 "allure open allure-report" # 打开报告 ] for cmd in commands: # 如果是Windows,使用call命令,否则直接运行 if WIN: subprocess.run(f"call {cmd}", shell=True) else: subprocess.run(cmd, shell=True) if __name__ == "__main__": main() ``` ### 步骤4:安装依赖 在`requirements.txt`中列出依赖: ``` pytest allure-pytest ``` 安装依赖:`pip install -r requirements.txt` ### 步骤5:运行测试 执行`run_case.py`,它将依次执行: 1. 运行pytest测试,生成Allure结果数据到`allure-results`目录。 2. 使用Allure命令行工具生成HTML报告到`allure-report`目录。 3. 自动打开生成的HTML报告。 ### 步骤6:查看Allure报告 报告将展示测试的执行情况,包括通过率、失败情况、跳过情况等,并且有丰富的图表和详情。 ### 扩展:使用Allure特性增强报告 在测试用例中,可以使用Allure提供的装饰器来增强报告的可读性,例如: ```python import allure @allure.feature("测试计算") class TestCalculation: @allure.story("加法测试") def test_addition(self): assert 1+1==2 @allure.story("减法测试") @allure.severity(allure.severity_level.CRITICAL) def test_subtraction(self): assert 5-3==2 ``` 这样在报告中,我们可以看到按照特性(Feature)和故事(Story)分类的测试用例,以及严重级别。 ### 注意事项 - 确保已经正确安装Allure命令行工具,并将其加入系统环境变量PATH中[^4]。 - 在运行脚本中,如果使用虚拟环境,需要先激活虚拟环境(引用[5]中有相关命令),但我们的脚本中并没有激活虚拟环境的步骤,因为通常我们会在运行脚本前确保在虚拟环境中。如果需要,可以在命令列表的最前面添加激活虚拟环境的命令(如引用[5]所示)。 通过以上步骤,我们就可以完成一个基于pytestAllure的测试开发实战。 §§相关问题§§ 1. 如何给Allure测试报告添加自定义的步骤描述? 2. 在pytest中如何参数化测试用例? 3. 如何将Allure报告集成到持续集成(CI)工具中?</think>### Python pytest Allure框架测试开发实战教程 下面是一个完整的实战教程,帮助你快速掌握Python测试开发中pytest+Allure框架的使用: --- #### **1. 环境安装与配置** ```bash # 安装核心依赖 pip install pytest allure-pytest selenium # 安装Allure命令行工具(需配置环境变量) # 下载地址:https://github.com/allure-framework/allure2/releases # 解压后将bin目录加入系统PATH ``` --- #### **2. 项目结构示例** ``` project/ ├── test_case/ # 测试用例目录 │ ├── test_login.py # 测试模块 │ └── test_search.py ├── conftest.py # pytest全局配置 ├── run.py # 测试执行入口 └── reports/ # 测试报告目录 ``` --- #### **3. 测试用例编写规范** ```python # test_login.py import allure import pytest @allure.feature("用户认证") class TestLogin: @allure.story("成功登录") @allure.severity(allure.severity_level.CRITICAL) def test_success_login(self): """验证有效凭据登录成功""" with allure.step("输入用户名"): print("输入admin") with allure.step("输入密码"): print("输入123456") with allure.step("点击登录按钮"): print("点击操作") assert "dashboard" in "欢迎来到dashboard页面" @allure.story("失败登录") @pytest.mark.parametrize("username,password", [ ("admin", "wrong"), ("test", "123456") ]) def test_failed_login(self, username, password): """验证无效凭据登录失败""" allure.dynamic.title(f"登录失败测试:{username}/{password}") print(f"尝试登录 {username}:{password}") assert "invalid" in "登录失败:无效凭证" ``` **关键注解说明**: - `@allure.feature`:功能模块分类 - `@allure.story`:用户故事/测试场景 - `@allure.step`:操作步骤分解 - `@pytest.mark.parametrize`:参数化测试 --- #### **4. 全局配置(conftest.py)** ```python import pytest from selenium import webdriver @pytest.fixture(scope="session") def browser(): """共享浏览器实例""" driver = webdriver.Chrome() driver.implicitly_wait(10) yield driver driver.quit() @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item): """获取测试结果钩子""" outcome = yield report = outcome.get_result() if report.when == 'call' and report.failed: try: # 失败时截图 driver = item.funcargs['browser'] driver.save_screenshot(f"reports/{item.nodeid}.png") allure.attach.file(f"reports/{item.nodeid}.png", name="失败截图", attachment_type=allure.attachment_type.PNG) except: pass ``` --- #### **5. 测试执行脚本(run.py)** ```python #!/usr/bin/env python3 import subprocess import pytest import os if __name__ == "__main__": # 1. 执行测试并生成原始数据 pytest.main([ '-v', 'test_case/', '--alluredir=reports/raw', '--clean-alluredir' ]) # 2. 生成HTML报告 os.system('allure generate reports/raw -o reports/html --clean') # 3. 自动打开报告 os.system('allure open reports/html') ``` --- #### **6. 执行测试与查看报告** ```bash # 运行测试 python run.py # 报告生成后自动打开浏览器 # 或手动查看:allure open reports/html ``` **报告包含核心功能**: 1. 测试用例分层展示(Feature > Story) 2. 参数化测试多维度展示 3. 失败用例自动截图 4. 历史趋势对比 5. 环境信息记录 6. 用例执行时间统计 --- #### **7. 最佳实践技巧** 1. **参数化优化**: ```python # 使用json文件管理测试数据 import json with open("test_data.json") as f: test_data = json.load(f) @pytest.mark.parametrize("data", test_data["login_cases"]) def test_login(data): username = data["username"] ... ``` 2. **Allure标签动态生成**: ```python def test_search(): search_term = "pytest" allure.dynamic.title(f"搜索测试: {search_term}") allure.dynamic.tag("smoke") ``` 3. **CI/CD集成示例**(Jenkins): ```groovy pipeline { stages { stage('Test') { steps { sh 'python run.py' } } stage('Report') { steps { allure includeProperties: false, jdk: '', results: [[path: 'reports/raw']] } } } } ``` --- #### **8. 常见问题解决** 1. **Allure报告无数据**: - 检查`--alluredir`路径是否正确 - 确认测试执行未使用`-p no:allure`参数 2. **截图失败**: - 确保`conftest.py`在项目根目录 - 验证浏览器驱动兼容性 3. **参数化显示异常**: - 使用`allure.dynamic`替代静态注解 - 避免在参数中使用特殊字符`@$&` > 完整示例代码参考:https://github.com/pytest-dev/pytest-allure-example [^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值