-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_visualization.py
More file actions
234 lines (194 loc) · 6.22 KB
/
test_visualization.py
File metadata and controls
234 lines (194 loc) · 6.22 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
"""
可视化组件测试脚本
直接测试可视化功能
"""
import sys
import os
# 设置路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)
# 直接导入
from my_utils.profiling.visualization.charts import ChartConfig, ChartJsRenderer, create_chart_renderer
from my_utils.profiling.visualization.transformers import DataTransformer, MetricEvent
from my_utils.profiling.visualization.layouts import LayoutBuilder, Finding, Recommendation, AnalysisReport, Severity
from my_utils.profiling.visualization.html_generator import HTMLReportGenerator
def test_basic_chart():
"""测试基本图表"""
print("=" * 60)
print("测试1: 基本图表")
print("=" * 60)
# 创建渲染器
renderer = create_chart_renderer()
# 创建图表配置
config = ChartConfig(
chart_type="line",
title="Performance Over Time",
data={
"labels": [1, 2, 3, 4, 5],
"datasets": [{
"label": "Loss",
"data": [2.5, 2.1, 1.8, 1.5, 1.3],
"borderColor": "rgb(75, 192, 192)",
"backgroundColor": "rgba(75, 192, 192, 0.2)",
"fill": True,
}]
}
)
# 渲染
html = renderer.render(config)
print(f"[OK] 图表HTML已生成 (长度: {len(html)} 字符)")
# 保存
with open("test_chart.html", "w", encoding="utf-8") as f:
f.write(f"""
<!DOCTYPE html>
<html>
<head>
<title>Chart Test</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
</head>
<body>
<h1>Performance Chart</h1>
{html}
</body>
</html>
""")
print("[OK] 已保存到: test_chart.html")
def test_data_transformer():
"""测试数据转换器"""
print("\n" + "=" * 60)
print("测试2: 数据转换器")
print("=" * 60)
# 创建模拟数据
import time
events = []
for step in range(10):
events.append(MetricEvent(
timestamp=time.time(),
name="loss",
value=2.0 - step * 0.1,
unit="",
tags={"step": str(step)}
))
# 使用转换器
transformer = DataTransformer()
# 时间序列
time_series = transformer.to_time_series(events, "loss")
print(f"[OK] 时间序列: {len(time_series['labels'])} 个数据点")
# 统计
stats = transformer.compute_statistics(events)
print(f"[OK] 统计: {len(stats)} 个指标")
print(f" - loss: mean={stats[0]['mean']:.3f}, std={stats[0]['std']:.3f}")
def test_layout_builder():
"""测试布局构建器"""
print("\n" + "=" * 60)
print("测试3: 布局构建器")
print("=" * 60)
builder = LayoutBuilder()
builder.add_header(title="Test Report", subtitle="Generated by test script")
builder.add_summary(
summary="Test summary text",
score=85,
details={"Test1": "Value1", "Test2": "Value2"}
)
html = builder.build()
print(f"[OK] HTML已生成 (长度: {len(html)} 字符)")
with open("test_layout.html", "w", encoding="utf-8") as f:
f.write(html)
print("[OK] 已保存到: test_layout.html")
def test_full_report():
"""测试完整报告生成"""
print("\n" + "=" * 60)
print("测试4: 完整报告")
print("=" * 60)
# 创建模拟数据
import time
events = []
for step in range(10):
events.append(MetricEvent(
timestamp=time.time(),
name="loss",
value=2.0 * (0.9 ** step),
unit="",
tags={"step": str(step)}
))
events.append(MetricEvent(
timestamp=time.time(),
name="timer.forward",
value=100 + step * 2,
unit="ms",
tags={"step": str(step)}
))
events.append(MetricEvent(
timestamp=time.time(),
name="memory.allocated",
value=8.0 + step * 0.01,
unit="GB",
tags={"step": str(step)}
))
# 创建报告
report = AnalysisReport(
metadata={"event_count": len(events)},
findings=[
Finding(
id="test1",
title="Test Finding",
description="This is a test finding",
severity=Severity.HIGH,
category="test",
evidence={"value": 0.5},
affected_components=["test"],
metrics={}
)
],
recommendations=[
Recommendation(
id="rec1",
title="Test Recommendation",
description="This is a test recommendation",
priority=8,
estimated_impact="10%",
effort="low",
actions=["Action 1", "Action 2"],
references=[]
)
],
summary="Test summary",
overall_score=75.0
)
# 生成报告
generator = HTMLReportGenerator()
html = generator.generate(
report=report,
events=events,
output_path="test_full_report.html"
)
print(f"[OK] 完整报告已生成")
print(f" 事件数: {len(events)}")
print(f" 发现数: {len(report.findings)}")
print(f" 建议数: {len(report.recommendations)}")
print(f" 得分: {report.overall_score:.0f}/100")
print("[OK] 已保存到: test_full_report.html")
def main():
print("\n")
print("╔" + "═" * 58 + "╗")
print("║" + " " * 15 + "可视化组件测试" + " " * 29 + "║")
print("╚" + "═" * 58 + "╝")
try:
test_basic_chart()
test_data_transformer()
test_layout_builder()
test_full_report()
print("\n" + "=" * 60)
print("[OK] 所有测试通过!")
print("=" * 60)
print("\n生成的文件:")
print(" - test_chart.html")
print(" - test_layout.html")
print(" - test_full_report.html")
print("\n在浏览器中打开这些文件查看结果!")
except Exception as e:
print(f"\n[FAIL] 测试失败: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()