# pytest-test-framework **Repository Path**: zhongqihang/pytest-test-framework ## Basic Information - **Project Name**: pytest-test-framework - **Description**: 企业级 Pytest 测试框架模板 - 支持 UI/API/数据库三层验证、Allure 报告、并发测试、异步测试 - **Primary Language**: Python - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2026-03-25 - **Last Updated**: 2026-07-06 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Pytest 测试框架模板 [![Python Version](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/) [![Pytest](https://img.shields.io/badge/pytest-8.3+-green.svg)](https://docs.pytest.org/) [![Playwright](https://img.shields.io/badge/playwright-1.49+-orange.svg)](https://playwright.dev/) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) 企业级 Pytest 测试框架模板,支持 UI/API/数据库三层验证、Allure 报告、并发测试、异步测试。 ## ✨ 特性 - 🎯 **三层验证模式**:UI + API + 数据库完整验证 - 📄 **Page Object 模式**:清晰的页面对象封装 - 📊 **Allure 报告集成**:自动截图、录像、日志、网络请求 - 🚀 **并发测试支持**:pytest-xdist 并发执行,大幅缩短测试时间 - ⏱️ **异步测试工具**:完整的异步测试工具函数和规范 - 📦 **灵活依赖管理**:按需安装,支持 MySQL/SQLite - 🧹 **自动清理**:测试数据自动清理,避免污染 - 📝 **完善文档**:详细的使用指南和编写规范 ## 目录结构 ``` tests/ ├── conftest.py # 核心配置文件 ├── pytest.ini # pytest 配置 ├── requirements-test.txt # 测试依赖 ├── run_tests.py # 测试运行脚本 ├── README.md # 测试文档 │ ├── api/ # API 测试目录 │ └── test_example_api.py # API 测试示例 │ ├── ui/ # UI 测试目录 │ ├── pages/ # Page Object 模式 │ │ ├── base_page.py # 基础页面类 │ │ └── example_page.py # 页面对象示例 │ └── test_example_ui.py # UI 测试示例 │ ├── common/ # 共享工具和 fixtures │ ├── fixtures/ # 共享 fixtures │ │ ├── __init__.py │ │ ├── api.py # API 客户端 fixtures │ │ ├── auth.py # 认证相关 fixtures │ │ └── database.py # 数据库 fixtures │ ├── allure_helper.py # Allure 报告辅助工具 │ └── allure_decorators.py # Allure 装饰器 │ └── reports/ # 测试报告目录 ├── allure/ # Allure 原始数据 ├── allure-report/ # Allure HTML 报告 ├── coverage/ # 覆盖率报告 ├── screenshots/ # 截图 └── videos/ # 测试录像 ``` ## 快速开始 ### 1. 安装依赖 ```bash pip install -r requirements-test.txt playwright install chromium ``` ### 2. 配置项目信息 编辑 `conftest.py`,修改以下配置: ```python # 项目基础配置 PROJECT_NAME = "你的项目名" API_BASE_URL = "http://localhost:8000" DB_CONFIG = { "host": "localhost", "port": 3306, "user": "root", "password": "password", "database": "your_db" } ``` ### 3. 运行测试 ```bash # 运行所有测试 pytest # 运行 API 测试 pytest -m api # 运行 UI 测试 pytest -m ui # 运行 P0 优先级测试 pytest -m p0 # 生成 Allure 报告 pytest --alluredir=reports/allure allure serve reports/allure ``` ## 测试编写指南 ### API 测试示例 ```python import pytest import allure from common.allure_helper import AllureHelper @pytest.mark.api @pytest.mark.p1 @allure.feature("用户管理") @allure.story("用户 CRUD 操作") class TestUserAPI: @pytest.fixture(autouse=True) def setup(self, api_client, db_helper): self.client = api_client self.db = db_helper @pytest.mark.positive @allure.title("API - 测试创建用户") @allure.severity(allure.severity_level.CRITICAL) def test_create_user(self): with allure.step("1. 准备测试数据"): test_data = {"username": "test_user", "email": "test@example.com"} AllureHelper.attach_json(test_data, "请求数据") with allure.step("2. 调用创建 API"): response = self.client.post("/api/users", json=test_data) AllureHelper.attach_api_call("POST", "/api/users", test_data, response) with allure.step("3. 验证响应"): assert response.status_code == 200 assert response.json()["success"] is True with allure.step("4. 验证数据库"): result = self.db.fetch_one("SELECT * FROM users WHERE username = %s", ("test_user",)) assert result["email"] == "test@example.com" ``` ### UI 测试示例 ```python import pytest import allure from ui.pages.user_page import UserPage @pytest.mark.ui @pytest.mark.p1 class TestUserUI: @pytest.fixture(autouse=True) def setup(self, page, auto_login): pass @pytest.mark.positive def test_create_user(self, page, db_helper, screenshot_helper): user_page = UserPage(page) # 1. 前端操作 user_page.navigate_to_list() screenshot_helper("01_user_list") user_page.create_user("test_user", "test@example.com") screenshot_helper("02_after_create") # 2. 前端验证 assert user_page.is_user_exists("test_user") # 3. 数据库验证 result = db_helper.fetch_one("SELECT * FROM users WHERE username = %s", ("test_user",)) assert result["email"] == "test@example.com" ``` ## 核心特性 ### 1. Fixture 分层设计 - **Session 级别**:数据库连接、浏览器实例(所有测试共享) - **Function 级别**:页面实例、API 客户端、数据库助手(每个测试独立) - **Autouse**:自动登录、自动清理(无需显式声明) ### 2. Page Object 模式 所有页面操作封装在 Page Object 中,测试用例只调用高层方法: ```python class UserPage(BasePage): def create_user(self, username: str, email: str): self.click("#create-btn") self.fill("#username", username) self.fill("#email", email) self.click("#submit-btn") self.page.wait_for_url("**/users/list") ``` ### 3. 三层验证模式 ```python # 1. 前端操作 user_page.create_user("test", "test@example.com") # 2. 前端验证 assert user_page.is_user_exists("test") # 3. 数据库验证 result = db.fetch_one("SELECT * FROM users WHERE username = %s", ("test",)) assert result["email"] == "test@example.com" ``` ### 4. Allure 集成 - 自动附件钩子(截图、视频、日志、网络请求) - AllureHelper 工具类(丰富的附件方法) - AllureDecorators 装饰器(简化标记) ### 5. 自动清理 ```python @pytest.fixture(scope="function", autouse=True) def cleanup_test_data(db_helper): yield # 测试执行 # 清理测试数据 db_helper.execute("DELETE FROM users WHERE username LIKE 'test_%'") ``` ## 技术栈 | 类别 | 技术 | 版本 | 用途 | |------|------|------|------| | 测试框架 | pytest | 8.3.4 | 核心测试框架 | | UI 自动化 | Playwright | 1.49.1 | 浏览器自动化 | | API 测试 | requests | 2.32.3 | HTTP 请求 | | 数据库 | pymysql | 1.1.1 | MySQL 连接 | | 测试报告 | allure-pytest | 2.13.5 | 测试报告生成 | | 并行执行 | pytest-xdist | 3.6.1 | 并行测试 | | 覆盖率 | pytest-cov | 6.0.0 | 代码覆盖率 | ## 最佳实践 1. **分层清晰**:API 测试、UI 测试、单元测试分离 2. **Page Object**:所有 UI 操作封装在 Page Object 中 3. **三层验证**:前端 + API + 数据库 4. **自动清理**:测试数据自动清理,避免污染 5. **丰富报告**:Allure 集成,自动附加截图、视频、日志 6. **Fixture 复用**:通过 common/fixtures 实现跨测试复用 7. **标记管理**:使用 pytest markers 分类测试 ## 适配新项目 ### 1. 修改配置 编辑 `conftest.py`: - 修改 `PROJECT_NAME`、`API_BASE_URL` - 修改 `DB_CONFIG` 数据库配置 - 修改 `auto_login` fixture 的登录逻辑 ### 2. 创建 Page Object 在 `ui/pages/` 目录下创建页面对象: - 继承 `BasePage` - 封装页面操作方法 - 使用清晰的方法命名(`navigate_to_*`、`create_*`、`is_*_exists`) ### 3. 编写测试用例 - API 测试放在 `api/` 目录 - UI 测试放在 `ui/` 目录 - 使用 pytest markers 标记测试类型和优先级 ### 4. 自定义清理逻辑 编辑 `conftest.py` 中的 `cleanup_test_data` fixture,添加项目特定的清理逻辑。 ## 常见问题 ### 1. 如何跳过某些测试? ```python @pytest.mark.skip(reason="功能未实现") def test_something(): pass ``` ### 2. 如何参数化测试? ```python @pytest.mark.parametrize("username,email", [ ("user1", "user1@example.com"), ("user2", "user2@example.com"), ]) def test_create_user(username, email): pass ``` ### 3. 如何并行运行测试? ```bash pytest -n 4 # 使用 4 个进程并行运行 ``` ### 4. 如何只运行失败的测试? ```bash pytest --lf # last failed ``` ## 📚 文档 | 文档 | 说明 | |------|------| | [快速参考](快速参考.md) | 快速参考卡片 ⭐⭐⭐⭐⭐ | | [使用指南](使用指南.md) | 快速使用指南 ⭐⭐⭐⭐⭐ | | [测试用例编写规范](测试用例编写规范.md) | 测试用例编写规范 ⭐⭐⭐⭐⭐ | | [异步测试用例编写规范](异步测试用例编写规范.md) | 异步测试规范 ⭐⭐⭐⭐ | | [并发测试配置指南](并发测试配置指南.md) | 并发测试指南 ⭐⭐⭐⭐ | | [依赖管理说明](依赖管理说明.md) | 依赖管理说明 ⭐⭐⭐⭐ | | [UI测试报告内容说明](UI测试报告内容说明.md) | UI 测试报告说明 ⭐⭐⭐⭐ | | [模板优化说明](模板优化说明.md) | 模板优化说明 ⭐⭐⭐ | ## 许可证 MIT License