-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_ghostbridge.py
More file actions
250 lines (201 loc) · 7.71 KB
/
Copy pathtest_ghostbridge.py
File metadata and controls
250 lines (201 loc) · 7.71 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
238
239
240
241
242
243
244
245
246
247
248
249
250
"""
GhostBridge 系统测试脚本
测试感知、执行和生成功能
"""
import sys
from pathlib import Path
# 添加 GhostBridge 到 Python 路径
ghostbridge_path = Path(r"C:\Users\ljy33\Desktop\GhostBridge\GhostBridge")
if str(ghostbridge_path) not in sys.path:
sys.path.insert(0, str(ghostbridge_path))
from ghostbridge.perception import add_tags_to_image, identify_element
from ghostbridge.generator import parse_har, build_system_prompt, clean_api_with_llm, generate_openapi_yaml
def test_perception():
"""测试感知层功能"""
print("=" * 60)
print("1. 测试感知层 (Perception)")
print("=" * 60)
# 创建一个简单的测试图像
from PIL import Image, ImageDraw
test_image_path = Path("test_image.png")
img = Image.new('RGB', (800, 600), color='white')
draw = ImageDraw.Draw(img)
# 绘制一些 UI 元素
draw.rectangle([100, 100, 300, 140], outline='gray', width=2)
draw.rectangle([100, 160, 300, 200], outline='gray', width=2)
draw.rectangle([100, 240, 250, 280], fill='blue', outline='blue')
img.save(test_image_path)
print(f"✓ 创建测试图像: {test_image_path}")
# 测试添加标签
try:
tagged_image = add_tags_to_image(str(test_image_path))
print(f"✓ 添加标签成功: {tagged_image}")
# 检查生成的文件
tagged_path = Path(tagged_image)
meta_path = tagged_path.with_name(tagged_path.stem.replace("_tagged", "_tags.json"))
if meta_path.exists():
print(f"✓ 元数据文件已生成: {meta_path}")
# 读取并显示元数据
import json
meta = json.loads(meta_path.read_text(encoding='utf-8'))
print(f" - 标签数量: {len(meta.get('tags', []))}")
for tag in meta.get('tags', []):
print(f" 标签 {tag['id']}: 中心({tag['center'][0]}, {tag['center'][1]})")
# 测试元素识别
result = identify_element(tagged_image, "登录按钮")
print(f"✓ 元素识别结果: tag_id={result['tag_id']}, center={result['center']}")
return True
except Exception as e:
print(f"✗ 感知层测试失败: {e}")
import traceback
traceback.print_exc()
return False
def test_generator():
"""测试生成层功能"""
print("\n" + "=" * 60)
print("2. 测试生成层 (Generator)")
print("=" * 60)
# 测试 System Prompt 构建
try:
system_prompt = build_system_prompt()
print(f"✓ System Prompt 构建成功")
print(f" 长度: {len(system_prompt)} 字符")
print(f" 前100字符: {system_prompt[:100]}...")
# 测试 HAR 解析
# 创建一个模拟 HAR 文件
sample_har = {
"log": {
"entries": [
{
"request": {
"url": "https://example.com/api/user",
"method": "POST",
"queryString": [],
"postData": {
"text": '{"name":"test"}'
}
},
"response": {
"content": {
"mimeType": "application/json"
}
}
},
{
"request": {
"url": "https://example.com/style.css",
"method": "GET",
"queryString": [],
"postData": {}
},
"response": {
"content": {
"mimeType": "text/css"
}
}
}
]
}
}
har_path = Path("test_session.har")
import json
har_path.write_text(json.dumps(sample_har), encoding='utf-8')
print(f"✓ 创建测试 HAR 文件: {har_path}")
# 解析 HAR
requests = parse_har(str(har_path))
print(f"✓ HAR 解析成功,提取 {len(requests)} 个请求")
for req in requests:
print(f" - {req['method']} {req['url'][:50]}...")
# 测试 LLM 清洗
for req in requests:
yaml_snippet = clean_api_with_llm(req)
print(f"\n✓ LLM 清洗结果:")
print(yaml_snippet[:200] + "...")
# 测试生成 OpenAPI YAML
output_yaml = Path("test_openapi.yaml")
generate_openapi_yaml(str(har_path), str(output_yaml))
print(f"\n✓ OpenAPI YAML 生成成功: {output_yaml}")
if output_yaml.exists():
content = output_yaml.read_text(encoding='utf-8')
print(f" 文件大小: {len(content)} 字节")
print(f" 前200字符: {content[:200]}...")
return True
except Exception as e:
print(f"✗ 生成层测试失败: {e}")
import traceback
traceback.print_exc()
return False
def test_operator():
"""测试执行层功能(需要浏览器)"""
print("\n" + "=" * 60)
print("3. 测试执行层 (Operator)")
print("=" * 60)
try:
from ghostbridge.operator import LegacySystemOperator
print("ℹ️ 执行层需要 Playwright 浏览器")
print("ℹ️ 这是一个模拟测试,不会实际启动浏览器")
# 测试创建 Operator 实例
operator = LegacySystemOperator(headless=True)
print("✓ LegacySystemOperator 实例创建成功")
print(f" - headless: {operator.headless}")
# 检查依赖
try:
import playwright
print("✓ Playwright 已安装")
except ImportError:
print("✗ Playwright 未安装,需要运行: pip install playwright")
print("✗ 然后运行: playwright install chromium")
return False
return True
except Exception as e:
print(f"✗ 执行层测试失败: {e}")
import traceback
traceback.print_exc()
return False
def cleanup():
"""清理测试文件"""
print("\n" + "=" * 60)
print("清理测试文件")
print("=" * 60)
test_files = [
"test_image.png",
"test_image_tagged.png",
"test_image_tags.json",
"test_session.har",
"test_openapi.yaml",
"__temp_record.har"
]
for file in test_files:
path = Path(file)
if path.exists():
path.unlink()
print(f"✓ 删除: {file}")
def main():
"""运行所有测试"""
print("\n" + "=" * 60)
print("GhostBridge 系统测试")
print("=" * 60)
results = []
# 运行测试
results.append(("感知层", test_perception()))
results.append(("生成层", test_generator()))
results.append(("执行层", test_operator()))
# 总结
print("\n" + "=" * 60)
print("测试总结")
print("=" * 60)
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} 个测试失败")
# 清理
cleanup()
print("\n测试完成!")
if __name__ == "__main__":
main()