# pytest-api-framework **Repository Path**: zhanglongwork/pytest-api-framework ## Basic Information - **Project Name**: pytest-api-framework - **Description**: 接口自动化框架Python文件 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-03-07 - **Last Updated**: 2026-03-07 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # API 自动化测试框架 基于 pytest 的企业级 API 自动化测试框架,支持数据驱动、多环境配置、数据库操作、加密工具等完整功能。 ## ✨ 核心特性 - 🚀 **强大的 HTTP 客户端** - 支持重试机制、代理、SSL验证、文件上传等 - 📊 **丰富的断言方法** - JSON路径断言、响应时间断言、Schema验证等 - 🔐 **完善的加密工具** - MD5/SHA/Base64/AES加密、Token生成等 - 💾 **数据库支持** - MySQL数据库操作、事务管理、自动回滚 - 🌍 **多环境配置** - dev/test/staging/prod环境一键切换 - 📝 **数据驱动测试** - YAML格式测试数据,易于维护 - 📈 **测试报告** - HTML报告和Allure报告双支持 - ⚡ **并行执行** - pytest-xdist多进程并行测试 - 🔧 **丰富的Fixture** - 随机数据生成、临时文件、Mock响应等 ## 📁 项目结构 ``` pytest-api-framework/ ├── commons/ # 公共工具模块 │ ├── __init__.py │ ├── http_client.py # HTTP请求客户端(重试/代理/SSL) │ ├── assert_util.py # 断言工具类(JSON路径/Schema/响应时间) │ ├── database.py # 数据库操作类(MySQL) │ ├── crypto_util.py # 加密工具类(MD5/SHA/Base64/AES) │ └── logger_config.py # 日志配置 ├── config/ # 配置模块 │ ├── __init__.py │ └── config.py # 多环境配置管理 ├── data/ # 测试数据(YAML) │ ├── login.yaml # 登录测试数据 │ ├── user.yaml # 用户接口测试数据 │ └── phpwind.yaml # 其他测试数据 ├── hotload/ # 热加载模块 │ ├── __init__.py │ └── hotload_manager.py ├── tests/ # 测试用例 │ ├── __init__.py │ ├── conftest.py # pytest配置和Fixture │ ├── test_api.py # API测试用例 │ └── test_example.py # 示例测试用例 ├── utils/ # 工具类 │ ├── __init__.py │ └── read_data.py # 数据读取工具 ├── logs/ # 日志目录(自动生成) ├── reports/ # 测试报告目录(自动生成) ├── temps/ # 临时文件目录(自动生成) ├── .gitignore ├── pytest.ini # pytest配置 ├── requirements.txt # 依赖包 ├── run.py # 运行入口 ├── README.md # 项目文档 └── GUIDE.md # 使用指南 ``` ## 🚀 快速开始 ### 1. 安装依赖 ```bash pip install -r requirements.txt ``` ### 2. 配置环境 编辑 `config/config.py`,设置你的 API 基础 URL: ```python # 或使用环境变量 export TEST_ENV=prod export BASE_URL=https://api.example.com ``` ### 3. 运行测试 ```bash # 运行所有测试 python run.py # 使用 pytest 命令 pytest -v # 指定环境运行 pytest --env=prod -v # 只运行冒烟测试 pytest -v -m smoke # 生成 HTML 报告 pytest --html=reports/report.html # 生成 Allure 报告 pytest --alluredir=allure-results allure serve allure-results # 并行执行 pytest -n auto ``` ## 📖 核心模块使用 ### HTTPClient - HTTP 请求客户端 ```python from commons.http_client import HTTPClient # 初始化 client = HTTPClient( base_url="https://api.example.com", timeout=30, max_retries=3, verify_ssl=True ) # 基本请求 response = client.get("/users", params={"id": 123}) response = client.post("/login", json={"username": "admin", "password": "123456"}) response = client.put("/users/123", json={"name": "new_name"}) response = client.delete("/users/123") # 设置认证 client.set_bearer_token("your_token") client.set_auth(("username", "password")) # Cookie 管理 client.set_cookies({"session_id": "xxx"}) client.clear_cookies() # 文件上传 client.upload_file("/upload", "/path/to/file", file_key="file") # 使用上下文管理器 with HTTPClient("https://api.example.com") as client: response = client.get("/users") ``` ### AssertUtil - 断言工具 ```python from commons.assert_util import AssertUtil # 基本断言 AssertUtil.assert_equal(actual, expected) AssertUtil.assert_not_equal(actual, expected) AssertUtil.assert_in("key", {"key": "value"}) # HTTP 断言 AssertUtil.assert_status_code(response.status_code, 200) AssertUtil.assert_status_code_in(response.status_code, [200, 201]) # JSON 路径断言 AssertUtil.assert_json_path(response.json(), "data.user.id", 123) AssertUtil.assert_json_path_exists(response.json(), "data.user.name") # 响应时间断言 AssertUtil.assert_response_time(response.elapsed_ms, 1000) # Schema 验证 schema = { "id": "int", "name": "str", "email": "str" } AssertUtil.assert_schema(response.json(), schema) # 类型断言 AssertUtil.assert_type(response.json()["id"], int) # 列表断言 AssertUtil.assert_list_length(response.json()["items"], 10) AssertUtil.assert_list_not_empty(response.json()["items"]) # 正则断言 AssertUtil.assert_regex_match(email, r"[\w\.-]+@[\w\.-]+\.\w+") ``` ### CryptoUtil - 加密工具 ```python from commons.crypto_util import CryptoUtil # 哈希加密 md5_hash = CryptoUtil.md5("password") sha256_hash = CryptoUtil.sha256("password") # Base64 编解码 encoded = CryptoUtil.base64_encode("hello world") decoded = CryptoUtil.base64_decode(encoded) # HMAC 签名 signature = CryptoUtil.hmac_sha256("secret_key", "message") # 生成随机数据 token = CryptoUtil.generate_token() uuid = CryptoUtil.generate_uuid() timestamp = CryptoUtil.generate_timestamp() # API 签名 params = {"name": "test", "age": 18} signature = CryptoUtil.generate_signature(params, "secret_key", method="md5") # AES 加解密(需安装 pycryptodome) encrypted = CryptoUtil.encrypt_aes("secret data", "16bytesecretkey!!") decrypted = CryptoUtil.decrypt_aes(encrypted, "16bytesecretkey!!") # 密码哈希 hashed = CryptoUtil.hash_password("password123") is_valid = CryptoUtil.verify_password("password123", hashed) ``` ### Database - 数据库操作 ```python from commons.database import Database, get_database_from_config # 使用配置连接 db = get_database_from_config() db.connect() # 或直接创建连接 db = Database( host="localhost", port=3306, user="root", password="password", database="test_db" ) db.connect() # 查询 users = db.fetch_all("SELECT * FROM users WHERE age > %s", (18,)) user = db.fetch_one("SELECT * FROM users WHERE id = %s", (1,)) count = db.fetch_value("SELECT COUNT(*) FROM users") # 插入 user_id = db.insert_and_get_id("users", {"name": "test", "email": "test@example.com"}) # 更新 db.update("users", {"name": "new_name"}, "id = %s", (1,)) # 删除 db.delete("users", "id = %s", (1,)) # 事务 with db.transaction(): db.insert("users", {"name": "user1"}) db.insert("users", {"name": "user2"}) # 使用上下文管理器 with Database(host="localhost", database="test_db") as db: users = db.fetch_all("SELECT * FROM users") ``` ### 多环境配置 ```python from config.config import Config # 切换环境 Config.set_env("prod") # 获取配置 base_url = Config.get("BASE_URL") timeout = Config.get("TIMEOUT", 30) # 获取所有配置 all_config = Config.get_all() # 使用环境变量覆盖 export BASE_URL=https://custom-api.com export TEST_ENV=prod ``` ## 🧪 编写测试用例 ### 数据驱动测试 ```yaml # data/login.yaml - case_id: login_001 name: "正常登录" method: POST path: /api/login json: username: admin password: "123456" expected_status: 200 expected_code: 0 ``` ```python # tests/test_login.py import pytest from commons.http_client import HTTPClient from commons.assert_util import AssertUtil class TestLogin: @pytest.fixture(scope="class", autouse=True) def setup(self, base_url): self.client = HTTPClient(base_url) yield self.client.close() @pytest.mark.parametrize("data", read_yaml_data("login.yaml")) def test_login(self, data): response = self.client.request( method=data['method'], path=data['path'], json=data['json'] ) AssertUtil.assert_status_code(response.status_code, data['expected_status']) ``` ### 使用 Fixture ```python import pytest class TestExample: # 使用会话级别 HTTP 客户端 def test_with_session_client(self, http_client): response = http_client.get("/users") assert response.status_code == 200 # 使用随机数据生成器 def test_with_random_data(self, random_data): email = random_data.email() phone = random_data.phone() # 使用数据库事务(自动回滚) def test_with_db(self, db_transaction): db_transaction.insert("users", {"name": "test"}) # 使用临时文件 def test_with_temp_file(self, temp_file): file_path = temp_file("content", ".txt") ``` ## 📊 测试报告 ### HTML 报告 ```bash pytest --html=reports/report.html --self-contained-html ``` ### Allure 报告 ```bash pytest --alluredir=allure-results allure serve allure-results ``` ## 🏷️ 测试标记 ```python @pytest.mark.smoke # 冒烟测试 @pytest.mark.regression # 回归测试 @pytest.mark.api # API 测试 @pytest.mark.slow # 慢速测试 @pytest.mark.db # 数据库测试 @pytest.mark.auth # 认证测试 ``` ```bash # 只运行冒烟测试 pytest -m smoke # 运行慢速测试 pytest --runslow ``` ## 🔧 命令行选项 ```bash # 指定环境 pytest --env=prod # 运行慢速测试 pytest --runslow # 并行执行 pytest -n auto # 失败重试 pytest --reruns 3 # 详细输出 pytest -v -s ``` ## 📝 最佳实践 1. **测试数据分离** - 使用 YAML 文件管理测试数据 2. **统一断言** - 使用 AssertUtil 进行断言 3. **日志记录** - 关键步骤记录日志 4. **环境隔离** - 使用多环境配置 5. **事务回滚** - 数据库测试使用事务自动回滚 6. **并行执行** - 使用 pytest-xdist 加速测试 ## 📦 依赖说明 | 包名 | 用途 | |------|------| | pytest | 测试框架 | | requests | HTTP 请求 | | PyYAML | YAML 解析 | | allure-pytest | Allure 报告 | | pytest-html | HTML 报告 | | pytest-xdist | 并行执行 | | loguru | 日志系统 | | pymysql | MySQL 数据库 | | pycryptodome | AES 加密 | ## 📄 许可证 MIT License