-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathtest_api_v2.py
More file actions
629 lines (533 loc) · 24.2 KB
/
test_api_v2.py
File metadata and controls
629 lines (533 loc) · 24.2 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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
"""
Tests for Instructor API v2 endpoints.
"""
import json
from unittest.mock import MagicMock, patch
from uuid import uuid4
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from common.djangoapps.student.models import CourseEnrollment
from common.djangoapps.student.tests.factories import InstructorFactory, UserFactory
from lms.djangoapps.courseware.models import StudentModule
from lms.djangoapps.instructor_task.models import InstructorTask
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import BlockFactory, CourseFactory
class LearnerViewTestCase(ModuleStoreTestCase):
"""
Tests for GET /api/instructor/v2/courses/{course_key}/learners/{email_or_username}
"""
def setUp(self):
super().setUp()
self.client = APIClient()
self.course = CourseFactory.create()
self.instructor = InstructorFactory.create(course_key=self.course.id)
self.student = UserFactory(
username='john_harvard',
email='[email protected]',
)
self.student.profile.name = 'John Harvard'
self.student.profile.save()
self.client.force_authenticate(user=self.instructor)
def test_get_learner_by_username(self):
"""Test retrieving learner info by username"""
url = reverse('instructor_api_v2:learner_detail', kwargs={
'course_id': str(self.course.id),
'email_or_username': self.student.username
})
response = self.client.get(url)
expected_progress_url = reverse('student_progress', kwargs={
'course_id': str(self.course.id),
'student_id': self.student.id,
})
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertEqual(data['username'], 'john_harvard')
self.assertEqual(data['email'], '[email protected]')
self.assertEqual(data['full_name'], 'John Harvard')
self.assertEqual(data['progress_url'], expected_progress_url)
def test_get_learner_by_email(self):
"""Test retrieving learner info by email"""
url = reverse('instructor_api_v2:learner_detail', kwargs={
'course_id': str(self.course.id),
'email_or_username': self.student.email
})
response = self.client.get(url)
expected_progress_url = reverse('student_progress', kwargs={
'course_id': str(self.course.id),
'student_id': self.student.id,
})
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertEqual(data['username'], 'john_harvard')
self.assertEqual(data['email'], '[email protected]')
self.assertEqual(data['progress_url'], expected_progress_url)
def test_get_learner_requires_authentication(self):
"""Test that endpoint requires authentication"""
self.client.force_authenticate(user=None)
url = reverse('instructor_api_v2:learner_detail', kwargs={
'course_id': str(self.course.id),
'email_or_username': self.student.username
})
response = self.client.get(url)
self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
class ProblemViewTestCase(ModuleStoreTestCase):
"""
Tests for GET /api/instructor/v2/courses/{course_key}/problems/{location}
"""
def setUp(self):
super().setUp()
self.client = APIClient()
self.course = CourseFactory.create(display_name='Test Course')
self.instructor = InstructorFactory.create(course_key=self.course.id)
self.chapter = BlockFactory.create(
parent=self.course,
category='chapter',
display_name='Week 1'
)
self.sequential = BlockFactory.create(
parent=self.chapter,
category='sequential',
display_name='Homework 1'
)
self.problem = BlockFactory.create(
parent=self.sequential,
category='problem',
display_name='Sample Problem'
)
self.client.force_authenticate(user=self.instructor)
def test_get_problem_metadata(self):
"""Test retrieving problem metadata"""
url = reverse('instructor_api_v2:problem_detail', kwargs={
'course_id': str(self.course.id),
'location': str(self.problem.location)
})
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertEqual(data['id'], str(self.problem.location))
self.assertEqual(data['name'], 'Sample Problem')
self.assertIn('breadcrumbs', data)
self.assertIsInstance(data['breadcrumbs'], list)
def test_get_problem_with_breadcrumbs(self):
"""Test that breadcrumbs contain the full course hierarchy"""
url = reverse('instructor_api_v2:problem_detail', kwargs={
'course_id': str(self.course.id),
'location': str(self.problem.location)
})
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
breadcrumbs = data['breadcrumbs']
# Should contain: course → chapter → sequential → problem
self.assertEqual(len(breadcrumbs), 4)
self.assertEqual(breadcrumbs[0]['display_name'], self.course.display_name)
self.assertIsNone(breadcrumbs[0]['usage_key']) # course-level has no usage_key
self.assertEqual(breadcrumbs[1]['display_name'], 'Week 1')
self.assertEqual(breadcrumbs[2]['display_name'], 'Homework 1')
self.assertEqual(breadcrumbs[3]['display_name'], 'Sample Problem')
def test_get_problem_invalid_location(self):
"""Test 400 with invalid problem location"""
url = reverse('instructor_api_v2:problem_detail', kwargs={
'course_id': str(self.course.id),
'location': 'invalid-location'
})
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('error', response.json())
def test_get_problem_without_learner_has_null_score_and_attempts(self):
"""Test that current_score and attempts are null when no learner is specified"""
url = reverse('instructor_api_v2:problem_detail', kwargs={
'course_id': str(self.course.id),
'location': str(self.problem.location)
})
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertIsNone(data['current_score'])
self.assertIsNone(data['attempts'])
def test_get_problem_with_learner_returns_score_and_attempts(self):
"""Test that current_score and attempts are returned when learner has a StudentModule"""
student = UserFactory()
StudentModule.objects.create(
student=student,
course_id=self.course.id,
module_state_key=self.problem.location,
module_type='problem',
grade=7.0,
max_grade=10.0,
state=json.dumps({'attempts': 3}),
)
url = reverse('instructor_api_v2:problem_detail', kwargs={
'course_id': str(self.course.id),
'location': str(self.problem.location)
})
response = self.client.get(url, {'email_or_username': student.username})
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertEqual(data['current_score']['score'], 7.0)
self.assertEqual(data['current_score']['total'], 10.0)
self.assertEqual(data['attempts']['current'], 3)
def test_get_problem_with_learner_no_submission_returns_nulls(self):
"""Test that current_score and attempts are null when learner has no StudentModule"""
student = UserFactory()
url = reverse('instructor_api_v2:problem_detail', kwargs={
'course_id': str(self.course.id),
'location': str(self.problem.location)
})
response = self.client.get(url, {'email_or_username': student.username})
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertIsNone(data['current_score'])
self.assertIsNone(data['attempts'])
def test_get_problem_with_unknown_learner_returns_404(self):
"""Test that a 404 is returned when learner does not exist"""
url = reverse('instructor_api_v2:problem_detail', kwargs={
'course_id': str(self.course.id),
'location': str(self.problem.location)
})
response = self.client.get(url, {'email_or_username': 'nonexistent_user'})
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_get_problem_requires_authentication(self):
"""Test that endpoint requires authentication"""
self.client.force_authenticate(user=None)
url = reverse('instructor_api_v2:problem_detail', kwargs={
'course_id': str(self.course.id),
'location': str(self.problem.location)
})
response = self.client.get(url)
self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
class TaskStatusViewTestCase(ModuleStoreTestCase):
"""
Tests for GET /api/instructor/v2/courses/{course_key}/tasks/{task_id}
"""
def setUp(self):
super().setUp()
self.client = APIClient()
self.course = CourseFactory.create()
self.instructor = InstructorFactory.create(course_key=self.course.id)
self.client.force_authenticate(user=self.instructor)
def test_get_task_status_completed(self):
"""Test retrieving completed task status"""
# Create a completed task
task_id = str(uuid4())
task_output = json.dumps({
'current': 150,
'total': 150,
'message': 'Reset attempts for 150 learners'
})
InstructorTask.objects.create(
course_id=self.course.id,
task_type='rescore_problem',
task_key='',
task_input='{}',
task_id=task_id,
task_state='SUCCESS',
task_output=task_output,
requester=self.instructor
)
url = reverse('instructor_api_v2:task_status', kwargs={
'course_id': str(self.course.id),
'task_id': task_id
})
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertEqual(data['task_id'], task_id)
self.assertEqual(data['state'], 'completed')
self.assertIn('progress', data)
self.assertEqual(data['progress']['current'], 150)
self.assertEqual(data['progress']['total'], 150)
self.assertIn('result', data)
self.assertTrue(data['result']['success'])
def test_get_task_status_running(self):
"""Test retrieving running task status"""
# Create a running task
task_id = str(uuid4())
task_output = json.dumps({'current': 75, 'total': 150})
InstructorTask.objects.create(
course_id=self.course.id,
task_type='rescore_problem',
task_key='',
task_input='{}',
task_id=task_id,
task_state='PROGRESS',
task_output=task_output,
requester=self.instructor
)
url = reverse('instructor_api_v2:task_status', kwargs={
'course_id': str(self.course.id),
'task_id': task_id
})
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertEqual(data['state'], 'running')
self.assertIn('progress', data)
self.assertEqual(data['progress']['current'], 75)
self.assertEqual(data['progress']['total'], 150)
def test_get_task_status_failed(self):
"""Test retrieving failed task status"""
# Create a failed task
task_id = str(uuid4())
InstructorTask.objects.create(
course_id=self.course.id,
task_type='rescore_problem',
task_key='',
task_input='{}',
task_id=task_id,
task_state='FAILURE',
task_output='Task execution failed',
requester=self.instructor
)
url = reverse('instructor_api_v2:task_status', kwargs={
'course_id': str(self.course.id),
'task_id': task_id
})
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertEqual(data['state'], 'failed')
self.assertIn('error', data)
self.assertIn('code', data['error'])
self.assertIn('message', data['error'])
def test_get_task_requires_authentication(self):
"""Test that endpoint requires authentication"""
self.client.force_authenticate(user=None)
url = reverse('instructor_api_v2:task_status', kwargs={
'course_id': str(self.course.id),
'task_id': 'some-task-id'
})
response = self.client.get(url)
self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
class GradingConfigViewTestCase(ModuleStoreTestCase):
"""
Tests for GET /api/instructor/v2/courses/{course_key}/grading-config
"""
def setUp(self):
super().setUp()
self.client = APIClient()
self.course = CourseFactory.create()
self.instructor = InstructorFactory.create(course_key=self.course.id)
self.client.force_authenticate(user=self.instructor)
def test_get_grading_config(self):
"""Test retrieving grading configuration returns graders and grade cutoffs"""
url = reverse('instructor_api_v2:grading_config', kwargs={
'course_id': str(self.course.id),
})
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertIn('graders', data)
self.assertIn('grade_cutoffs', data)
self.assertIsInstance(data['graders'], list)
self.assertIsInstance(data['grade_cutoffs'], dict)
def test_get_grading_config_grader_fields(self):
"""Test that each grader entry has the expected fields"""
url = reverse('instructor_api_v2:grading_config', kwargs={
'course_id': str(self.course.id),
})
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
for grader in data['graders']:
self.assertIn('type', grader)
self.assertIn('min_count', grader)
self.assertIn('drop_count', grader)
self.assertIn('weight', grader)
def test_get_grading_config_requires_authentication(self):
"""Test that endpoint requires authentication"""
self.client.force_authenticate(user=None)
url = reverse('instructor_api_v2:grading_config', kwargs={
'course_id': str(self.course.id),
})
response = self.client.get(url)
self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
class GradingEndpointTestBase(ModuleStoreTestCase):
"""
Base test class for grading endpoints with real course structures,
real permissions, and real StudentModule records.
"""
def setUp(self):
super().setUp()
self.client = APIClient()
self.course = CourseFactory.create(display_name='Test Course')
self.chapter = BlockFactory.create(
parent=self.course,
category='chapter',
display_name='Week 1'
)
self.sequential = BlockFactory.create(
parent=self.chapter,
category='sequential',
display_name='Homework 1'
)
self.problem = BlockFactory.create(
parent=self.sequential,
category='problem',
display_name='Test Problem'
)
# Real instructor with real course permissions
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.force_authenticate(user=self.instructor)
# Real enrolled student with real module state
self.student = UserFactory(username='test_student', email='[email protected]')
CourseEnrollment.enroll(self.student, self.course.id)
self.student_module = StudentModule.objects.create(
student=self.student,
course_id=self.course.id,
module_state_key=self.problem.location,
state=json.dumps({'attempts': 10}),
)
class ResetAttemptsViewTestCase(GradingEndpointTestBase):
"""
Tests for POST /api/instructor/v2/courses/{course_key}/{problem}/grading/attempts/reset
"""
def _get_url(self, problem=None):
return reverse('instructor_api_v2:reset_attempts', kwargs={
'course_id': str(self.course.id),
'problem': problem or str(self.problem.location),
})
def test_reset_single_learner(self):
"""Single learner reset zeroes attempt count and returns 200."""
response = self.client.post(self._get_url() + '?learner=test_student')
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertTrue(data['success'])
self.assertEqual(data['learner'], 'test_student')
self.assertEqual(data['message'], 'Attempts reset successfully')
# Verify the actual StudentModule was modified
self.student_module.refresh_from_db()
self.assertEqual(json.loads(self.student_module.state)['attempts'], 0)
@patch('lms.djangoapps.instructor_task.api.submit_reset_problem_attempts_for_all_students')
def test_reset_all_learners(self, mock_submit):
"""Bulk reset queues a background task and returns 202."""
mock_task = MagicMock()
mock_task.task_id = str(uuid4())
mock_submit.return_value = mock_task
response = self.client.post(self._get_url())
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
data = response.json()
self.assertEqual(data['task_id'], mock_task.task_id)
self.assertIn('status_url', data)
self.assertEqual(data['scope']['learners'], 'all')
mock_submit.assert_called_once()
class DeleteStateViewTestCase(GradingEndpointTestBase):
"""
Tests for DELETE /api/instructor/v2/courses/{course_key}/{problem}/grading/state
"""
def _get_url(self, problem=None):
return reverse('instructor_api_v2:delete_state', kwargs={
'course_id': str(self.course.id),
'problem': problem or str(self.problem.location),
})
@patch('lms.djangoapps.grades.signals.handlers.PROBLEM_WEIGHTED_SCORE_CHANGED.send')
def test_delete_state(self, _mock_signal):
"""Delete state removes the StudentModule record and returns 200."""
response = self.client.delete(self._get_url() + '?learner=test_student')
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertTrue(data['success'])
self.assertEqual(data['learner'], 'test_student')
self.assertEqual(data['message'], 'State deleted successfully')
# Verify the StudentModule was actually deleted
self.assertFalse(
StudentModule.objects.filter(pk=self.student_module.pk).exists()
)
def test_delete_state_requires_learner_param(self):
"""DELETE without learner query param returns 400."""
response = self.client.delete(self._get_url())
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
class RescoreViewTestCase(GradingEndpointTestBase):
"""
Tests for POST /api/instructor/v2/courses/{course_key}/{problem}/grading/scores/rescore
"""
def _get_url(self, problem=None):
return reverse('instructor_api_v2:rescore', kwargs={
'course_id': str(self.course.id),
'problem': problem or str(self.problem.location),
})
@patch('lms.djangoapps.instructor_task.api.submit_rescore_problem_for_student')
def test_rescore_single_learner(self, mock_submit):
"""Single learner rescore queues a task and returns 202."""
mock_task = MagicMock()
mock_task.task_id = str(uuid4())
mock_submit.return_value = mock_task
response = self.client.post(self._get_url() + '?learner=test_student')
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
data = response.json()
self.assertEqual(data['task_id'], mock_task.task_id)
self.assertEqual(data['scope']['learners'], 'test_student')
mock_submit.assert_called_once()
# Default only_if_higher should be False
self.assertFalse(mock_submit.call_args[0][3])
@patch('lms.djangoapps.instructor_task.api.submit_rescore_problem_for_student')
def test_rescore_only_if_higher(self, mock_submit):
"""Rescore with only_if_higher=true passes the flag through."""
mock_task = MagicMock()
mock_task.task_id = str(uuid4())
mock_submit.return_value = mock_task
response = self.client.post(self._get_url() + '?learner=test_student&only_if_higher=true')
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
self.assertTrue(mock_submit.call_args[0][3])
@patch('lms.djangoapps.instructor_task.api.submit_rescore_problem_for_all_students')
def test_rescore_all_learners(self, mock_submit):
"""Bulk rescore queues a task and returns 202."""
mock_task = MagicMock()
mock_task.task_id = str(uuid4())
mock_submit.return_value = mock_task
response = self.client.post(self._get_url())
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
data = response.json()
self.assertEqual(data['scope']['learners'], 'all')
mock_submit.assert_called_once()
class ScoreOverrideViewTestCase(GradingEndpointTestBase):
"""
Tests for PUT /api/instructor/v2/courses/{course_key}/{problem}/grading/scores
"""
def _get_url(self, problem=None):
return reverse('instructor_api_v2:score_override', kwargs={
'course_id': str(self.course.id),
'problem': problem or str(self.problem.location),
})
@patch('lms.djangoapps.instructor_task.api.submit_override_score')
def test_override_score(self, mock_submit):
"""Score override queues a task and returns 202."""
mock_task = MagicMock()
mock_task.task_id = str(uuid4())
mock_submit.return_value = mock_task
response = self.client.put(
self._get_url() + '?learner=test_student',
data={'score': 8.5},
format='json',
)
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
data = response.json()
self.assertEqual(data['task_id'], mock_task.task_id)
self.assertEqual(data['scope']['learners'], 'test_student')
# Verify the score value was passed through
self.assertEqual(mock_submit.call_args[0][3], 8.5)
def test_override_requires_learner_param(self):
"""PUT without learner query param returns 400."""
response = self.client.put(
self._get_url(),
data={'score': 8.5},
format='json',
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_override_requires_score_in_body(self):
"""PUT without score in body returns 400."""
response = self.client.put(
self._get_url() + '?learner=test_student',
data={},
format='json',
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_override_rejects_negative_score(self):
"""PUT with negative score returns 400."""
response = self.client.put(
self._get_url() + '?learner=test_student',
data={'score': -1},
format='json',
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)