-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_profiling.py
More file actions
277 lines (212 loc) · 7.96 KB
/
test_profiling.py
File metadata and controls
277 lines (212 loc) · 7.96 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
from memevolve.utils.profiling import (
MemoryProfiler,
ProfileResult,
PerformanceReport,
profile_memory_operation,
benchmark_memory_system
)
from pathlib import Path
import time
import tempfile
import sys
# sys.path.insert(0, 'src') # No longer needed with package structure
# sys.path.insert(0, 'src') # No longer needed with package structure
class MockMemorySystem:
"""Mock memory system for testing."""
def __init__(self):
self.operations_called = []
def add_experience(self, experience):
"""Mock add experience."""
self.operations_called.append(("add_experience", experience))
time.sleep(0.01) # Simulate some work
return f"id_{len(self.operations_called)}"
def query_memory(self, query, **kwargs):
"""Mock query memory."""
self.operations_called.append(("query_memory", query, kwargs))
time.sleep(0.005) # Simulate some work
return [{"id": "result_1", "content": "test result"}]
def custom_operation(self, param):
"""Mock custom operation."""
self.operations_called.append(("custom_operation", param))
time.sleep(0.002) # Simulate some work
return f"result_{param}"
def test_memory_profiler_initialization():
"""Test profiler initialization."""
profiler = MemoryProfiler()
assert profiler is not None
assert len(profiler.results) == 0
def test_profile_operation_context_manager():
"""Test profiling with context manager."""
profiler = MemoryProfiler()
with profiler.profile_operation("test_operation", param1="value1"):
time.sleep(0.01)
assert len(profiler.results) == 1
result = profiler.results[0]
assert result.operation_name == "test_operation"
assert result.duration_seconds >= 0.01
assert result.metadata["param1"] == "value1"
def test_profile_function():
"""Test profiling a function call."""
profiler = MemoryProfiler()
def test_func(x, y=10):
time.sleep(0.005)
return x + y
result = profiler.profile_function(
test_func, 5, y=15, operation_name="add_func")
assert result == 20
assert len(profiler.results) == 1
assert profiler.results[0].operation_name == "add_func"
assert profiler.results[0].duration_seconds >= 0.005
def test_profile_memory_system_operation():
"""Test profiling memory system operations."""
profiler = MemoryProfiler()
memory_system = MockMemorySystem()
result = profiler.profile_memory_system_operation(
memory_system, "add_experience",
{"type": "lesson", "content": "test"}
)
assert result.startswith("id_")
assert len(profiler.results) == 1
assert profiler.results[0].operation_name == "memory_system.add_experience"
def test_generate_report_empty():
"""Test generating report with no data."""
profiler = MemoryProfiler()
report = profiler.generate_report("test_report")
assert report.report_id == "test_report"
assert report.total_operations == 0
assert report.total_duration == 0.0
assert "No profiling data available" in report.recommendations
def test_generate_report_with_data():
"""Test generating report with profiling data."""
profiler = MemoryProfiler()
# Add some mock results
profiler.results = [
ProfileResult(
operation_name="fast_op",
start_time="2024-01-01T00:00:00Z",
end_time="2024-01-01T00:00:01Z",
duration_seconds=0.1
),
ProfileResult(
operation_name="slow_op",
start_time="2024-01-01T00:00:00Z",
end_time="2024-01-01T00:00:05Z",
duration_seconds=10.0 # Make this very slow to trigger bottleneck
),
ProfileResult(
operation_name="slow_op",
start_time="2024-01-01T00:00:00Z",
end_time="2024-01-01T00:00:03Z",
duration_seconds=8.0
)
]
report = profiler.generate_report()
assert report.total_operations == 3
assert abs(report.total_duration - 18.1) < 0.001
assert abs(report.average_operation_time - 6.033) < 0.01
assert "fast_op" in report.operation_breakdown
assert "slow_op" in report.operation_breakdown
# Bottleneck detection depends on the threshold logic
def test_clear_results():
"""Test clearing profiling results."""
profiler = MemoryProfiler()
with profiler.profile_operation("test"):
pass
assert len(profiler.results) == 1
profiler.clear_results()
assert len(profiler.results) == 0
def test_export_profile_stats():
"""Test exporting profile statistics."""
profiler = MemoryProfiler()
with profiler.profile_operation("test_export"):
time.sleep(0.001)
with tempfile.TemporaryDirectory() as temp_dir:
filepath = Path(temp_dir) / "profile_stats.txt"
success = profiler.export_profile_stats(filepath)
assert success
assert filepath.exists()
content = filepath.read_text()
assert len(content) > 0
assert "function calls" in content.lower()
def test_run_benchmark():
"""Test running benchmark suite."""
profiler = MemoryProfiler()
memory_system = MockMemorySystem()
operations = [
{
"name": "add_lesson",
"type": "add_experience",
"args": [{"type": "lesson", "content": "test lesson"}]
},
{
"name": "query_test",
"type": "query_memory",
"args": ["test query"],
"kwargs": {"top_k": 5}
}
]
report = profiler.run_benchmark(memory_system, operations, iterations=1)
assert report.total_operations == 2
assert len(memory_system.operations_called) == 2
assert report.operation_breakdown["memory_system.add_experience"]["count"] == 1
assert report.operation_breakdown["memory_system.query_memory"]["count"] == 1
def test_convenience_functions():
"""Test convenience profiling functions."""
memory_system = MockMemorySystem()
# Test profile_memory_operation
result = profile_memory_operation(
memory_system, "add_experience",
{"type": "lesson", "content": "test"}
)
assert result.startswith("id_")
# Test benchmark_memory_system
operations = [
{
"name": "simple_add",
"type": "add_experience",
"args": [{"type": "lesson", "content": "benchmark test"}]
}
]
with tempfile.TemporaryDirectory() as temp_dir:
export_path = Path(temp_dir) / "benchmark_stats.txt"
report = benchmark_memory_system(
memory_system, operations, iterations=1,
export_path=export_path
)
assert report.total_operations == 1
assert export_path.exists()
def test_profile_result_to_dict():
"""Test ProfileResult serialization."""
result = ProfileResult(
operation_name="test_op",
start_time="2024-01-01T00:00:00Z",
end_time="2024-01-01T00:00:01Z",
duration_seconds=1.5,
memory_usage_mb=50.0,
cpu_usage_percent=25.0,
metadata={"key": "value"}
)
data = result.to_dict()
assert data["operation_name"] == "test_op"
assert data["duration_seconds"] == 1.5
assert data["memory_usage_mb"] == 50.0
assert data["cpu_usage_percent"] == 25.0
assert data["metadata"]["key"] == "value"
def test_performance_report_to_dict():
"""Test PerformanceReport serialization."""
report = PerformanceReport(
report_id="test_report",
timestamp="2024-01-01T00:00:00Z",
total_operations=10,
total_duration=5.0,
average_operation_time=0.5,
operation_breakdown={"op1": {"count": 5, "avg_time": 0.3}},
bottlenecks=["op1 is slow"],
recommendations=["Optimize op1"]
)
data = report.to_dict()
assert data["report_id"] == "test_report"
assert data["total_operations"] == 10
assert data["total_duration"] == 5.0
assert len(data["bottlenecks"]) == 1
assert len(data["recommendations"]) == 1