-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_setup.py
More file actions
191 lines (148 loc) · 5.68 KB
/
test_setup.py
File metadata and controls
191 lines (148 loc) · 5.68 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
"""Test script to verify the extraction pipeline"""
import os
import sys
import logging
from pathlib import Path
# Add project to path
sys.path.insert(0, str(Path(__file__).parent))
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def test_imports():
"""Test if all modules can be imported"""
logger.info("Testing imports...")
try:
from app.models import DatabaseManager, init_db, get_db
logger.info("✓ Models imported successfully")
from app.parser import PDFExtractor
logger.info("✓ Parser imported successfully")
from app.extraction_service import ExtractionService
logger.info("✓ Extraction service imported successfully")
from app.routes import bp
logger.info("✓ Routes imported successfully")
from app import create_app
logger.info("✓ App factory imported successfully")
return True
except ImportError as e:
logger.error(f"✗ Import failed: {e}")
return False
def test_database():
"""Test database initialization"""
logger.info("Testing database...")
try:
from app.models import init_db, get_db, DatabaseManager
# Initialize database
init_db()
logger.info("✓ Database initialized successfully")
# Test connection
with get_db() as conn:
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = cursor.fetchall()
logger.info(f"✓ Database has {len(tables)} tables")
# Test get stats
stats = DatabaseManager.get_database_stats()
logger.info(f"✓ Database stats retrieved: {stats}")
return True
except Exception as e:
logger.error(f"✗ Database test failed: {e}")
return False
def test_app_creation():
"""Test Flask app creation"""
logger.info("Testing Flask app creation...")
try:
from app import create_app
app = create_app('development')
logger.info("✓ Flask app created successfully")
# Test that routes are registered
with app.app_context():
routes = [str(rule) for rule in app.url_map.iter_rules()]
logger.info(f"✓ Registered {len(routes)} routes")
# Check for key endpoints
key_endpoints = ['/api/upload', '/api/states', '/api/status']
for endpoint in key_endpoints:
if any(endpoint in route for route in routes):
logger.info(f" ✓ {endpoint} registered")
return True
except Exception as e:
logger.error(f"✗ App creation test failed: {e}")
return False
def test_extraction_service():
"""Test extraction service initialization"""
logger.info("Testing extraction service...")
try:
from app.extraction_service import ExtractionService
service = ExtractionService(
output_dir='extracted_data'
)
logger.info("✓ Extraction service initialized successfully")
# Check directories exist
assert os.path.exists('extracted_data'), "extracted_data directory not created"
logger.info("✓ Required directories exist")
return True
except Exception as e:
logger.error(f"✗ Extraction service test failed: {e}")
return False
def test_sample_extraction():
"""Test sample data extraction (without PDF file)"""
logger.info("Testing sample data structure...")
try:
from app.parser import PDFExtractor
# Create a mock extracted data structure
sample_data = {
"states": [
{"name": "Lagos", "code": "LG"}
],
"lgas": [
{"name": "Ajeromi-Ifelodun", "code": "001", "state": "Lagos"}
],
"wards": [
{"name": "Ward 1", "code": "001", "lga": "Ajeromi-Ifelodun", "state": "Lagos"}
]
}
# Verify structure
assert "states" in sample_data
assert "lgas" in sample_data
assert "wards" in sample_data
logger.info("✓ Sample data structure is valid")
return True
except Exception as e:
logger.error(f"✗ Sample extraction test failed: {e}")
return False
def run_all_tests():
"""Run all tests"""
logger.info("=" * 50)
logger.info("Starting System Tests")
logger.info("=" * 50)
tests = [
("Imports", test_imports),
("Database", test_database),
("App Creation", test_app_creation),
("Extraction Service", test_extraction_service),
("Sample Extraction", test_sample_extraction)
]
results = {}
for test_name, test_func in tests:
try:
results[test_name] = test_func()
except Exception as e:
logger.error(f"✗ {test_name} test crashed: {e}")
results[test_name] = False
logger.info("=" * 50)
logger.info("Test Results Summary")
logger.info("=" * 50)
passed = sum(1 for v in results.values() if v)
total = len(results)
for test_name, result in results.items():
status = "✓ PASS" if result else "✗ FAIL"
logger.info(f"{status}: {test_name}")
logger.info("=" * 50)
logger.info(f"Total: {passed}/{total} tests passed")
logger.info("=" * 50)
return passed == total
if __name__ == '__main__':
success = run_all_tests()
sys.exit(0 if success else 1)