387 lines
14 KiB
Markdown
387 lines
14 KiB
Markdown
# 规则库增强设计与用法指南
|
||
|
||
## 概述
|
||
|
||
DDMS合规性验证软件的规则库是整个系统的核心组件,用于存储、管理和执行各种验证规则。本文档介绍了规则库的增强设计,包括新增的规则类型、生命周期和作用域支持、YAML规则格式等特性,以及如何使用这些新功能。
|
||
|
||
## 增强特性
|
||
|
||
### 1. 规则生命周期
|
||
|
||
规则生命周期定义了规则在API测试流程中的适用阶段,使规则执行更加精确和高效。规则生命周期包括以下几个阶段:
|
||
|
||
- **请求准备阶段 (RequestPreparation)**: 在构建和发送API请求之前执行的规则,用于验证请求URL、请求头、请求参数等是否符合要求。
|
||
- **请求执行阶段 (RequestExecution)**: 在发送API请求过程中执行的规则,用于监控请求的执行过程。
|
||
- **响应验证阶段 (ResponseValidation)**: 在接收到API响应后执行的规则,用于验证响应状态码、响应头、响应体等是否符合要求。
|
||
- **后处理阶段 (PostValidation)**: 在完成响应验证后执行的规则,用于执行一些清理或记录工作。
|
||
- **任意阶段 (AnyStage)**: 不关注具体执行阶段的通用规则。
|
||
|
||
### 2. 规则作用域
|
||
|
||
规则作用域定义了规则针对的具体对象,使规则的应用更加精确。规则作用域包括以下几个类型:
|
||
|
||
- **请求URL (RequestURL)**: 规则验证请求的URL是否符合要求,如是否符合RESTful设计规范等。
|
||
- **请求头 (RequestHeaders)**: 规则验证请求头是否符合要求,如是否包含必要的认证信息等。
|
||
- **请求参数 (RequestParams)**: 规则验证请求参数是否符合要求,如参数格式、必填项等。
|
||
- **请求体 (RequestBody)**: 规则验证请求体是否符合要求,如必要的字段、格式等。
|
||
- **响应状态码 (ResponseStatus)**: 规则验证响应状态码是否符合要求,如是否为200、404等特定状态码。
|
||
- **响应头 (ResponseHeaders)**: 规则验证响应头是否符合要求,如是否包含跨域头等。
|
||
- **响应体 (ResponseBody)**: 规则验证响应体是否符合要求,如必要的字段、格式等。
|
||
- **响应时间 (ResponseTime)**: 规则验证API响应时间是否在允许的范围内。
|
||
- **安全性 (Security)**: 规则验证API安全相关的要求,如是否使用HTTPS、是否包含认证信息等。
|
||
- **性能 (Performance)**: 规则验证API性能相关的要求,如响应时间、资源消耗等。
|
||
- **任意作用域 (AnyScope)**: 不关注具体作用域的通用规则。
|
||
|
||
### 3. 新增规则类型
|
||
|
||
为了满足不同场景的验证需求,增强了以下规则类型:
|
||
|
||
- **性能规则 (PerformanceRule)**: 用于验证API性能相关的指标,如响应时间、吞吐量等。
|
||
- **安全规则 (SecurityRule)**: 用于验证API安全相关的要求,如HTTPS强制、认证授权等。
|
||
- **RESTful设计规则 (RESTfulDesignRule)**: 用于验证API URL设计是否符合RESTful规范。
|
||
- **错误处理规则 (ErrorHandlingRule)**: 用于验证API错误响应是否符合标准格式和处理方式。
|
||
|
||
### 4. YAML规则格式
|
||
|
||
为了提高规则的可读性和可维护性,增加了对YAML格式规则的支持。YAML格式的规则可以直接嵌入Python代码,实现更灵活的验证逻辑。
|
||
|
||
## 规则示例
|
||
|
||
### 性能规则示例
|
||
|
||
```yaml
|
||
id: response-time-threshold
|
||
name: 响应时间阈值规则
|
||
description: 验证API响应时间是否在允许的范围内
|
||
category: Performance
|
||
version: 1.0.0
|
||
severity: warning
|
||
is_enabled: true
|
||
tags:
|
||
- performance
|
||
- response-time
|
||
target_type: APIResponse
|
||
lifecycle: ResponseValidation
|
||
scope: ResponseTime
|
||
threshold: 500 # 毫秒
|
||
metric: response_time
|
||
unit: ms
|
||
code: |
|
||
def validate(context):
|
||
response = context.get('api_response')
|
||
if not response:
|
||
return {'is_valid': False, 'message': '缺少API响应对象'}
|
||
|
||
response_time = response.elapsed_time * 1000 # 转换为毫秒
|
||
threshold = context.get('threshold', 500) # 默认500毫秒
|
||
|
||
if response_time > threshold:
|
||
return {
|
||
'is_valid': False,
|
||
'message': f'响应时间 {response_time:.2f}ms 超过阈值 {threshold}ms',
|
||
'details': {
|
||
'actual_time': response_time,
|
||
'threshold': threshold,
|
||
'unit': 'ms'
|
||
}
|
||
}
|
||
|
||
return {
|
||
'is_valid': True,
|
||
'message': f'响应时间 {response_time:.2f}ms 在阈值 {threshold}ms 内',
|
||
'details': {
|
||
'actual_time': response_time,
|
||
'threshold': threshold,
|
||
'unit': 'ms'
|
||
}
|
||
}
|
||
```
|
||
|
||
### 安全规则示例
|
||
|
||
```yaml
|
||
id: https-only-rule
|
||
name: HTTPS强制使用规则
|
||
description: 验证API是否只使用HTTPS协议,确保通信安全
|
||
category: Security
|
||
version: 1.0.0
|
||
severity: error
|
||
is_enabled: true
|
||
tags:
|
||
- security
|
||
- https
|
||
- encryption
|
||
target_type: APIRequest
|
||
lifecycle: RequestPreparation
|
||
scope: Security
|
||
check_type: transport_security
|
||
expected_value: https
|
||
code: |
|
||
def validate(context):
|
||
request = context.get('api_request')
|
||
if not request:
|
||
return {'is_valid': False, 'message': '缺少API请求对象'}
|
||
|
||
url = str(request.url)
|
||
|
||
if not url.startswith('https://'):
|
||
return {
|
||
'is_valid': False,
|
||
'message': 'API请求必须使用HTTPS协议',
|
||
'details': {
|
||
'current_url': url,
|
||
'expected_protocol': 'https'
|
||
}
|
||
}
|
||
|
||
return {
|
||
'is_valid': True,
|
||
'message': 'API请求使用了HTTPS协议',
|
||
'details': {
|
||
'url': url
|
||
}
|
||
}
|
||
```
|
||
|
||
### RESTful设计规则示例
|
||
|
||
```yaml
|
||
id: restful-url-pattern
|
||
name: RESTful URL设计规则
|
||
description: 验证API URL是否符合RESTful设计规范
|
||
category: APIDesign
|
||
version: 1.0.0
|
||
severity: warning
|
||
is_enabled: true
|
||
tags:
|
||
- restful
|
||
- api-design
|
||
- url-pattern
|
||
target_type: APIRequest
|
||
lifecycle: RequestPreparation
|
||
scope: RequestURL
|
||
design_aspect: URL设计
|
||
pattern: "^/api/v\\d+/[a-z0-9-]+(/[a-z0-9-]+)*$"
|
||
code: |
|
||
import re
|
||
|
||
def validate(context):
|
||
request = context.get('api_request')
|
||
if not request:
|
||
return {'is_valid': False, 'message': '缺少API请求对象'}
|
||
|
||
url = str(request.url)
|
||
|
||
# 解析URL,获取路径部分
|
||
from urllib.parse import urlparse
|
||
parsed_url = urlparse(url)
|
||
path = parsed_url.path
|
||
|
||
# 使用正则表达式验证路径
|
||
pattern = context.get('pattern', "^/api/v\\d+/[a-z0-9-]+(/[a-z0-9-]+)*$")
|
||
if not re.match(pattern, path):
|
||
return {
|
||
'is_valid': False,
|
||
'message': 'API URL不符合RESTful设计规范',
|
||
'details': {
|
||
'current_path': path,
|
||
'expected_pattern': pattern,
|
||
'suggestion': '路径应该遵循 /api/v{version}/{资源}[/{id}] 格式'
|
||
}
|
||
}
|
||
|
||
return {
|
||
'is_valid': True,
|
||
'message': 'API URL符合RESTful设计规范',
|
||
'details': {
|
||
'path': path
|
||
}
|
||
}
|
||
```
|
||
|
||
### 错误处理规则示例
|
||
|
||
```yaml
|
||
id: standard-error-response
|
||
name: 标准错误响应格式规则
|
||
description: 验证API错误响应是否符合标准格式
|
||
category: ErrorHandling
|
||
version: 1.0.0
|
||
severity: warning
|
||
is_enabled: true
|
||
tags:
|
||
- error-handling
|
||
- response-format
|
||
target_type: APIResponse
|
||
lifecycle: ResponseValidation
|
||
scope: ResponseBody
|
||
error_code: "*" # 匹配所有错误码
|
||
expected_status: -1 # 不验证状态码
|
||
code: |
|
||
def validate(context):
|
||
response = context.get('api_response')
|
||
if not response:
|
||
return {'is_valid': False, 'message': '缺少API响应对象'}
|
||
|
||
# 只检查4xx和5xx状态码的响应
|
||
if response.status_code < 400:
|
||
return {'is_valid': True, 'message': '非错误响应,跳过验证'}
|
||
|
||
# 确保响应包含JSON内容
|
||
if not response.json_content:
|
||
return {
|
||
'is_valid': False,
|
||
'message': '错误响应不是有效的JSON格式',
|
||
'details': {
|
||
'status_code': response.status_code,
|
||
'content_type': response.headers.get('Content-Type', '未知')
|
||
}
|
||
}
|
||
|
||
# 检查错误响应的必要字段
|
||
required_fields = ['code', 'message']
|
||
missing_fields = [field for field in required_fields if field not in response.json_content]
|
||
|
||
if missing_fields:
|
||
return {
|
||
'is_valid': False,
|
||
'message': '错误响应缺少必要字段',
|
||
'details': {
|
||
'missing_fields': missing_fields,
|
||
'required_fields': required_fields,
|
||
'response': response.json_content
|
||
}
|
||
}
|
||
|
||
return {
|
||
'is_valid': True,
|
||
'message': '错误响应符合标准格式',
|
||
'details': {
|
||
'status_code': response.status_code,
|
||
'error_code': response.json_content.get('code'),
|
||
'error_message': response.json_content.get('message')
|
||
}
|
||
}
|
||
```
|
||
|
||
## 使用方法
|
||
|
||
### 1. 创建规则
|
||
|
||
可以通过以下两种方式创建规则:
|
||
|
||
1. **编程方式创建**:通过实例化规则类来创建规则对象,然后使用规则库的`save_rule`方法保存。
|
||
|
||
```python
|
||
from ddms_compliance_suite.models.rule_models import PerformanceRule, RuleCategory, TargetType, RuleLifecycle, RuleScope
|
||
|
||
# 创建性能规则
|
||
performance_rule = PerformanceRule(
|
||
id="response-time-max-500ms",
|
||
name="响应时间不超过500毫秒",
|
||
description="验证API响应时间不超过500毫秒",
|
||
category=RuleCategory.PERFORMANCE,
|
||
severity="warning",
|
||
target_type=TargetType.API_RESPONSE,
|
||
lifecycle=RuleLifecycle.RESPONSE_VALIDATION,
|
||
scope=RuleScope.RESPONSE_TIME,
|
||
threshold=500,
|
||
metric="response_time",
|
||
unit="ms"
|
||
)
|
||
|
||
# 保存规则
|
||
rule_repository.save_rule(performance_rule)
|
||
```
|
||
|
||
2. **YAML文件创建**:将规则定义为YAML文件,存放在规则库的目录结构中。
|
||
|
||
YAML规则文件存放路径: `rules/yaml_rules/{category}/{rule_id}/{version}.yaml`
|
||
|
||
### 2. 查询规则
|
||
|
||
可以使用规则库的`query_rules`方法查询规则,支持按规则类别、目标类型、生命周期、作用域等条件筛选。
|
||
|
||
```python
|
||
from ddms_compliance_suite.models.rule_models import RuleQuery, RuleCategory, TargetType, RuleLifecycle, RuleScope
|
||
|
||
# 查询所有API响应验证阶段的性能规则
|
||
query = RuleQuery(
|
||
category=RuleCategory.PERFORMANCE,
|
||
target_type=TargetType.API_RESPONSE,
|
||
lifecycle=RuleLifecycle.RESPONSE_VALIDATION,
|
||
scope=RuleScope.RESPONSE_TIME,
|
||
is_enabled=True
|
||
)
|
||
|
||
rules = rule_repository.query_rules(query)
|
||
print(f"找到 {len(rules)} 条规则")
|
||
```
|
||
|
||
### 3. 执行规则
|
||
|
||
可以使用规则执行引擎的`execute_rule`方法执行单个规则,或使用`execute_rules_for_lifecycle`方法执行特定生命周期阶段的所有规则。
|
||
|
||
```python
|
||
from ddms_compliance_suite.rule_executor.executor import RuleExecutor
|
||
|
||
# 创建规则执行引擎
|
||
executor = RuleExecutor(rule_repository)
|
||
|
||
# 执行单个规则
|
||
result = executor.execute_rule(rule, context)
|
||
print(f"规则 '{result.rule_name}' 结果: {'通过' if result.is_valid else '失败'} - {result.message}")
|
||
|
||
# 执行特定生命周期阶段的所有规则
|
||
results = executor.execute_rules_for_lifecycle(RuleLifecycle.RESPONSE_VALIDATION, context)
|
||
for result in results:
|
||
print(f"规则 '{result.rule_name}' 结果: {'通过' if result.is_valid else '失败'} - {result.message}")
|
||
```
|
||
|
||
### 4. 在测试中使用规则
|
||
|
||
可以在API测试流程中集成规则验证,以确保API请求和响应符合规范要求。
|
||
|
||
```python
|
||
from ddms_compliance_suite.api_caller.caller import APICaller, APIRequest
|
||
from ddms_compliance_suite.rule_executor.executor import RuleExecutor
|
||
|
||
# 创建API调用器
|
||
api_caller = APICaller()
|
||
|
||
# 创建API请求
|
||
request = APIRequest(
|
||
method="GET",
|
||
url="https://api.example.com/api/v1/users/123",
|
||
headers={"Content-Type": "application/json"}
|
||
)
|
||
|
||
# 执行请求准备阶段的规则
|
||
context = {"api_request": request}
|
||
prep_results = executor.execute_rules_for_lifecycle(RuleLifecycle.REQUEST_PREPARATION, context)
|
||
for result in prep_results:
|
||
print(f"规则 '{result.rule_name}' 结果: {'通过' if result.is_valid else '失败'} - {result.message}")
|
||
|
||
# 发送API请求
|
||
response = api_caller.call_api(request)
|
||
|
||
# 执行响应验证阶段的规则
|
||
context["api_response"] = response
|
||
resp_results = executor.execute_rules_for_lifecycle(RuleLifecycle.RESPONSE_VALIDATION, context)
|
||
for result in resp_results:
|
||
print(f"规则 '{result.rule_name}' 结果: {'通过' if result.is_valid else '失败'} - {result.message}")
|
||
```
|
||
|
||
## 最佳实践
|
||
|
||
1. **合理组织规则**:按照规则类别、生命周期和作用域组织规则,使规则库结构清晰。
|
||
2. **使用标签**:为规则添加标签,方便按照特定主题或功能筛选规则。
|
||
3. **合理设置优先级**:为规则设置合理的严重性级别,以便于区分重要规则和次要规则。
|
||
4. **编写清晰的规则描述**:为规则提供清晰的描述,使其他开发者能够理解规则的用途和行为。
|
||
5. **使用YAML格式**:对于复杂的验证逻辑,优先使用YAML格式的规则,便于维护和调试。
|
||
6. **避免硬编码**:在规则中避免硬编码具体的验证标准,而是通过规则属性来配置。
|
||
7. **定期维护规则库**:随着API的演进,定期更新和维护规则库,确保规则始终有效。
|
||
|
||
## 结论
|
||
|
||
规则库的增强设计为API测试提供了更强大、更灵活的验证能力,使得DDMS合规性验证软件能够更精确地验证API接口的行为,确保其符合平台定义的数据共享标准和技术规范。通过合理组织和使用规则,可以显著提高API测试的效率和质量。 |