compliance/README_API_TEST_FRAMEWORK.md
2025-05-16 15:18:02 +08:00

230 lines
6.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# API测试框架
这是一个全面的API测试框架专为API合规性测试而设计。该框架能够基于Swagger和YAPI文档自动生成和执行API测试验证API响应是否符合预期的格式和结构。
## 主要功能
- **多格式支持**支持从Swagger和YAPI文件导入API定义。
- **自动测试生成**根据API文档自动生成测试用例。
- **请求参数生成**基于API文档中的schema定义自动生成合理的测试数据。
- **响应验证**
- 状态码验证
- JSON格式验证
- JSON Schema验证
- 未来可扩展自定义规则验证
- **测试编排**管理多个API测试的执行和结果收集。
- **命令行工具**便于集成到CI/CD流程中。
- **详细报告**:生成详细的测试报告,包括失败原因和建议。
## 框架架构
该框架由以下主要组件组成:
1. **输入解析器Input Parser**
- 解析Swagger和YAPI格式的API文档
- 提取API路径、方法、参数和响应schema等信息
2. **API调用器API Caller**
- 负责构建和发送API请求
- 处理不同类型的请求参数和请求体
3. **JSON验证器JSON Validator**
- 验证API响应的格式和结构
- 基于JSON Schema进行响应验证
4. **测试编排器Test Orchestrator**
- 协调上述组件的工作
- 管理测试执行流程
- 收集和汇总测试结果
5. **命令行工具CLI**
- 提供命令行接口,便于使用和集成
## 安装与依赖
该框架依赖以下库:
```
pytest
requests
jsonschema
prance (可选用于高级Swagger解析)
```
可以通过以下命令安装依赖:
```bash
pip install pytest requests jsonschema
```
## 使用方法
### 生成API测试
使用提供的命令行工具生成API测试
```bash
# 从YAPI文件生成测试
python generate_api_tests.py --yapi 路径/到/yapi导出文件.json --base-url http://api服务器:端口
# 从Swagger文件生成测试
python generate_api_tests.py --swagger 路径/到/swagger文件.json --base-url http://api服务器:端口
# 生成特定分类的API测试
python generate_api_tests.py --yapi 路径/到/yapi文件.json --base-url http://api服务器:端口 --categories 分类1,分类2
# 查看所有可用分类
python generate_api_tests.py --yapi 路径/到/yapi文件.json --list-categories
```
### 运行API测试
使用测试编排器运行API测试
```bash
# 运行所有测试
python run_api_tests.py --yapi 路径/到/yapi文件.json --base-url http://api服务器:端口
# 运行特定分类的测试
python run_api_tests.py --yapi 路径/到/yapi文件.json --base-url http://api服务器:端口 --categories 分类1,分类2
# 保存测试结果到文件
python run_api_tests.py --yapi 路径/到/yapi文件.json --base-url http://api服务器:端口 --output 测试报告.json
```
### 运行生成的测试文件
使用pytest运行生成的测试文件
```bash
pytest tests/test_generated_yapi_apis.py -v
# 或
pytest tests/test_generated_swagger_apis.py -v
```
## 测试数据生成
该框架根据API文档中定义的JSON Schema自动生成测试数据
- 对于基本类型(字符串、数字、布尔值等),生成合理的随机值
- 对于对象类型,根据属性定义生成嵌套对象
- 对于数组类型,生成包含适当元素的数组
- 优先使用文档中提供的示例值和默认值
例如对于以下Schema
```json
{
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"},
"tags": {
"type": "array",
"items": {"type": "string"}
}
}
}
```
框架会生成类似这样的测试数据:
```json
{
"name": "测试名称",
"age": 25,
"tags": ["标签1", "标签2"]
}
```
## 响应验证
该框架提供多层次的响应验证:
1. **状态码验证**检查HTTP状态码是否在预期范围内默认为2xx
2. **JSON格式验证**确保响应是有效的JSON格式
3. **Schema验证**根据API文档中定义的响应Schema验证响应内容
4. **自定义规则验证**:(未来扩展)支持基于规则库的自定义验证
验证结果包含详细信息,有助于快速定位和修复问题。
## 示例
### 直接使用验证器
```python
from ddms_compliance_suite.json_schema_validator.validator import JSONSchemaValidator
# 创建验证器
validator = JSONSchemaValidator()
# 定义schema
schema = {
"type": "object",
"properties": {
"code": {"type": "number"},
"message": {"type": "string"},
"data": {"type": "object"}
},
"required": ["code", "message"]
}
# 验证响应
response_data = {"code": 200, "message": "success", "data": {"id": 1}}
result = validator.validate(response_data, schema)
if result.is_valid:
print("验证通过")
else:
print("验证失败")
for error in result.errors:
print(f"错误: {error}")
```
### 使用测试编排器
```python
from ddms_compliance_suite.test_orchestrator import APITestOrchestrator
from ddms_compliance_suite.input_parser.parser import InputParser
# 解析API文档
parser = InputParser()
parsed_api = parser.parse_yapi_spec("path/to/yapi.json")
# 创建测试编排器
orchestrator = APITestOrchestrator(base_url="http://api-server:8080")
# 运行单个API测试
endpoint = parsed_api.endpoints[0]
result = orchestrator.run_test_for_endpoint(endpoint)
# 检查结果
print(f"测试结果: {result.status}")
print(f"测试消息: {result.message}")
# 打印验证详情
if result.validation_details:
print("验证详情:")
for key, value in result.validation_details.items():
if isinstance(value, dict) and 'is_valid' in value:
valid_str = "通过" if value['is_valid'] else "失败"
print(f" {key}: {valid_str}")
if not value['is_valid'] and 'errors' in value:
for error in value['errors']:
print(f" 错误: {error}")
```
## 未来扩展
该框架计划在未来增加以下功能:
1. **规则库**支持自定义验证规则更灵活地定义API响应的合规性要求
2. **测试覆盖率分析**提供API测试覆盖率的统计和分析
3. **历史记录**保存测试历史记录支持比较不同版本的API测试结果
4. **Web界面**提供Web界面方便查看和管理测试结果
5. **性能测试**集成性能测试功能评估API的性能指标
## 贡献与反馈
欢迎提供反馈和建议,帮助我们改进这个框架。如有问题或建议,请联系项目维护者