-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest_remaining_features.py
More file actions
434 lines (358 loc) · 15.6 KB
/
Copy pathtest_remaining_features.py
File metadata and controls
434 lines (358 loc) · 15.6 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
"""
Automated Testing - Remaining Features
Tests: Goals, Assessment Response/Complete, Activities, Chat, Gamification
"""
import requests
import json
from datetime import datetime
BASE_URL = "http://127.0.0.1:5000/api"
class TestSession:
def __init__(self):
self.access_token = None
self.user_id = None
self.username = None
self.assessment_id = None
self.learning_path_id = None
self.enrollment_id = None
def print_header(self, title):
print("\n" + "="*70)
print(f" {title}")
print("="*70)
def print_step(self, step_num, description):
print(f"\nStep {step_num}: {description}")
print("-" * 70)
def print_result(self, success, message, data=None):
status = "✅ PASS" if success else "❌ FAIL"
print(f"{status}: {message}")
if data:
print(f"Data: {json.dumps(data, indent=2)[:500]}")
def register_user(self):
"""Register a new test user"""
self.print_step(1, "Registering new user")
username = f"featuretest_{int(datetime.now().timestamp())}"
self.username = username
try:
response = requests.post(
f"{BASE_URL}/auth/register",
json={
"username": username,
"email": f"{username}@test.com",
"password": "Test123!",
"native_language": "Telugu",
"target_language": "English"
},
timeout=10
)
except requests.exceptions.Timeout:
self.print_result(False, "Request timeout - backend not responding", None)
return False
except Exception as e:
self.print_result(False, f"Connection error: {str(e)}", None)
return False
if response.status_code == 201:
data = response.json()
self.access_token = data.get('access_token')
self.user_id = data.get('user', {}).get('id')
self.print_result(True, f"User registered: {username}", {"user_id": self.user_id})
return True
else:
self.print_result(False, f"Registration failed: {response.status_code}", response.json())
return False
def login_user(self):
"""Login with test user"""
self.print_step(2, "Logging in")
try:
response = requests.post(
f"{BASE_URL}/auth/login",
json={
"username": self.username,
"password": "Test123!"
},
timeout=10
)
except Exception as e:
self.print_result(False, f"Login request error: {str(e)}", None)
return False
if response.status_code == 200:
data = response.json()
self.access_token = data.get('access_token')
self.print_result(True, "Login successful", {"token_length": len(self.access_token)})
return True
else:
self.print_result(False, f"Login failed: {response.status_code}", response.json())
return False
def get_headers(self):
"""Get headers with auth token"""
return {
"Authorization": f"Bearer {self.access_token}",
"Content-Type": "application/json"
}
# ============================================================
# TEST 1: GOAL SETTING
# ============================================================
def test_goal_setting(self):
"""Test setting user goals"""
self.print_header("TEST 1: GOAL SETTING ENDPOINT")
self.print_step("1.1", "Setting daily learning goals")
response = requests.post(
f"{BASE_URL}/personalization/goals",
headers=self.get_headers(),
json={
"daily_time_goal": 20,
"learning_focus": "conversation"
}
)
if response.status_code == 201:
data = response.json()
self.print_result(True, "Goal setting successful", data.get('goal'))
return True
else:
self.print_result(False, f"Goal setting failed: {response.status_code}", response.json())
return False
# ============================================================
# TEST 2: ASSESSMENT FLOW (RESPOND + COMPLETE)
# ============================================================
def test_assessment_flow(self):
"""Test assessment response and completion"""
self.print_header("TEST 2: ASSESSMENT RESPONSE & COMPLETION")
# Start assessment first
self.print_step("2.1", "Starting assessment")
response = requests.post(
f"{BASE_URL}/personalization/assessment/start",
headers=self.get_headers()
)
if response.status_code != 201:
self.print_result(False, f"Assessment start failed: {response.status_code}", response.json())
return False
data = response.json()
# Try to get assessment data from different possible locations
assessment = data.get('assessment', {})
self.assessment_id = assessment.get('assessment_id') or data.get('assessment_id')
questions = assessment.get('questions', []) or data.get('questions', [])
print(f"DEBUG: Full response = {json.dumps(data, indent=2)[:500]}")
self.print_result(True, f"Assessment started (ID: {self.assessment_id})",
{"question_count": len(questions), "has_assessment_key": 'assessment' in data})
if not questions:
self.print_result(False, "No questions in assessment response", None)
return False
# Respond to each question
self.print_step("2.2", "Responding to assessment questions")
responses = [
"My name is Ram and I am a software developer from Hyderabad.",
"I usually wake up at 6 AM, go to work, and come back home in the evening.",
"I want to improve my English speaking skills to communicate better at work."
]
for idx, question in enumerate(questions):
question_id = question.get('id') or question.get('question_id')
if not question_id:
print(f"⚠️ Question {idx+1} has no ID, skipping")
continue
response = requests.post(
f"{BASE_URL}/personalization/assessment/{self.assessment_id}/respond",
headers=self.get_headers(),
json={
"question_id": question_id,
"user_response": responses[idx] if idx < len(responses) else "Yes, I understand."
}
)
if response.status_code == 200:
print(f"✅ Question {idx+1} answered successfully")
else:
print(f"❌ Question {idx+1} failed: {response.status_code}")
print(f" Response: {response.json()}")
# Complete assessment
self.print_step("2.3", "Completing assessment")
response = requests.post(
f"{BASE_URL}/personalization/assessment/{self.assessment_id}/complete",
headers=self.get_headers()
)
if response.status_code == 200:
try:
data = response.json()
self.print_result(True, "Assessment completed", data.get('results'))
return True
except:
self.print_result(True, "Assessment completed (no JSON response)",
{"status": response.status_code, "text": response.text[:200]})
return True
elif response.status_code == 404:
self.print_result(False, "Assessment completion endpoint not found (404)",
{"assessment_id": self.assessment_id})
return False
else:
try:
error_data = response.json()
except:
error_data = {"text": response.text[:200]}
self.print_result(False, f"Assessment completion failed: {response.status_code}",
error_data)
return False
# ============================================================
# TEST 3: ACTIVITIES
# ============================================================
def test_activities(self):
"""Test activities endpoint"""
self.print_header("TEST 3: ACTIVITIES SYSTEM")
# First enroll in a learning path
self.print_step("3.1", "Enrolling in learning path")
# Get learning paths
response = requests.get(
f"{BASE_URL}/courses/learning-paths",
headers=self.get_headers()
)
if response.status_code != 200:
self.print_result(False, "Failed to get learning paths", response.json())
return False
paths = response.json().get('learning_paths', [])
if not paths:
self.print_result(False, "No learning paths available", None)
return False
self.learning_path_id = paths[0]['id']
# Enroll
response = requests.post(
f"{BASE_URL}/courses/learning-paths/{self.learning_path_id}/enroll",
headers=self.get_headers()
)
if response.status_code != 201:
self.print_result(False, "Enrollment failed", response.json())
return False
self.print_result(True, f"Enrolled in path {self.learning_path_id}", None)
# Get activities
self.print_step("3.2", "Getting activities list")
response = requests.get(
f"{BASE_URL}/activity/all",
headers=self.get_headers()
)
if response.status_code == 200:
data = response.json()
activities = data.get('activities', [])
if activities:
self.print_result(True, f"Activities retrieved: {len(activities)} found",
{"first_activity": activities[0] if activities else None})
return True
else:
self.print_result(False, "Activities list is EMPTY",
{"message": "No activities generated after enrollment"})
return False
else:
self.print_result(False, f"Activities endpoint failed: {response.status_code}",
response.json())
return False
# ============================================================
# TEST 4: CHAT ENDPOINT
# ============================================================
def test_chat(self):
"""Test chat endpoint"""
self.print_header("TEST 4: CHAT/AI TUTOR ENDPOINT")
self.print_step("4.1", "Sending message to AI tutor")
response = requests.post(
f"{BASE_URL}/chat/quick-chat",
headers=self.get_headers(),
json={
"message": "Hello! Can you help me learn basic English greetings?",
"context": "learning_assistance"
}
)
if response.status_code == 200:
data = response.json()
ai_response = data.get('response', '')
self.print_result(True, "Chat endpoint working",
{"response_preview": ai_response[:200]})
return True
else:
self.print_result(False, f"Chat endpoint failed: {response.status_code}",
response.json())
return False
# ============================================================
# TEST 5: GAMIFICATION
# ============================================================
def test_gamification(self):
"""Test gamification endpoints"""
self.print_header("TEST 5: GAMIFICATION SYSTEM")
# Test points
self.print_step("5.1", "Getting user points")
response = requests.get(
f"{BASE_URL}/gamification/points",
headers=self.get_headers()
)
points_success = False
if response.status_code == 200:
data = response.json()
self.print_result(True, "Points retrieved", data)
points_success = True
else:
self.print_result(False, f"Points endpoint failed: {response.status_code}",
response.json())
# Test badges
self.print_step("5.2", "Getting user badges")
response = requests.get(
f"{BASE_URL}/gamification/badges",
headers=self.get_headers()
)
badges_success = False
if response.status_code == 200:
data = response.json()
self.print_result(True, "Badges retrieved", data)
badges_success = True
else:
self.print_result(False, f"Badges endpoint failed: {response.status_code}",
response.json())
# Test leaderboard
self.print_step("5.3", "Getting leaderboard")
response = requests.get(
f"{BASE_URL}/gamification/leaderboard",
headers=self.get_headers()
)
leaderboard_success = False
if response.status_code == 200:
data = response.json()
self.print_result(True, "Leaderboard retrieved", data)
leaderboard_success = True
else:
self.print_result(False, f"Leaderboard endpoint failed: {response.status_code}",
response.json())
return points_success and badges_success and leaderboard_success
def main():
print("="*70)
print(" LANGUAGE LEARNING PLATFORM - REMAINING FEATURES TEST")
print("="*70)
print(f"Backend: {BASE_URL}")
print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("="*70)
session = TestSession()
results = {}
# Setup: Register and login
if not session.register_user():
print("\n❌ CRITICAL: User registration failed. Cannot continue.")
return
if not session.login_user():
print("\n❌ CRITICAL: User login failed. Cannot continue.")
return
print("\n✅ Setup complete. Starting feature tests...\n")
# Run tests
results['goal_setting'] = session.test_goal_setting()
results['assessment_flow'] = session.test_assessment_flow()
results['activities'] = session.test_activities()
results['chat'] = session.test_chat()
results['gamification'] = session.test_gamification()
# Summary
print("\n" + "="*70)
print(" TEST SUMMARY")
print("="*70)
total = len(results)
passed = sum(1 for v in results.values() if v)
for test_name, success in results.items():
status = "✅ PASS" if success else "❌ FAIL"
print(f"{status} - {test_name.replace('_', ' ').title()}")
print("-"*70)
print(f"Total: {passed}/{total} tests passed ({(passed/total*100):.1f}%)")
print("="*70)
if passed == total:
print("\n🎉 ALL TESTS PASSED! System is fully functional.")
elif passed >= total * 0.7:
print(f"\n⚠️ Most tests passed. {total - passed} issue(s) need attention.")
else:
print(f"\n❌ Multiple failures detected. {total - passed} tests failed.")
return results
if __name__ == "__main__":
main()