#!/usr/bin/env python3 """ DMS合规性测试工具 - 完整测试脚本(包含mock服务) 1. 启动mock_dms_server.py在5001端口 2. 调用Docker化的API服务器进行测试 3. 清理mock服务 """ import requests import json import time import sys import subprocess import signal import os from pathlib import Path class MockServerManager: def __init__(self, mock_script="mock_dms_server.py", port=5001): self.mock_script = mock_script self.port = port self.process = None def start(self): """启动mock服务器""" print(f"[信息] 启动mock服务器: {self.mock_script} (端口 {self.port})") if not Path(self.mock_script).exists(): print(f"[错误] Mock脚本不存在: {self.mock_script}") return False try: # 启动mock服务器 self.process = subprocess.Popen( [sys.executable, self.mock_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) # 等待服务启动 print(f"[信息] 等待mock服务器启动...") for i in range(10): # 最多等待10秒 try: response = requests.get(f"http://127.0.0.1:{self.port}/", timeout=2) if response.status_code in [200, 404]: # 404也算正常,说明服务在运行 print(f"[成功] Mock服务器启动成功 (尝试 {i+1}/10)") return True except: pass time.sleep(1) print(f"[错误] Mock服务器启动超时") return False except Exception as e: print(f"[错误] 启动mock服务器失败: {e}") return False def stop(self): """停止mock服务器""" if self.process: print(f"[信息] 停止mock服务器...") try: self.process.terminate() self.process.wait(timeout=5) print(f"[成功] Mock服务器已停止") except subprocess.TimeoutExpired: print(f"[警告] Mock服务器强制终止") self.process.kill() self.process.wait() except Exception as e: print(f"[错误] 停止mock服务器失败: {e}") def test_api_server(api_server, target_api, output_log="log_dms1.txt"): """测试API服务器""" print(f"\n[测试] API服务器功能测试...") # 测试配置(对应原始命令行参数) test_config = { "base-url": target_api, "dms": "./assets/doc/dms/domain.json", "stages-dir": "./custom_stages", "custom-test-cases-dir": "./custom_testcases", "verbose": True, "output": "./test_reports/", "format": "json", "generate-pdf": True, "strictness-level": "CRITICAL", "ignore-ssl": True } print(f"[信息] 测试配置:") print(json.dumps(test_config, indent=2, ensure_ascii=False)) try: print(f"[信息] 发送测试请求到API服务器...") start_time = time.time() response = requests.post( f"{api_server}/run", json=test_config, headers={"Content-Type": "application/json"}, timeout=120 # 2分钟超时 ) end_time = time.time() duration = end_time - start_time # 保存结果到日志文件 with open(output_log, 'w', encoding='utf-8') as f: f.write(f"=== DMS合规性测试结果 ===\n") f.write(f"执行时间: {duration:.2f}秒\n") f.write(f"HTTP状态码: {response.status_code}\n") f.write(f"响应头: {dict(response.headers)}\n\n") if response.status_code == 200: f.write("=== 测试成功 ===\n") try: result_json = response.json() f.write(json.dumps(result_json, indent=2, ensure_ascii=False)) except: f.write("响应内容(非JSON格式):\n") f.write(response.text) else: f.write("=== 测试失败 ===\n") f.write(f"错误信息: {response.text}\n") # 显示结果 print(f"[信息] 请求完成,耗时: {duration:.2f}秒") print(f"[信息] HTTP状态码: {response.status_code}") if response.status_code == 200: print(f"[成功] 测试执行成功") try: result = response.json() print(f"[信息] 测试状态: {result.get('status', '未知')}") if 'summary' in result: summary = result['summary'] print(f"[信息] 测试摘要:") print(f" - 总测试数: {summary.get('total_tests', 0)}") print(f" - 通过数: {summary.get('passed_tests', 0)}") print(f" - 失败数: {summary.get('failed_tests', 0)}") print(f" - 跳过数: {summary.get('skipped_tests', 0)}") if 'output_files' in result: print(f"[信息] 生成的文件:") for file_info in result['output_files']: print(f" - {file_info}") return True except: print(f"[信息] 响应内容已保存到: {output_log}") return True else: print(f"[失败] 测试执行失败") print(f"[错误] 错误信息: {response.text[:200]}...") return False except requests.exceptions.Timeout: print(f"[错误] 请求超时(2分钟)") return False except Exception as e: print(f"[错误] 请求异常: {e}") return False def main(): print("=== DMS合规性测试工具 - 完整功能测试 ===") api_server = "http://localhost:5050" history_server = "http://localhost:5051" target_api = "http://host.docker.internal:5001/" # 使用Docker内部主机访问 # 检查mock脚本是否存在 mock_script = "../mock_dms_server.py" if not Path(mock_script).exists(): print(f"[警告] Mock脚本不存在: {mock_script}") print(f"[信息] 请手动启动mock服务器: python mock_dms_server.py") mock_manager = None else: mock_manager = MockServerManager(mock_script, 5001) try: # 1. 启动mock服务器(如果存在) if mock_manager: if not mock_manager.start(): print(f"[错误] Mock服务器启动失败") print(f"[建议] 请手动启动: python {mock_script}") return 1 # 2. 测试API服务器健康检查 print(f"\n[测试] API服务器健康检查...") health_response = requests.get(f"{api_server}/", timeout=10) if health_response.status_code == 200: print(f"[成功] API服务器运行正常") else: print(f"[错误] API服务器不可用: {health_response.status_code}") return 1 # 3. 测试历史查看器 print(f"\n[测试] 历史查看器...") history_response = requests.get(f"{history_server}/", timeout=10) if history_response.status_code == 200: print(f"[成功] 历史查看器运行正常") else: print(f"[警告] 历史查看器异常: {history_response.status_code}") # 4. 执行完整的API测试 success = test_api_server(api_server, target_api) if success: print(f"\n[成功] 所有测试完成!") print(f"[信息] 查看详细日志: cat log_dms1.txt") print(f"[信息] 查看测试报告: ls -la test_reports/") return 0 else: print(f"\n[失败] 测试执行失败") return 1 except KeyboardInterrupt: print(f"\n[信息] 用户中断测试") return 1 except Exception as e: print(f"\n[错误] 测试异常: {e}") return 1 finally: # 清理mock服务器 if mock_manager: mock_manager.stop() if __name__ == "__main__": sys.exit(main()) try: print(f"[信息] 发送测试请求到API服务器...") start_time = time.time() response = requests.post( f"{api_server}/run", json=test_config, headers={"Content-Type": "application/json"}, timeout=120 # 2分钟超时 ) end_time = time.time() duration = end_time - start_time # 保存结果到日志文件 with open(output_log, 'w', encoding='utf-8') as f: f.write(f"=== DMS合规性测试结果 ===\n") f.write(f"执行时间: {duration:.2f}秒\n") f.write(f"HTTP状态码: {response.status_code}\n") f.write(f"响应头: {dict(response.headers)}\n\n") if response.status_code == 200: f.write("=== 测试成功 ===\n") try: result_json = response.json() f.write(json.dumps(result_json, indent=2, ensure_ascii=False)) except: f.write("响应内容(非JSON格式):\n") f.write(response.text) else: f.write("=== 测试失败 ===\n") f.write(f"错误信息: {response.text}\n") # 显示结果 print(f"[信息] 请求完成,耗时: {duration:.2f}秒") print(f"[信息] HTTP状态码: {response.status_code}") if response.status_code == 200: print(f"[成功] 测试执行成功") try: result = response.json() print(f"[信息] 测试状态: {result.get('status', '未知')}") if 'summary' in result: summary = result['summary'] print(f"[信息] 测试摘要: {summary}") return True except: print(f"[信息] 响应内容已保存到: {output_log}") return True else: print(f"[失败] 测试执行失败") print(f"[错误] 错误信息: {response.text[:200]}...") return False except requests.exceptions.Timeout: print(f"[错误] 请求超时(2分钟)") return False except Exception as e: print(f"[错误] 请求异常: {e}") return False def main(): print("=== DMS合规性测试工具 - 完整功能测试 ===") api_server = "http://localhost:5050" history_server = "http://localhost:5051" target_api = "http://127.0.0.1:5001/" # 检查mock脚本是否存在 mock_script = "mock_dms_server.py" if not Path(mock_script).exists(): print(f"[警告] Mock脚本不存在: {mock_script}") print(f"[信息] 将直接测试API服务器(可能会因为目标API不可用而失败)") mock_manager = None else: mock_manager = MockServerManager(mock_script, 5001) try: # 1. 启动mock服务器(如果存在) if mock_manager: if not mock_manager.start(): print(f"[错误] Mock服务器启动失败") return 1 # 2. 测试API服务器健康检查 print(f"\n[测试] API服务器健康检查...") health_response = requests.get(f"{api_server}/", timeout=10) if health_response.status_code == 200: print(f"[成功] API服务器运行正常") else: print(f"[错误] API服务器不可用: {health_response.status_code}") return 1 # 3. 测试历史查看器 print(f"\n[测试] 历史查看器...") history_response = requests.get(f"{history_server}/", timeout=10) if history_response.status_code == 200: print(f"[成功] 历史查看器运行正常") else: print(f"[警告] 历史查看器异常: {history_response.status_code}") # 4. 执行完整的API测试 success = test_api_server(api_server, target_api) if success: print(f"\n[成功] 所有测试完成!") print(f"[信息] 查看详细日志: cat log_dms1.txt") print(f"[信息] 查看测试报告: ls -la test_reports/") return 0 else: print(f"\n[失败] 测试执行失败") return 1 except KeyboardInterrupt: print(f"\n[信息] 用户中断测试") return 1 except Exception as e: print(f"\n[错误] 测试异常: {e}") return 1 finally: # 清理mock服务器 if mock_manager: mock_manager.stop() if __name__ == "__main__": sys.exit(main())