PCM_Report/test_config_service.py

307 lines
10 KiB
Python
Raw Normal View History

2025-12-11 14:32:31 +08:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
配置服务测试脚本
用于验证配置服务的各项功能
"""
import requests
import json
import time
# 配置
SERVICE_HOST = "127.0.0.1"
SERVICE_PORT = 5000
BASE_URL = f"http://{SERVICE_HOST}:{SERVICE_PORT}"
def print_section(title):
"""打印分隔线"""
print("\n" + "="*60)
print(f" {title}")
print("="*60)
def test_health_check():
"""测试健康检查接口"""
print_section("测试1: 健康检查")
try:
response = requests.get(f"{BASE_URL}/api/health", timeout=3)
print(f"状态码: {response.status_code}")
if response.status_code == 200:
data = response.json()
print(f"服务状态: {data.get('status')}")
print(f"服务名称: {data.get('service')}")
print(f"服务版本: {data.get('version')}")
print("✓ 健康检查通过")
return True
else:
print("✗ 健康检查失败")
return False
except requests.exceptions.ConnectionError:
print("✗ 无法连接到配置服务")
print(" 请确保配置服务已启动: python config_service.py")
return False
except Exception as e:
print(f"✗ 错误: {e}")
return False
def test_get_config_text():
"""测试获取配置文件(文本格式)"""
print_section("测试2: 获取配置文件(文本格式)")
try:
response = requests.get(f"{BASE_URL}/api/config/text?path=config.json", timeout=5)
print(f"状态码: {response.status_code}")
if response.status_code == 200:
data = response.json()
if data.get("success"):
config_text = data.get("text", "")
print(f"配置文件路径: {data.get('path')}")
print(f"配置文件大小: {len(config_text)} 字节")
print(f"前100个字符: {config_text[:100]}...")
# 验证JSON格式
try:
json.loads(config_text)
print("✓ JSON格式正确")
except json.JSONDecodeError:
print("✗ JSON格式错误")
return False
print("✓ 获取配置文件成功")
return True
else:
print(f"✗ 获取失败: {data.get('error')}")
return False
else:
print("✗ 获取配置文件失败")
return False
except Exception as e:
print(f"✗ 错误: {e}")
return False
def test_get_config_json():
"""测试获取配置文件JSON格式"""
print_section("测试3: 获取配置文件JSON格式")
try:
response = requests.get(f"{BASE_URL}/api/config?path=config.json", timeout=5)
print(f"状态码: {response.status_code}")
if response.status_code == 200:
data = response.json()
if data.get("success"):
config = data.get("config", {})
print(f"配置文件路径: {data.get('path')}")
print(f"配置项数量: {len(config)}")
# 显示部分配置内容
if "influx" in config:
print(" - 包含 InfluxDB 配置")
if "placeholders" in config:
print(f" - 包含 {len(config.get('placeholders', {}))} 个占位符")
print("✓ 获取配置文件成功")
return config
else:
print(f"✗ 获取失败: {data.get('error')}")
return None
else:
print("✗ 获取配置文件失败")
return None
except Exception as e:
print(f"✗ 错误: {e}")
return None
def test_update_config_validation():
"""测试配置更新的JSON验证"""
print_section("测试4: JSON格式验证")
# 测试无效的JSON
invalid_json = '{"invalid": json content}'
try:
payload = {
"text": invalid_json,
"path": "test_invalid.json"
}
response = requests.post(f"{BASE_URL}/api/config/text", json=payload, timeout=5)
print(f"状态码: {response.status_code}")
if response.status_code == 400:
data = response.json()
print(f"预期的错误: {data.get('error')}")
print("✓ JSON验证功能正常")
return True
else:
print("✗ JSON验证没有正确工作")
return False
except Exception as e:
print(f"✗ 错误: {e}")
return False
def test_full_workflow():
"""测试完整的读取-修改-保存流程"""
print_section("测试5: 完整工作流程测试")
test_file = "test_config_temp.json"
# 1. 创建测试配置
print("\n步骤1: 创建测试配置文件")
test_config = {
"test": True,
"timestamp": time.time(),
"message": "这是一个测试配置"
}
try:
payload = {
"text": json.dumps(test_config, ensure_ascii=False, indent=2),
"path": test_file
}
response = requests.post(f"{BASE_URL}/api/config/text", json=payload, timeout=5)
if response.status_code == 200 and response.json().get("success"):
print("✓ 创建测试配置成功")
else:
print("✗ 创建测试配置失败")
return False
except Exception as e:
print(f"✗ 错误: {e}")
return False
# 2. 读取测试配置
print("\n步骤2: 读取测试配置文件")
try:
response = requests.get(f"{BASE_URL}/api/config?path={test_file}", timeout=5)
if response.status_code == 200:
data = response.json()
if data.get("success"):
config = data.get("config", {})
if config.get("test") == True and "message" in config:
print("✓ 读取测试配置成功")
print(f" 消息: {config.get('message')}")
else:
print("✗ 配置内容不匹配")
return False
else:
print("✗ 读取失败")
return False
else:
print("✗ 读取测试配置失败")
return False
except Exception as e:
print(f"✗ 错误: {e}")
return False
# 3. 修改测试配置
print("\n步骤3: 修改测试配置文件")
test_config["message"] = "配置已被修改"
test_config["modified"] = True
try:
payload = {
"text": json.dumps(test_config, ensure_ascii=False, indent=2),
"path": test_file
}
response = requests.post(f"{BASE_URL}/api/config/text", json=payload, timeout=5)
if response.status_code == 200 and response.json().get("success"):
print("✓ 修改测试配置成功")
else:
print("✗ 修改测试配置失败")
return False
except Exception as e:
print(f"✗ 错误: {e}")
return False
# 4. 验证修改结果
print("\n步骤4: 验证修改结果")
try:
response = requests.get(f"{BASE_URL}/api/config?path={test_file}", timeout=5)
if response.status_code == 200:
data = response.json()
if data.get("success"):
config = data.get("config", {})
if config.get("modified") == True and config.get("message") == "配置已被修改":
print("✓ 修改验证成功")
print(f" 新消息: {config.get('message')}")
else:
print("✗ 修改未生效")
return False
else:
print("✗ 验证失败")
return False
else:
print("✗ 验证请求失败")
return False
except Exception as e:
print(f"✗ 错误: {e}")
return False
print("\n✓ 完整工作流程测试通过")
print(f" 注意: 测试文件 {test_file} 已创建,您可以手动删除")
return True
def run_all_tests():
"""运行所有测试"""
print("\n" + "="*60)
print(" 配置服务功能测试")
print("="*60)
print(f"\n服务地址: {BASE_URL}")
print("开始测试...\n")
results = []
# 测试1: 健康检查
results.append(("健康检查", test_health_check()))
# 如果健康检查失败,不继续后续测试
if not results[0][1]:
print("\n" + "="*60)
print(" 配置服务未运行,无法继续测试")
print(" 请先启动配置服务: python config_service.py")
print("="*60)
return
# 测试2: 获取配置(文本)
results.append(("获取配置(文本)", test_get_config_text()))
# 测试3: 获取配置JSON
config = test_get_config_json()
results.append(("获取配置JSON", config is not None))
# 测试4: JSON验证
results.append(("JSON格式验证", test_update_config_validation()))
# 测试5: 完整工作流程
results.append(("完整工作流程", test_full_workflow()))
# 打印测试结果摘要
print_section("测试结果摘要")
total_tests = len(results)
passed_tests = sum(1 for _, result in results if result)
failed_tests = total_tests - passed_tests
for test_name, result in results:
status = "✓ 通过" if result else "✗ 失败"
print(f"{test_name:20s} - {status}")
print(f"\n总测试数: {total_tests}")
print(f"通过: {passed_tests}")
print(f"失败: {failed_tests}")
if failed_tests == 0:
print("\n🎉 所有测试通过!配置服务运行正常。")
else:
print(f"\n⚠️ 有 {failed_tests} 个测试失败,请检查配置服务。")
if __name__ == "__main__":
run_all_tests()