Repository navigation
Expand file tree
/
Copy pathtest_api_validation.py
More file actions
303 lines (260 loc) Β· 13.5 KB
/
Copy pathtest_api_validation.py
File metadata and controls
303 lines (260 loc) Β· 13.5 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
#!/usr/bin/env python3
"""
Backend API Validation Script
Tests all endpoints systematically for API contract compliance and error handling.
"""
import json
import requests
import time
from pathlib import Path
from typing import Dict, Any
BASE_URL = "http://localhost:8000"
TIMEOUT = 30
class APIValidator:
def __init__(self):
self.results = {}
self.test_data = {}
def log_result(self, endpoint: str, status: str, details: str = ""):
"""Log test result"""
self.results[endpoint] = {"status": status, "details": details}
print(f"{'β
' if status == 'PASS' else 'β'} {endpoint}: {status}")
if details:
print(f" {details}")
def test_health_endpoint(self):
"""Test basic health endpoint"""
try:
response = requests.get(f"{BASE_URL}/health", timeout=5)
if response.status_code == 200:
data = response.json()
if "status" in data and data["status"] == "healthy":
self.log_result("/health", "PASS", "Health check successful")
return True
else:
self.log_result("/health", "FAIL", f"Invalid response: {data}")
else:
self.log_result("/health", "FAIL", f"Status: {response.status_code}")
except Exception as e:
self.log_result("/health", "FAIL", f"Connection error: {e}")
return False
def test_resume_upload(self):
"""Test /resume/upload endpoint"""
try:
# Use the text resume file we created
with open("test_resume.txt", "rb") as f:
test_content = f.read()
files = {"file": ("test_resume.txt", test_content, "text/plain")}
data = {"github_url": "https://github.com/testuser"}
response = requests.post(f"{BASE_URL}/resume/upload", files=files, data=data, timeout=TIMEOUT)
if response.status_code == 200:
result = response.json()
required_fields = ["id", "status", "message", "data"]
if all(field in result for field in required_fields):
if result["data"] and "id" in result["data"]:
self.test_data["resume_id"] = result["data"]["id"]
self.log_result("/resume/upload", "PASS", f"Resume uploaded: {result['id']}")
return True
else:
self.log_result("/resume/upload", "FAIL", "Missing data.id in response")
else:
self.log_result("/resume/upload", "FAIL", f"Missing fields: {set(required_fields) - set(result.keys())}")
else:
self.log_result("/resume/upload", "FAIL", f"Status: {response.status_code}, Body: {response.text[:200]}")
except Exception as e:
self.log_result("/resume/upload", "FAIL", f"Error: {e}")
return False
def test_jobs_analyze(self):
"""Test /jobs/analyze endpoint"""
try:
# Test with job text
payload = {
"job_text": "Senior Software Engineer position requiring Python, FastAPI, React, and 5+ years experience. Must have experience with cloud platforms and microservices architecture."
}
response = requests.post(f"{BASE_URL}/jobs/analyze", json=payload, timeout=TIMEOUT)
if response.status_code == 200:
result = response.json()
required_fields = ["id", "title", "company", "required_skills", "preferred_skills", "technologies", "experience_level", "key_requirements"]
if all(field in result for field in required_fields):
self.test_data["job_id"] = result["id"]
self.log_result("/jobs/analyze", "PASS", f"Job analyzed: {result['id']}")
return True
else:
self.log_result("/jobs/analyze", "FAIL", f"Missing fields: {set(required_fields) - set(result.keys())}")
else:
self.log_result("/jobs/analyze", "FAIL", f"Status: {response.status_code}, Body: {response.text[:200]}")
except Exception as e:
self.log_result("/jobs/analyze", "FAIL", f"Error: {e}")
return False
def test_optimize_sse(self):
"""Test /optimize SSE endpoint"""
if "resume_id" not in self.test_data or "job_id" not in self.test_data:
self.log_result("/optimize (SSE)", "SKIP", "Missing resume_id or job_id from previous tests")
return False
try:
payload = {
"resume_id": self.test_data["resume_id"],
"job_id": self.test_data["job_id"]
}
response = requests.post(f"{BASE_URL}/optimize", json=payload, stream=True, timeout=TIMEOUT)
if response.status_code == 200:
if "text/event-stream" in response.headers.get("content-type", ""):
# Read first few SSE events
events_received = 0
for line in response.iter_lines(decode_unicode=True):
if line.startswith("data: "):
events_received += 1
if events_received >= 3: # Check first 3 events
break
if events_received > 0:
self.log_result("/optimize (SSE)", "PASS", f"SSE streaming working, received {events_received} events")
return True
else:
self.log_result("/optimize (SSE)", "FAIL", "No SSE events received")
else:
self.log_result("/optimize (SSE)", "FAIL", f"Wrong content-type: {response.headers.get('content-type')}")
else:
self.log_result("/optimize (SSE)", "FAIL", f"Status: {response.status_code}, Body: {response.text[:200]}")
except Exception as e:
self.log_result("/optimize (SSE)", "FAIL", f"Error: {e}")
return False
def test_export_endpoints(self):
"""Test /export/{format} endpoints with template selection"""
if "resume_id" not in self.test_data:
self.log_result("/export/{format}", "SKIP", "Missing resume_id from previous tests")
return False
formats_tested = 0
formats_passed = 0
# Test templates endpoint first
try:
response = requests.get(f"{BASE_URL}/export/templates", timeout=10)
if response.status_code == 200:
templates = response.json()
if isinstance(templates, list) and len(templates) > 0:
self.log_result("/export/templates", "PASS", f"Found {len(templates)} templates")
else:
self.log_result("/export/templates", "FAIL", "No templates returned")
else:
self.log_result("/export/templates", "FAIL", f"Status: {response.status_code}")
except Exception as e:
self.log_result("/export/templates", "FAIL", f"Error: {e}")
# Test PDF export with different templates
for template in ["classic", "modern"]:
formats_tested += 1
try:
payload = {
"resume_id": self.test_data["resume_id"],
"template": template
}
response = requests.post(f"{BASE_URL}/export/pdf", json=payload, timeout=TIMEOUT)
if response.status_code == 200:
content_type = response.headers.get("content-type", "")
if "html" in content_type or "pdf" in content_type:
formats_passed += 1
self.log_result(f"/export/pdf ({template})", "PASS", f"Content-Type: {content_type}")
else:
self.log_result(f"/export/pdf ({template})", "FAIL", f"Wrong content-type: {content_type}")
else:
self.log_result(f"/export/pdf ({template})", "FAIL", f"Status: {response.status_code}")
except Exception as e:
self.log_result(f"/export/pdf ({template})", "FAIL", f"Error: {e}")
# Test DOCX export
formats_tested += 1
try:
payload = {
"resume_id": self.test_data["resume_id"],
"template": "classic"
}
response = requests.post(f"{BASE_URL}/export/docx", json=payload, timeout=TIMEOUT)
if response.status_code == 200:
content_type = response.headers.get("content-type", "")
if "document" in content_type or "octet-stream" in content_type:
formats_passed += 1
self.log_result("/export/docx", "PASS", f"Content-Type: {content_type}")
else:
self.log_result("/export/docx", "FAIL", f"Wrong content-type: {content_type}")
else:
self.log_result("/export/docx", "FAIL", f"Status: {response.status_code}")
except Exception as e:
self.log_result("/export/docx", "FAIL", f"Error: {e}")
return formats_passed == formats_tested
def test_github_analyze(self):
"""Test /github/analyze endpoint"""
try:
payload = {"username": "octocat"} # GitHub's mascot account
response = requests.post(f"{BASE_URL}/github/analyze", json=payload, timeout=TIMEOUT)
if response.status_code == 200:
result = response.json()
required_fields = ["username", "profile_url", "impact_metrics", "tech_stack", "top_repositories", "project_highlights", "resume_bullet_points"]
if all(field in result for field in required_fields):
self.log_result("/github/analyze", "PASS", f"GitHub analysis for {result['username']}")
return True
else:
self.log_result("/github/analyze", "FAIL", f"Missing fields: {set(required_fields) - set(result.keys())}")
else:
self.log_result("/github/analyze", "FAIL", f"Status: {response.status_code}, Body: {response.text[:200]}")
except Exception as e:
self.log_result("/github/analyze", "FAIL", f"Error: {e}")
return False
def test_error_handling(self):
"""Test error handling across endpoints"""
error_tests = [
# Invalid file type
("/resume/upload", "POST", {"files": {"file": ("test.exe", b"invalid", "application/exe")}}),
# Missing required fields
("/jobs/analyze", "POST", {"json": {}}),
# Invalid resume ID
("/optimize", "POST", {"json": {"resume_id": "invalid", "job_id": "invalid"}}),
# Invalid export format
("/export/invalid", "POST", {"json": {"resume_id": "test"}}),
# Invalid GitHub username
("/github/analyze", "POST", {"json": {"username": ""}}),
]
passed = 0
total = len(error_tests)
for endpoint, method, kwargs in error_tests:
try:
if method == "POST":
response = requests.post(f"{BASE_URL}{endpoint}", timeout=10, **kwargs)
else:
response = requests.get(f"{BASE_URL}{endpoint}", timeout=10, **kwargs)
if 400 <= response.status_code < 500:
passed += 1
self.log_result(f"Error handling {endpoint}", "PASS", f"Status: {response.status_code}")
else:
self.log_result(f"Error handling {endpoint}", "FAIL", f"Expected 4xx, got: {response.status_code}")
except Exception as e:
self.log_result(f"Error handling {endpoint}", "FAIL", f"Error: {e}")
return passed == total
def run_all_tests(self):
"""Run all API validation tests"""
print("π Starting Backend API Validation")
print("=" * 50)
# Test basic connectivity
if not self.test_health_endpoint():
print("β Backend not accessible, stopping tests")
return
# Test core endpoints in order
self.test_resume_upload()
self.test_jobs_analyze()
self.test_optimize_sse()
self.test_export_endpoints()
self.test_github_analyze()
self.test_error_handling()
# Summary
print("\n" + "=" * 50)
print("π VALIDATION SUMMARY")
print("=" * 50)
passed = sum(1 for r in self.results.values() if r["status"] == "PASS")
failed = sum(1 for r in self.results.values() if r["status"] == "FAIL")
skipped = sum(1 for r in self.results.values() if r["status"] == "SKIP")
print(f"β
PASSED: {passed}")
print(f"β FAILED: {failed}")
print(f"βοΈ SKIPPED: {skipped}")
print(f"π SUCCESS RATE: {passed/(passed+failed)*100:.1f}%" if (passed+failed) > 0 else "N/A")
if failed > 0:
print("\nπ FAILED TESTS:")
for endpoint, result in self.results.items():
if result["status"] == "FAIL":
print(f" {endpoint}: {result['details']}")
if __name__ == "__main__":
validator = APIValidator()
validator.run_all_tests()