-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_imports.py
More file actions
225 lines (188 loc) · 8.08 KB
/
test_imports.py
File metadata and controls
225 lines (188 loc) · 8.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
#!/usr/bin/env python3
"""
Test script to validate all import scenarios for Python Complexity Analyzer
This script tests that the package can be used in all the intended ways.
"""
import sys
import os
import subprocess
from pathlib import Path
def test_package_imports():
"""Test importing the package as a library."""
print("🧪 Testing package imports...")
try:
# Add src to path
src_path = Path(__file__).parent / "src"
sys.path.insert(0, str(src_path))
# Test main package import
import python_complexity
print(f"✅ Package import: python_complexity v{python_complexity.__version__}")
# Test individual module imports
from python_complexity import PerformanceAnalyzer, ComplexityAnalyzer, BenchmarkRunner
print("✅ Individual class imports work")
# Test that classes can be instantiated
perf = PerformanceAnalyzer()
comp = ComplexityAnalyzer()
bench = BenchmarkRunner()
print("✅ Class instantiation works")
return True
except Exception as e:
print(f"❌ Package imports failed: {e}")
return False
def test_direct_script_execution():
"""Test running scripts directly."""
print("\n🧪 Testing direct script execution...")
scripts_to_test = [
"src/python_complexity/main_simple.py",
"src/python_complexity/main.py"
]
success_count = 0
for script in scripts_to_test:
try:
# Test that script can be imported (which tests the import logic)
script_path = Path(__file__).parent / script
if script_path.exists():
# Use a subprocess to test import without hanging on GUI
result = subprocess.run([
sys.executable, "-c",
f"import sys; sys.path.insert(0, '{script_path.parent}'); "
f"import {script_path.stem}; print('Import successful')"
], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
print(f"✅ {script} can be imported and executed")
success_count += 1
else:
print(f"❌ {script} import failed: {result.stderr}")
else:
print(f"❌ {script} not found")
except subprocess.TimeoutExpired:
print(f"✅ {script} started successfully (GUI timeout expected)")
success_count += 1
except Exception as e:
print(f"❌ {script} execution test failed: {e}")
return success_count == len(scripts_to_test)
def test_module_execution():
"""Test running as module with python -m."""
print("\n🧪 Testing module execution...")
try:
# Test that __main__.py can be imported
src_path = Path(__file__).parent / "src"
sys.path.insert(0, str(src_path))
from python_complexity.__main__ import main
print("✅ __main__.py imports work")
# Test actual module execution (without GUI hanging)
result = subprocess.run([
sys.executable, "-c",
f"import sys; sys.path.insert(0, '{src_path}'); "
f"from python_complexity.__main__ import main; print('Module execution ready')"
], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
print("✅ Module execution entry point works")
return True
else:
print(f"❌ Module execution failed: {result.stderr}")
return False
except Exception as e:
print(f"❌ Module execution test failed: {e}")
return False
def test_import_fallbacks():
"""Test that import fallbacks work correctly."""
print("\n🧪 Testing import fallback mechanisms...")
# Test relative imports work (package context)
try:
src_path = Path(__file__).parent / "src"
sys.path.insert(0, str(src_path))
# This should use relative imports
from python_complexity.main_simple import SimpleResultsPanel
print("✅ Relative imports work in package context")
# Test absolute imports work (direct script context)
script_dir = src_path / "python_complexity"
sys.path.insert(0, str(script_dir))
# Import modules directly (simulating script execution)
import performance_analyzer
import complexity_analyzer
import benchmark_runner
print("✅ Absolute imports work in script context")
return True
except Exception as e:
print(f"❌ Import fallback test failed: {e}")
return False
def test_all_entry_points():
"""Test all the different ways to run the application."""
print("\n🧪 Testing all entry points...")
entry_points = [
("Package module", "python -m src.python_complexity"),
("Direct script (simple)", "python src/python_complexity/main_simple.py"),
("Direct script (full)", "python src/python_complexity/main.py"),
]
success_count = 0
for name, command in entry_points:
try:
# Replace 'python' with actual Python executable
cmd_parts = command.split()
cmd_parts[0] = sys.executable
# Quick test that doesn't hang on GUI
result = subprocess.run(
cmd_parts + ["--help"],
capture_output=True, text=True, timeout=5,
cwd=Path(__file__).parent
)
# If --help doesn't work, try importing the module
if result.returncode != 0:
test_cmd = [
sys.executable, "-c",
"import sys; " +
("sys.path.insert(0, 'src'); import python_complexity" if "python_complexity" in command
else f"sys.path.insert(0, '{Path(cmd_parts[1]).parent}'); import {Path(cmd_parts[1]).stem}")
]
result = subprocess.run(test_cmd, capture_output=True, text=True, timeout=5)
if result.returncode == 0:
print(f"✅ {name}: {command}")
success_count += 1
else:
print(f"❌ {name}: {command} - {result.stderr.strip()}")
except subprocess.TimeoutExpired:
print(f"✅ {name}: {command} (started successfully, GUI timeout expected)")
success_count += 1
except Exception as e:
print(f"❌ {name}: {command} - {e}")
return success_count == len(entry_points)
def main():
"""Run all import tests."""
print("🔧 Python Complexity Analyzer - Import Test Suite")
print("=" * 60)
tests = [
("Package Imports", test_package_imports),
("Direct Script Execution", test_direct_script_execution),
("Module Execution", test_module_execution),
("Import Fallbacks", test_import_fallbacks),
("Entry Points", test_all_entry_points),
]
passed = 0
total = len(tests)
for test_name, test_func in tests:
try:
if test_func():
passed += 1
print(f"✅ {test_name}: PASSED")
else:
print(f"❌ {test_name}: FAILED")
except Exception as e:
print(f"❌ {test_name}: ERROR - {e}")
print()
print("=" * 60)
print(f"📊 Test Results: {passed}/{total} tests passed")
if passed == total:
print("🎉 All import scenarios work correctly!")
print("\n📋 The package supports:")
print(" • Running as a package: python -m python_complexity")
print(" • Direct script execution: python main_simple.py")
print(" • Library imports: from python_complexity import ...")
print(" • Fallback imports for both contexts")
return True
else:
print("⚠️ Some import scenarios need attention.")
return False
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)