-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_analyzer.py
More file actions
330 lines (255 loc) · 9.08 KB
/
test_analyzer.py
File metadata and controls
330 lines (255 loc) · 9.08 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#!/usr/bin/env python3
"""
Test script for the Advanced Flow Analyzer
"""
import os
import sys
import tempfile
import shutil
from pathlib import Path
# Add current directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from flow import ProjectFlowAnalyzer, EnhancedFlowExtractor, BehavioralPatternExtractor
def create_sample_project():
"""Create a sample project for testing."""
project_dir = tempfile.mkdtemp(prefix="test_project_")
# Sample module 1: Simple functions
module1 = '''
def process_data(data):
"""Process input data."""
if not data:
return None
result = []
for item in data:
if item > 0:
result.append(item * 2)
return result
def validate_data(data):
"""Validate input data."""
return isinstance(data, list) and all(isinstance(x, int) for x in data)
'''
# Sample module 2: Class with state machine
module2 = '''
class ConnectionState:
"""State machine for connection states."""
def __init__(self):
self.state = "disconnected"
self.retry_count = 0
def connect(self):
"""Transition to connecting state."""
if self.state == "disconnected":
self.state = "connecting"
return True
return False
def connected(self):
"""Transition to connected state."""
if self.state == "connecting":
self.state = "connected"
self.retry_count = 0
return True
return False
def disconnect(self):
"""Transition to disconnected state."""
self.state = "disconnected"
return True
def failed(self):
"""Handle connection failure."""
if self.state == "connecting":
self.retry_count += 1
if self.retry_count > 3:
self.state = "disconnected"
self.retry_count = 0
return True
return False
'''
# Sample module 3: Recursive functions
module3 = '''
def factorial(n):
"""Calculate factorial recursively."""
if n <= 1:
return 1
return n * factorial(n - 1)
def fibonacci(n):
"""Calculate Fibonacci number recursively."""
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def tree_traversal(node):
"""Traverse tree structure."""
if not node:
return []
result = [node.value]
result.extend(tree_traversal(node.left))
result.extend(tree_traversal(node.right))
return result
'''
# Sample test file
test_file = '''
import unittest
import sys
import os
# Add modules to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from module1 import process_data, validate_data
from module2 import ConnectionState
from module3 import factorial
class TestProject(unittest.TestCase):
def test_process_data(self):
"""Test data processing."""
self.assertEqual(process_data([1, 2, 3]), [2, 4, 6])
self.assertIsNone(process_data([]))
def test_validate_data(self):
"""Test data validation."""
self.assertTrue(validate_data([1, 2, 3]))
self.assertFalse(validate_data("not a list"))
def test_connection_state(self):
"""Test state machine."""
conn = ConnectionState()
self.assertEqual(conn.state, "disconnected")
conn.connect()
self.assertEqual(conn.state, "connecting")
conn.connected()
self.assertEqual(conn.state, "connected")
def test_factorial(self):
"""Test recursive factorial."""
self.assertEqual(factorial(5), 120)
self.assertEqual(factorial(0), 1)
if __name__ == "__main__":
unittest.main()
'''
# Write files
Path(project_dir, "module1.py").write_text(module1)
Path(project_dir, "module2.py").write_text(module2)
Path(project_dir, "module3.py").write_text(module3)
Path(project_dir, "tests").mkdir()
Path(project_dir, "tests", "test_project.py").write_text(test_file)
return project_dir
def test_static_analysis():
"""Test static analysis functionality."""
print("\n=== Testing Static Analysis ===")
project_dir = create_sample_project()
try:
analyzer = ProjectFlowAnalyzer(mode='static')
analyzer.analyze_project(project_dir, 'test_output_static')
# Check outputs
assert os.path.exists('test_output_static/system_analysis.yaml')
assert os.path.exists('test_output_static/analysis_report.md')
print("✓ Static analysis test passed")
except Exception as e:
print(f"✗ Static analysis test failed: {e}")
import traceback
traceback.print_exc()
finally:
shutil.rmtree(project_dir)
if os.path.exists('test_output_static'):
shutil.rmtree('test_output_static')
def test_pattern_extraction():
"""Test behavioral pattern extraction."""
print("\n=== Testing Pattern Extraction ===")
project_dir = create_sample_project()
try:
analyzer = ProjectFlowAnalyzer(mode='behavioral')
analyzer.analyze_project(project_dir, 'test_output_patterns')
# Check if patterns were detected
assert len(analyzer.patterns) > 0
# Check for specific patterns
pattern_types = [p.type for p in analyzer.patterns]
assert 'sequential' in pattern_types
assert 'recursive' in pattern_types
assert 'state_machine' in pattern_types
print(f"✓ Detected {len(analyzer.patterns)} patterns:")
for p in analyzer.patterns:
print(f" - {p.name} ({p.type}, confidence: {p.confidence:.2f})")
except Exception as e:
print(f"✗ Pattern extraction test failed: {e}")
import traceback
traceback.print_exc()
finally:
shutil.rmtree(project_dir)
if os.path.exists('test_output_patterns'):
shutil.rmtree('test_output_patterns')
def test_hybrid_analysis():
"""Test hybrid static + dynamic analysis."""
print("\n=== Testing Hybrid Analysis ===")
project_dir = create_sample_project()
try:
analyzer = ProjectFlowAnalyzer(mode='hybrid')
analyzer.analyze_project(project_dir, 'test_output_hybrid')
# Check all outputs
outputs = [
'system_analysis.yaml',
'system_flow.mmd',
'system_flow.png',
'diagram_data.json',
'analysis_report.md'
]
for output in outputs:
assert os.path.exists(f'test_output_hybrid/{output}')
print("✓ Hybrid analysis test passed")
print("Generated files:")
for output in outputs:
size = os.path.getsize(f'test_output_hybrid/{output}')
print(f" - {output} ({size} bytes)")
except Exception as e:
print(f"✗ Hybrid analysis test failed: {e}")
import traceback
traceback.print_exc()
finally:
shutil.rmtree(project_dir)
if os.path.exists('test_output_hybrid'):
shutil.rmtree('test_output_hybrid')
def test_llm_prompt_generation():
"""Test LLM prompt generation."""
print("\n=== Testing LLM Prompt Generation ===")
project_dir = create_sample_project()
try:
analyzer = ProjectFlowAnalyzer(mode='reverse')
analyzer.analyze_project(project_dir, 'test_output_llm')
# Read generated prompt
with open('test_output_llm/system_analysis_prompt.md', 'r') as f:
prompt = f.read()
# Check prompt structure
required_sections = [
'# System Behavioral Analysis',
'## Overview',
'## Call Graph Structure',
'## Behavioral Patterns',
'## Data Flow Insights',
'## Reverse Engineering Guidelines'
]
for section in required_sections:
assert section in prompt, f"Missing section: {section}"
print("✓ LLM prompt generation test passed")
print(f"Prompt length: {len(prompt)} characters")
except Exception as e:
print(f"✗ LLM prompt test failed: {e}")
import traceback
traceback.print_exc()
finally:
shutil.rmtree(project_dir)
if os.path.exists('test_output_llm'):
shutil.rmtree('test_output_llm')
def main():
"""Run all tests."""
print("Running Advanced Flow Analyzer Tests")
print("=" * 50)
# Check dependencies
try:
import networkx
import matplotlib
import numpy
import yaml
print("✓ All dependencies installed")
except ImportError as e:
print(f"✗ Missing dependency: {e}")
print("Please run: pip install -r requirements.txt")
return
# Run tests
test_static_analysis()
test_pattern_extraction()
test_hybrid_analysis()
test_llm_prompt_generation()
print("\n" + "=" * 50)
print("Test suite complete!")
if __name__ == "__main__":
main()