compliance/examples/test_orchestrator_with_rules.py
2025-05-16 15:18:02 +08:00

170 lines
5.3 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
测试编排器与规则库集成示例
此示例展示如何使用集成了规则库的测试编排器来执行API测试。
"""
import os
import sys
import json
import logging
from pathlib import Path
# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from ddms_compliance_suite.test_orchestrator import APITestOrchestrator
from ddms_compliance_suite.models.rule_models import (
BaseRule, PerformanceRule, SecurityRule, RESTfulDesignRule, ErrorHandlingRule,
RuleCategory, TargetType, RuleLifecycle, RuleScope, SeverityLevel
)
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def create_example_rules(rule_repo):
"""创建示例规则"""
# 1. 性能规则 - 响应时间不超过500毫秒
performance_rule = PerformanceRule(
id="response-time-max-500ms",
name="响应时间不超过500毫秒",
description="验证API响应时间不超过500毫秒",
category=RuleCategory.PERFORMANCE,
severity=SeverityLevel.WARNING,
target_type=TargetType.API_RESPONSE,
lifecycle=RuleLifecycle.RESPONSE_VALIDATION,
scope=RuleScope.RESPONSE_TIME,
threshold=500.0,
metric="response_time",
unit="ms"
)
# 2. 安全规则 - HTTPS必须使用
security_rule = SecurityRule(
id="https-only-rule",
name="HTTPS强制使用规则",
description="验证API请求是否使用了HTTPS协议",
category=RuleCategory.SECURITY,
severity=SeverityLevel.ERROR,
target_type=TargetType.API_REQUEST,
lifecycle=RuleLifecycle.REQUEST_PREPARATION,
scope=RuleScope.SECURITY,
check_type="transport_security",
expected_value="https"
)
# 3. RESTful设计规则 - URL路径格式
restful_rule = RESTfulDesignRule(
id="restful-url-pattern",
name="RESTful URL设计规则",
description="验证API URL是否符合RESTful设计规范",
category=RuleCategory.API_DESIGN,
severity=SeverityLevel.WARNING,
target_type=TargetType.API_REQUEST,
lifecycle=RuleLifecycle.REQUEST_PREPARATION,
scope=RuleScope.REQUEST_URL,
design_aspect="URL设计",
pattern=r"^/api/v\d+/[a-z0-9-]+(/[a-z0-9-]+)*$"
)
# 4. 错误处理规则 - 错误响应格式
error_rule = ErrorHandlingRule(
id="standard-error-response",
name="标准错误响应格式规则",
description="验证API错误响应是否符合标准格式",
category=RuleCategory.ERROR_HANDLING,
severity=SeverityLevel.WARNING,
target_type=TargetType.API_RESPONSE,
lifecycle=RuleLifecycle.RESPONSE_VALIDATION,
scope=RuleScope.RESPONSE_BODY,
error_code="*",
expected_status=400
)
# 保存规则到规则库
rule_repo.save_rule(performance_rule)
rule_repo.save_rule(security_rule)
rule_repo.save_rule(restful_rule)
rule_repo.save_rule(error_rule)
logger.info("已创建示例规则")
def run_api_tests_with_rules(base_url, yapi_file_path, output_file=None):
"""
使用规则库运行API测试
Args:
base_url: API基础URL
yapi_file_path: YAPI定义文件路径
output_file: 输出文件路径(可选)
"""
# 创建临时规则目录
rules_dir = Path("./temp_rules")
rules_dir.mkdir(exist_ok=True)
try:
# 初始化测试编排器
orchestrator = APITestOrchestrator(
base_url=base_url,
rule_repo_path=str(rules_dir)
)
# 创建示例规则
create_example_rules(orchestrator.rule_repo)
# 运行API测试
logger.info(f"开始运行API测试: {yapi_file_path}")
summary = orchestrator.run_tests_from_yapi(yapi_file_path)
# 打印测试结果摘要
summary.print_summary()
# 保存测试结果
if output_file:
with open(output_file, 'w', encoding='utf-8') as f:
f.write(summary.to_json(pretty=True))
logger.info(f"测试结果已保存到: {output_file}")
return summary
finally:
# 清理临时规则目录
# 注意:如果要保留规则,可以注释掉这部分
import shutil
if rules_dir.exists():
shutil.rmtree(rules_dir)
def parse_arguments():
"""解析命令行参数"""
import argparse
parser = argparse.ArgumentParser(description='测试编排器与规则库集成示例')
parser.add_argument('--base-url', required=True, help='API基础URL')
parser.add_argument('--yapi', required=True, help='YAPI定义文件路径')
parser.add_argument('--output', help='输出文件路径')
return parser.parse_args()
def main():
"""主函数"""
args = parse_arguments()
# 运行API测试
summary = run_api_tests_with_rules(
base_url=args.base_url,
yapi_file_path=args.yapi,
output_file=args.output
)
# 返回测试结果状态码
return 1 if summary.failed > 0 or summary.error > 0 else 0
if __name__ == "__main__":
sys.exit(main())