-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_system.py
More file actions
237 lines (189 loc) · 7.23 KB
/
Copy pathtest_system.py
File metadata and controls
237 lines (189 loc) · 7.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""
GhostBridge 完整测试脚本
测试基础功能和 AI 功能
"""
import requests
import json
from PIL import Image, ImageDraw
import base64
import io
# API 端点
BASE_URL = "http://127.0.0.1:8000"
def create_test_image():
"""创建测试图像(模拟登录界面)"""
test_image = Image.new('RGB', (600, 400), color='white')
draw = ImageDraw.Draw(test_image)
# 绘制输入框
draw.rectangle([100, 100, 500, 140], outline='gray', width=2)
draw.rectangle([100, 160, 500, 200], outline='gray', width=2)
# 绘制按钮
draw.rectangle([100, 240, 250, 280], fill='blue', outline='blue')
draw.rectangle([270, 240, 420, 280], fill='green', outline='green')
# 转换为 base64
buffer = io.BytesIO()
test_image.save(buffer, format='PNG')
return base64.b64encode(buffer.getvalue()).decode('utf-8')
def test_health_check():
"""测试健康检查"""
print("=" * 50)
print("1. 健康检查测试")
print("=" * 50)
try:
response = requests.get(f"{BASE_URL}/health")
if response.status_code == 200:
print("✅ 健康检查通过")
print(f" 响应: {response.json()}")
return True
else:
print(f"❌ 健康检查失败: {response.status_code}")
return False
except Exception as e:
print(f"❌ 连接失败: {e}")
return False
def test_root_endpoint():
"""测试根端点"""
print("\n" + "=" * 50)
print("2. 根端点测试")
print("=" * 50)
try:
response = requests.get(f"{BASE_URL}/")
if response.status_code == 200:
print("✅ 根端点正常")
print(f" 响应: {response.json()}")
return True
else:
print(f"❌ 根端点失败: {response.status_code}")
return False
except Exception as e:
print(f"❌ 连接失败: {e}")
return False
def test_image_analysis():
"""测试图像分析"""
print("\n" + "=" * 50)
print("3. 图像分析测试")
print("=" * 50)
try:
image_base64 = create_test_image()
payload = {
"image": image_base64,
"command": None
}
response = requests.post(f"{BASE_URL}/api/analyze", json=payload)
if response.status_code == 200:
result = response.json()
print("✅ 图像分析成功")
print(f" 状态: {result['status']}")
print(f" 检测到元素数量: {result['total']}")
print(f" 元素类型: {[e['type'] for e in result['elements']]}")
if result['total'] > 0:
print("\n 元素详情:")
for i, e in enumerate(result['elements'], 1):
print(f" {i}. {e['type']}: 位置({e['x']}, {e['y']}), 尺寸{e['width']}x{e['height']}, 置信度{e['confidence']:.2f}")
return True
else:
print(f"❌ 图像分析失败: {response.status_code}")
print(f" 响应: {response.text}")
return False
except Exception as e:
print(f"❌ 请求失败: {e}")
return False
def test_command_processing():
"""测试命令处理"""
print("\n" + "=" * 50)
print("4. 命令处理测试")
print("=" * 50)
try:
image_base64 = create_test_image()
# 先分析图像获取元素
analyze_payload = {
"image": image_base64,
"command": None
}
analyze_response = requests.post(f"{BASE_URL}/api/analyze", json=analyze_payload)
if analyze_response.status_code != 200:
print("❌ 无法分析图像")
return False
elements = analyze_response.json()['elements']
# 测试不同命令
commands = ["login", "highlight_all"]
for cmd in commands:
print(f"\n 测试命令: {cmd}")
payload = {
"image": image_base64,
"command": cmd
}
response = requests.post(f"{BASE_URL}/api/analyze", json=payload)
if response.status_code == 200:
result = response.json()
print(f" ✅ 命令 '{cmd}' 执行成功")
print(f" 生成动作数量: {len(result.get('actions', []))}")
if result.get('actions'):
print(" 动作列表:")
for i, action in enumerate(result['actions'], 1):
print(f" {i}. {action['type']}: {action.get('description', 'N/A')}")
else:
print(f" ❌ 命令 '{cmd}' 执行失败: {response.status_code}")
return True
except Exception as e:
print(f"❌ 请求失败: {e}")
return False
def test_api_key_config():
"""检查 API key 配置"""
print("\n" + "=" * 50)
print("5. API Key 配置检查")
print("=" * 50)
import os
from dotenv import load_dotenv
load_dotenv()
api_keys = {
"QWEN_API_KEY": os.getenv("QWEN_API_KEY"),
"OPENAI_API_KEY": os.getenv("OPENAI_API_KEY"),
"GLM_API_KEY": os.getenv("GLM_API_KEY")
}
for key_name, key_value in api_keys.items():
if key_value:
print(f"✅ {key_name}: 已配置 (长度: {len(key_value)})")
else:
print(f"❌ {key_name}: 未配置")
configured_count = sum(1 for v in api_keys.values() if v)
if configured_count == 0:
print("\n⚠️ 未配置任何 API Key")
print(" 基础功能可用,但 AI 功能需要配置 API Key")
print(" 请在 .env 文件中配置至少一个 API Key")
else:
print(f"\n✅ 已配置 {configured_count} 个 API Key")
print(" AI 功能可用")
return configured_count > 0
def main():
"""运行所有测试"""
print("\n" + "=" * 50)
print("GhostBridge 系统测试")
print("=" * 50)
results = []
# 运行测试
results.append(("健康检查", test_health_check()))
results.append(("根端点", test_root_endpoint()))
results.append(("图像分析", test_image_analysis()))
results.append(("命令处理", test_command_processing()))
api_configured = test_api_key_config()
# 总结
print("\n" + "=" * 50)
print("测试总结")
print("=" * 50)
passed = sum(1 for _, result in results if result)
total = len(results)
for test_name, result in results:
status = "✅ 通过" if result else "❌ 失败"
print(f"{test_name}: {status}")
print(f"\n通过率: {passed}/{total} ({passed/total*100:.1f}%)")
if passed == total:
print("\n🎉 所有测试通过!系统运行正常。")
else:
print(f"\n⚠️ {total - passed} 个测试失败,请检查系统配置。")
if api_configured:
print("\n✅ AI 功能已配置,可以进行 AI 测试")
else:
print("\n⚠️ AI 功能未配置,仅基础功能可用")
print(" 如需使用 AI 功能,请在 .env 文件中配置 API Key")
if __name__ == "__main__":
main()