-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathtest_api_v2.py
More file actions
3724 lines (3128 loc) · 155 KB
/
test_api_v2.py
File metadata and controls
3724 lines (3128 loc) · 155 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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Unit tests for instructor API v2 endpoints.
"""
import json
from datetime import datetime, timedelta
from unittest.mock import Mock, patch
from urllib.parse import urlencode
from uuid import uuid4
import ddt
from django.conf import settings
from django.contrib.auth import get_user_model
from django.http import Http404
from django.test import SimpleTestCase, override_settings
from django.urls import NoReverseMatch, reverse
from edx_when.api import set_date_for_block, set_dates_for_course
from opaque_keys import InvalidKeyError
from pytz import UTC
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, APITestCase
from common.djangoapps.course_modes.tests.factories import CourseModeFactory
from common.djangoapps.student.models import ManualEnrollmentAudit
from common.djangoapps.student.models.course_enrollment import CourseEnrollment, CourseEnrollmentAllowed
from common.djangoapps.student.roles import (
CourseBetaTesterRole,
CourseDataResearcherRole,
CourseInstructorRole,
CourseStaffRole,
)
from common.djangoapps.student.tests.factories import (
AdminFactory,
CourseEnrollmentFactory,
InstructorFactory,
StaffFactory,
UserFactory,
)
from lms.djangoapps.certificates.data import CertificateStatuses
from lms.djangoapps.certificates.models import CertificateAllowlist, CertificateGenerationHistory
from lms.djangoapps.certificates.tests.factories import GeneratedCertificateFactory
from lms.djangoapps.courseware.models import StudentModule
from lms.djangoapps.instructor.access import ROLE_DISPLAY_NAMES
from lms.djangoapps.instructor.permissions import InstructorPermission
from lms.djangoapps.instructor.views.serializers_v2 import CourseInformationSerializerV2
from lms.djangoapps.instructor_task.tests.factories import InstructorTaskFactory
from openedx.core.djangoapps.django_comment_common.models import Role
from openedx.core.djangoapps.django_comment_common.utils import seed_permissions_roles
from xmodule.modulestore.tests.django_utils import TEST_DATA_SPLIT_MODULESTORE, SharedModuleStoreTestCase
from xmodule.modulestore.tests.factories import BlockFactory, CourseFactory
@ddt.ddt
class CourseMetadataViewTest(SharedModuleStoreTestCase):
"""
Tests for the CourseMetadataView API endpoint.
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.course = CourseFactory.create(
org='edX',
number='DemoX',
run='Demo_Course',
display_name='Demonstration Course',
self_paced=False,
enable_proctored_exams=True,
)
cls.proctored_course = CourseFactory.create(
org='edX',
number='Proctored',
run='2024',
display_name='Demonstration Proctored Course',
)
cls.course_key = cls.course.id
def setUp(self):
super().setUp()
self.client = APIClient()
self.admin = AdminFactory.create()
self.instructor = InstructorFactory.create(course_key=self.course_key)
self.staff = StaffFactory.create(course_key=self.course_key)
self.django_staff_user = UserFactory.create(is_staff=True)
self.data_researcher = UserFactory.create()
CourseDataResearcherRole(self.course_key).add_users(self.data_researcher)
CourseInstructorRole(self.proctored_course.id).add_users(self.instructor)
self.student = UserFactory.create()
# Create some enrollments for testing
CourseEnrollmentFactory.create(
user=self.student,
course_id=self.course_key,
mode='audit',
is_active=True
)
CourseEnrollmentFactory.create(
user=UserFactory.create(),
course_id=self.course_key,
mode='verified',
is_active=True
)
CourseEnrollmentFactory.create(
user=UserFactory.create(),
course_id=self.course_key,
mode='honor',
is_active=True
)
CourseEnrollmentFactory.create(
user=UserFactory.create(),
course_id=self.proctored_course.id,
mode='verified',
is_active=True
)
def _get_url(self, course_id=None):
"""Helper to get the API URL."""
if course_id is None:
course_id = str(self.course_key)
return reverse('instructor_api_v2:course_metadata', kwargs={'course_id': course_id})
@override_settings(
COURSE_AUTHORING_MICROFRONTEND_URL='http://localhost:2001/authoring',
ADMIN_CONSOLE_MICROFRONTEND_URL='http://localhost:2025/admin-console',
# intentionally include trailing slash to test URL joining logic
WRITABLE_GRADEBOOK_URL='http://localhost:1994/gradebook/',
)
def test_get_course_metadata_as_instructor(self):
"""
Test that an instructor can retrieve comprehensive course metadata.
"""
with patch(
'lms.djangoapps.instructor.views.serializers_v2.is_writable_gradebook_enabled',
return_value=True,
):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
assert response.status_code == status.HTTP_200_OK
data = response.data
# Verify basic course information
assert data['course_id'] == str(self.course_key)
assert data['display_name'] == 'Demonstration Course'
assert data['org'] == 'edX'
assert data['course_number'] == 'DemoX'
assert data['course_run'] == 'Demo_Course'
assert data['pacing'] == 'instructor'
# Verify enrollment counts structure
assert 'enrollment_counts' in data
assert 'total' in data['enrollment_counts']
assert 'total_enrollment' in data
assert data['total_enrollment'] >= 3
# Verify role-based enrollment counts are present
assert 'learner_count' in data
assert 'staff_count' in data
assert data['total_enrollment'] == data['learner_count'] + data['staff_count']
# Verify permissions structure
assert 'permissions' in data
permissions_data = data['permissions']
assert 'admin' in permissions_data
assert 'instructor' in permissions_data
assert 'staff' in permissions_data
assert 'forum_admin' in permissions_data
assert 'finance_admin' in permissions_data
assert 'sales_admin' in permissions_data
assert 'data_researcher' in permissions_data
# Verify sections structure
assert 'tabs' in data
assert isinstance(data['tabs'], list)
# Verify other metadata fields
assert 'num_sections' in data
assert 'grade_cutoffs' in data
assert 'course_errors' in data
assert 'studio_url' in data
assert 'disable_buttons' in data
assert 'has_started' in data
assert 'has_ended' in data
assert 'analytics_dashboard_message' in data
assert 'studio_grading_url' in data
assert 'admin_console_url' in data
assert 'gradebook_url' in data
assert data['studio_grading_url'] == f'http://localhost:2001/authoring/course/{self.course.id}/settings/grading'
assert data['admin_console_url'] == 'http://localhost:2025/admin-console/authz'
assert data['gradebook_url'] == f'http://localhost:1994/gradebook/{self.course.id}'
@override_settings(ADMIN_CONSOLE_MICROFRONTEND_URL='http://localhost:2025/admin-console')
def test_admin_console_url_requires_instructor_access(self):
"""
Test that the admin console URL is only available to users with instructor access.
"""
# data researcher has access to course but is not an instructor
self.client.force_authenticate(user=self.data_researcher)
response = self.client.get(self._get_url())
assert response.status_code == status.HTTP_200_OK
assert 'admin_console_url' in response.data
data = response.data
assert data['admin_console_url'] is None
@override_settings(ADMIN_CONSOLE_MICROFRONTEND_URL='http://localhost:2025/admin-console')
def test_django_staff_user_without_instructor_access_can_see_admin_console_url(self):
"""
Test that Django staff users without instructor access can see the admin console URL.
"""
self.client.force_authenticate(user=self.django_staff_user)
response = self.client.get(self._get_url())
assert response.status_code == status.HTTP_200_OK
assert 'admin_console_url' in response.data
data = response.data
assert data['admin_console_url'] == 'http://localhost:2025/admin-console/authz'
def test_get_course_metadata_as_staff(self):
"""
Test that course staff can retrieve course metadata.
"""
self.client.force_authenticate(user=self.staff)
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
self.assertEqual(data['course_id'], str(self.course_key)) # noqa: PT009
self.assertIn('permissions', data) # noqa: PT009
# Staff should have staff permission
self.assertTrue(data['permissions']['staff']) # noqa: PT009
def test_get_course_metadata_unauthorized(self):
"""
Test that students cannot access course metadata endpoint.
"""
self.client.force_authenticate(user=self.student)
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
error_code = "You do not have permission to perform this action."
self.assertEqual(response.data['developer_message'], error_code) # noqa: PT009
def test_get_course_metadata_unauthenticated(self):
"""
Test that unauthenticated users cannot access the endpoint.
"""
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_get_course_metadata_invalid_course_id(self):
"""
Test error handling for invalid course ID.
"""
self.client.force_authenticate(user=self.instructor)
invalid_course_id = 'invalid-course-id'
with self.assertRaises(NoReverseMatch): # noqa: PT027
self.client.get(self._get_url(course_id=invalid_course_id))
def test_get_course_metadata_nonexistent_course(self):
"""
Test error handling for non-existent course.
"""
self.client.force_authenticate(user=self.instructor)
nonexistent_course_id = 'course-v1:edX+NonExistent+2024'
response = self.client.get(self._get_url(course_id=nonexistent_course_id))
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
error_code = "Course not found: course-v1:edX+NonExistent+2024."
self.assertEqual(response.data['developer_message'], error_code) # noqa: PT009
def test_instructor_permissions_reflected(self):
"""
Test that instructor permissions are correctly reflected in response.
"""
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
permissions_data = response.data['permissions']
# Instructor should have instructor permission
self.assertTrue(permissions_data['instructor']) # noqa: PT009
def test_learner_and_staff_counts(self):
"""
Test that learner_count excludes staff/admins and staff_count is the difference.
"""
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
total = data['total_enrollment']
learner_count = data['learner_count']
staff_count = data['staff_count']
# Counts must be non-negative and sum to total
self.assertGreaterEqual(learner_count, 0) # noqa: PT009
self.assertGreaterEqual(staff_count, 0) # noqa: PT009
self.assertEqual(total, learner_count + staff_count) # noqa: PT009
# The student enrolled in setUp is not staff, so learner_count >= 1
self.assertGreaterEqual(learner_count, 1) # noqa: PT009
def test_enrollment_counts_by_mode(self):
"""
Test that enrollment counts include all configured modes,
even those with zero enrollments.
"""
# Configure modes for the course: audit, verified, honor, and professional
for mode_slug in ('audit', 'verified', 'honor', 'professional'):
CourseModeFactory.create(course_id=self.course_key, mode_slug=mode_slug)
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
enrollment_counts = response.data['enrollment_counts']
# All configured modes should be present
self.assertIn('audit', enrollment_counts) # noqa: PT009
self.assertIn('verified', enrollment_counts) # noqa: PT009
self.assertIn('honor', enrollment_counts) # noqa: PT009
self.assertIn('professional', enrollment_counts) # noqa: PT009
self.assertIn('total', enrollment_counts) # noqa: PT009
# professional has no enrollments but should still appear with 0
self.assertEqual(enrollment_counts['professional'], 0) # noqa: PT009
# Modes with enrollments should have correct counts
self.assertGreaterEqual(enrollment_counts['audit'], 1) # noqa: PT009
self.assertGreaterEqual(enrollment_counts['verified'], 1) # noqa: PT009
self.assertGreaterEqual(enrollment_counts['honor'], 1) # noqa: PT009
self.assertGreaterEqual(enrollment_counts['total'], 3) # noqa: PT009
def test_enrollment_counts_excludes_unconfigured_modes(self):
"""
Test that enrollment counts only include modes configured for the course,
not modes that exist on other courses.
"""
# Only configure audit and honor for this course (not verified)
CourseModeFactory.create(course_id=self.course_key, mode_slug='audit')
CourseModeFactory.create(course_id=self.course_key, mode_slug='honor')
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
enrollment_counts = response.data['enrollment_counts']
# Only configured modes should appear
self.assertIn('audit', enrollment_counts) # noqa: PT009
self.assertIn('honor', enrollment_counts) # noqa: PT009
self.assertIn('total', enrollment_counts) # noqa: PT009
# verified is not configured, so it should not appear
# (even though there are verified enrollments from setUp)
self.assertNotIn('verified', enrollment_counts) # noqa: PT009
def _get_tabs_from_response(self, user, course_id=None):
"""Helper to get tabs from API response."""
self.client.force_authenticate(user=user)
response = self.client.get(self._get_url(course_id))
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
return response.data.get('tabs', [])
def _test_staff_tabs(self, tabs):
"""Helper to test tabs visible to staff users."""
tab_ids = [tab['tab_id'] for tab in tabs]
# Staff should see these basic tabs (course_team is restricted to instructor/forum_admin)
expected_basic_tabs = ['course_info', 'enrollments', 'grading', 'cohorts']
assert tab_ids == expected_basic_tabs
def test_staff_sees_basic_tabs(self):
"""
Test that staff users see the basic set of tabs.
"""
tabs = self._get_tabs_from_response(self.staff)
self._test_staff_tabs(tabs)
def test_instructor_sees_all_basic_tabs(self):
"""
Test that instructors see all tabs that staff see.
"""
instructor_tabs = self._get_tabs_from_response(self.instructor)
tab_ids = [tab['tab_id'] for tab in instructor_tabs]
expected_tabs = ['course_info', 'enrollments', 'course_team', 'grading', 'cohorts']
assert tab_ids == expected_tabs
def test_researcher_sees_all_basic_tabs(self):
"""
Test that instructors see all tabs that staff see.
"""
tabs = self._get_tabs_from_response(self.data_researcher)
tab_ids = [tab['tab_id'] for tab in tabs]
self.assertEqual(['data_downloads'], tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.is_enabled_for_course')
def test_date_extensions_tab_when_enabled(self, mock_is_enabled):
"""
Test that date_extensions tab appears when edx-when is enabled for the course.
"""
mock_is_enabled.return_value = True
tabs = self._get_tabs_from_response(self.instructor)
tab_ids = [tab['tab_id'] for tab in tabs]
self.assertIn('date_extensions', tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.modulestore')
def test_open_responses_tab_with_openassessment_blocks(self, mock_modulestore):
"""
Test that open_responses tab appears when course has openassessment blocks.
"""
# Mock openassessment block
mock_block = Mock()
mock_block.parent = Mock() # Has a parent (not orphaned)
mock_store = Mock()
mock_store.get_items.return_value = [mock_block]
mock_store.get_course_errors.return_value = []
mock_modulestore.return_value = mock_store
tabs = self._get_tabs_from_response(self.staff)
tab_ids = [tab['tab_id'] for tab in tabs]
self.assertIn('open_responses', tab_ids) # noqa: PT009
@patch('django.conf.settings.FEATURES', {'ENABLE_SPECIAL_EXAMS': True, 'MAX_ENROLLMENT_INSTR_BUTTONS': 200})
def test_special_exams_tab_with_proctored_exams_enabled(self):
"""
Test that special_exams tab appears when course has proctored exams enabled.
"""
tabs = self._get_tabs_from_response(self.instructor)
tab_ids = [tab['tab_id'] for tab in tabs]
self.assertIn('special_exams', tab_ids) # noqa: PT009
@patch('django.conf.settings.FEATURES', {'ENABLE_SPECIAL_EXAMS': True, 'MAX_ENROLLMENT_INSTR_BUTTONS': 200})
def test_special_exams_tab_with_timed_exams_enabled(self):
"""
Test that special_exams tab appears when course has timed exams enabled.
"""
# Create course with timed exams
timed_course = CourseFactory.create(
org='edX',
number='Timed',
run='2024',
enable_timed_exams=True,
)
CourseInstructorRole(timed_course.id).add_users(self.instructor)
tabs = self._get_tabs_from_response(self.instructor, course_id=timed_course.id)
tab_ids = [tab['tab_id'] for tab in tabs]
self.assertIn('special_exams', tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.CertificateGenerationConfiguration.current')
@patch('django.conf.settings.FEATURES', {'ENABLE_CERTIFICATES_INSTRUCTOR_MANAGE': True,
'MAX_ENROLLMENT_INSTR_BUTTONS': 200})
def test_certificates_tab_for_instructor_when_enabled(self, mock_cert_config):
"""
Test that certificates tab appears for instructors when certificate management is enabled.
"""
mock_config = Mock()
mock_config.enabled = True
mock_cert_config.return_value = mock_config
tabs = self._get_tabs_from_response(self.instructor)
tab_ids = [tab['tab_id'] for tab in tabs]
self.assertIn('certificates', tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.CertificateGenerationConfiguration.current')
def test_certificates_tab_for_admin_visible(self, mock_cert_config):
"""
Test that certificates tab appears for admin users when certificates are enabled.
"""
mock_config = Mock()
mock_config.enabled = True
mock_cert_config.return_value = mock_config
tabs = self._get_tabs_from_response(self.admin)
tab_ids = [tab['tab_id'] for tab in tabs]
self.assertIn('certificates', tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.is_bulk_email_feature_enabled')
@ddt.data('staff', 'instructor', 'admin')
def test_bulk_email_tab_when_enabled(self, user_attribute, mock_bulk_email_enabled):
"""
Test that the bulk_email tab appears for all staff-level users when is_bulk_email_feature_enabled is True.
"""
mock_bulk_email_enabled.return_value = True
user = getattr(self, user_attribute)
tabs = self._get_tabs_from_response(user)
tab_ids = [tab['tab_id'] for tab in tabs]
self.assertIn('bulk_email', tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.is_bulk_email_feature_enabled')
@ddt.data(
(False, 'staff'),
(False, 'instructor'),
(False, 'admin'),
(True, 'data_researcher'),
)
@ddt.unpack
def test_bulk_email_tab_not_visible(self, feature_enabled, user_attribute, mock_bulk_email_enabled):
"""
Test that the bulk_email tab does not appear when is_bulk_email_feature_enabled is False or the user is not
a user with staff permissions.
"""
mock_bulk_email_enabled.return_value = feature_enabled
user = getattr(self, user_attribute)
tabs = self._get_tabs_from_response(user)
tab_ids = [tab['tab_id'] for tab in tabs]
self.assertNotIn('bulk_email', tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.is_bulk_email_feature_enabled')
@override_settings(COMMUNICATIONS_MICROFRONTEND_URL='http://localhost:1984')
def test_bulk_email_tab_url_uses_communications_mfe(self, mock_bulk_email_enabled):
"""
Test that the bulk_email tab URL uses COMMUNICATIONS_MICROFRONTEND_URL,
not INSTRUCTOR_MICROFRONTEND_URL.
"""
mock_bulk_email_enabled.return_value = True
tabs = self._get_tabs_from_response(self.staff)
bulk_email_tab = next((tab for tab in tabs if tab['tab_id'] == 'bulk_email'), None)
self.assertIsNotNone(bulk_email_tab) # noqa: PT009
expected_url = f'http://localhost:1984/courses/{self.course.id}/bulk_email'
self.assertEqual(bulk_email_tab['url'], expected_url) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.is_bulk_email_feature_enabled')
@override_settings(COMMUNICATIONS_MICROFRONTEND_URL=None)
def test_bulk_email_tab_logs_warning_when_communications_mfe_url_not_set(self, mock_bulk_email_enabled):
"""
Test that a warning is logged when COMMUNICATIONS_MICROFRONTEND_URL is not set,
and the resulting URL does not contain 'None'.
"""
mock_bulk_email_enabled.return_value = True
with self.assertLogs('lms.djangoapps.instructor.views.serializers_v2', level='WARNING') as cm:
tabs = self._get_tabs_from_response(self.staff)
self.assertTrue( # noqa: PT009
any('COMMUNICATIONS_MICROFRONTEND_URL is not configured' in msg for msg in cm.output)
)
bulk_email_tab = next((tab for tab in tabs if tab['tab_id'] == 'bulk_email'), None)
self.assertIsNotNone(bulk_email_tab) # noqa: PT009
self.assertFalse( # noqa: PT009
bulk_email_tab['url'].startswith('None'),
f"Tab URL should not start with 'None': {bulk_email_tab['url']}"
)
def test_tabs_have_sort_order(self):
"""
Test that all tabs include a sort_order field.
"""
tabs = self._get_tabs_from_response(self.staff)
for tab in tabs:
self.assertIn('sort_order', tab) # noqa: PT009
self.assertIsInstance(tab['sort_order'], int) # noqa: PT009
def test_disable_buttons_false_for_small_course(self):
"""
Test that disable_buttons is False for courses with <=200 enrollments.
"""
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
# With only 3 enrollments, buttons should not be disabled
self.assertFalse(response.data['disable_buttons']) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.modulestore')
def test_course_errors_from_modulestore(self, mock_modulestore):
"""
Test that course errors from modulestore are included in response.
"""
mock_store = Mock()
mock_store.get_course_errors.return_value = [(Exception("Test error"), '')]
mock_store.get_items.return_value = []
mock_modulestore.return_value = mock_store
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
self.assertIn('course_errors', response.data) # noqa: PT009
self.assertIsInstance(response.data['course_errors'], list) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.settings.INSTRUCTOR_MICROFRONTEND_URL', None)
def test_tabs_log_warning_when_mfe_url_not_set(self):
"""
Test that a warning is logged when INSTRUCTOR_MICROFRONTEND_URL is not set.
"""
with self.assertLogs('lms.djangoapps.instructor.views.serializers_v2', level='WARNING') as cm:
tabs = self._get_tabs_from_response(self.staff)
self.assertTrue( # noqa: PT009
any('INSTRUCTOR_MICROFRONTEND_URL is not configured' in msg for msg in cm.output)
)
# Tab URLs should use empty string as base, not "None"
for tab in tabs:
self.assertFalse(tab['url'].startswith('None'), f"Tab URL should not start with 'None': {tab['url']}") # noqa: PT009 # pylint: disable=line-too-long
self.assertTrue( # noqa: PT009
tab['url'].startswith(f'/{self.course.id}/'),
f"Tab URL should start with '/{self.course.id}/': {tab['url']}"
)
def test_pacing_self_for_self_paced_course(self):
"""
Test that pacing is 'self' for self-paced courses.
"""
# Create a self-paced course
self_paced_course = CourseFactory.create(
org='edX',
number='SelfPaced',
run='SP1',
self_paced=True,
)
instructor = InstructorFactory.create(course_key=self_paced_course.id)
self.client.force_authenticate(user=instructor)
url = reverse('instructor_api_v2:course_metadata', kwargs={'course_id': str(self_paced_course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
self.assertEqual(response.data['pacing'], 'self') # noqa: PT009
class BuildTabUrlTest(SimpleTestCase):
"""
Unit tests for CourseInformationSerializerV2._build_tab_url.
Tests the helper directly to verify URL joining behavior without
going through the full API stack.
"""
def _build(self, setting_name, *parts, strip_url=True):
return CourseInformationSerializerV2._build_tab_url(setting_name, *parts, strip_url=strip_url) # pylint: disable=protected-access
@override_settings(INSTRUCTOR_MICROFRONTEND_URL='http://localhost:2003/instructor-dashboard')
def test_joins_base_and_path_parts(self):
"""Parts are joined with '/' separators."""
result = self._build('INSTRUCTOR_MICROFRONTEND_URL', 'course-v1:edX+DemoX+Demo', 'grading')
self.assertEqual(result, '/instructor-dashboard/course-v1:edX+DemoX+Demo/grading') # noqa: PT009
@override_settings(INSTRUCTOR_MICROFRONTEND_URL='http://localhost:2003/instructor-dashboard/')
def test_strips_trailing_slash_from_base(self):
"""A trailing slash on the base URL does not produce a double slash."""
result = self._build('INSTRUCTOR_MICROFRONTEND_URL', 'course-v1:edX+DemoX+Demo', 'grading')
self.assertEqual(result, '/instructor-dashboard/course-v1:edX+DemoX+Demo/grading') # noqa: PT009
@override_settings(INSTRUCTOR_MICROFRONTEND_URL='http://localhost:2003/instructor-dashboard')
def test_strips_slashes_from_path_parts(self):
"""Leading and trailing slashes on path parts are stripped before joining."""
result = self._build('INSTRUCTOR_MICROFRONTEND_URL', '/course-v1:edX+DemoX+Demo/', '/grading/')
self.assertEqual(result, '/instructor-dashboard/course-v1:edX+DemoX+Demo/grading') # noqa: PT009
@override_settings(COMMUNICATIONS_MICROFRONTEND_URL=None)
def test_logs_warning_and_returns_relative_url_when_setting_is_none(self):
"""When the setting is None, a warning is logged and the URL is relative (no 'None' prefix)."""
with self.assertLogs('lms.djangoapps.instructor.views.serializers_v2', level='WARNING') as cm:
result = self._build(
'COMMUNICATIONS_MICROFRONTEND_URL', 'courses', 'course-v1:edX+DemoX+Demo', 'bulk_email'
)
self.assertTrue(any('COMMUNICATIONS_MICROFRONTEND_URL is not configured' in msg for msg in cm.output)) # noqa: PT009 # pylint: disable=line-too-long
self.assertFalse(result.startswith('None')) # noqa: PT009
self.assertEqual(result, '/courses/course-v1:edX+DemoX+Demo/bulk_email') # noqa: PT009
def test_logs_warning_when_setting_does_not_exist(self):
"""When the setting name is not defined at all, behavior matches the None case."""
with self.assertLogs('lms.djangoapps.instructor.views.serializers_v2', level='WARNING') as cm:
result = self._build('NONEXISTENT_MFE_URL', 'course-v1:edX+DemoX+Demo', 'grading')
self.assertTrue(any('NONEXISTENT_MFE_URL is not configured' in msg for msg in cm.output)) # noqa: PT009
self.assertEqual(result, '/course-v1:edX+DemoX+Demo/grading') # noqa: PT009
@override_settings(COMMUNICATIONS_MICROFRONTEND_URL='http://localhost:1984/communications/')
def test_base_with_subpath_and_trailing_slash(self):
"""Base URL with a subpath and trailing slash is joined cleanly."""
result = self._build(
"COMMUNICATIONS_MICROFRONTEND_URL", "courses", "course-v1:edX+DemoX+Demo", "bulk_email", strip_url=False
)
self.assertEqual(result, 'http://localhost:1984/communications/courses/course-v1:edX+DemoX+Demo/bulk_email') # noqa: PT009 # pylint: disable=line-too-long
@ddt.ddt
class InstructorTaskListViewTest(SharedModuleStoreTestCase):
"""
Tests for the InstructorTaskListView API endpoint.
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.course = CourseFactory.create(
org='edX',
number='TestX',
run='Test_Course',
display_name='Test Course',
)
cls.course_key = cls.course.id
# Create a problem block for testing
cls.chapter = BlockFactory.create(
parent=cls.course,
category='chapter',
display_name='Test Chapter'
)
cls.sequential = BlockFactory.create(
parent=cls.chapter,
category='sequential',
display_name='Test Sequential'
)
cls.vertical = BlockFactory.create(
parent=cls.sequential,
category='vertical',
display_name='Test Vertical'
)
cls.problem = BlockFactory.create(
parent=cls.vertical,
category='problem',
display_name='Test Problem'
)
cls.problem_location = str(cls.problem.location)
def setUp(self):
super().setUp()
self.client = APIClient()
self.instructor = InstructorFactory.create(course_key=self.course_key)
self.student = UserFactory.create()
def _get_url(self, course_id=None):
"""Helper to get the API URL."""
if course_id is None:
course_id = str(self.course_key)
return reverse('instructor_api_v2:instructor_tasks', kwargs={'course_id': course_id})
def test_get_instructor_tasks_as_instructor(self):
"""
Test that an instructor can retrieve instructor tasks.
"""
# Create a test task
task_id = str(uuid4())
InstructorTaskFactory.create(
course_id=self.course_key,
task_type='grade_problems',
task_state='PROGRESS',
requester=self.instructor,
task_id=task_id,
task_key="dummy key",
)
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
self.assertIn('tasks', response.data) # noqa: PT009
self.assertIsInstance(response.data['tasks'], list) # noqa: PT009
def test_get_instructor_tasks_unauthorized(self):
"""
Test that students cannot access instructor tasks endpoint.
"""
self.client.force_authenticate(user=self.student)
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
self.assertIn('You do not have permission to perform this action.', response.data['developer_message']) # noqa: PT009 # pylint: disable=line-too-long
def test_get_instructor_tasks_unauthenticated(self):
"""
Test that unauthenticated users cannot access the endpoint.
"""
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_get_instructor_tasks_nonexistent_course(self):
"""
Test error handling for non-existent course.
"""
self.client.force_authenticate(user=self.instructor)
nonexistent_course_id = 'course-v1:edX+NonExistent+2024'
response = self.client.get(self._get_url(course_id=nonexistent_course_id))
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
self.assertEqual('Course not found: course-v1:edX+NonExistent+2024.', response.data['developer_message']) # noqa: PT009 # pylint: disable=line-too-long
def test_filter_by_problem_location(self):
"""
Test filtering tasks by problem location.
"""
self.client.force_authenticate(user=self.instructor)
params = {
'problem_location_str': self.problem_location,
}
url = f"{self._get_url()}?{urlencode(params)}"
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
self.assertIn('tasks', response.data) # noqa: PT009
def test_filter_requires_problem_location_with_student(self):
"""
Test that student identifier requires problem location.
"""
self.client.force_authenticate(user=self.instructor)
self.client.force_authenticate(user=self.instructor)
params = {
'unique_student_identifier': self.student.email,
}
url = f"{self._get_url()}?{urlencode(params)}"
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
self.assertIn('error', response.data) # noqa: PT009
self.assertIn('problem_location_str', response.data['error']) # noqa: PT009
def test_filter_by_problem_and_student(self):
"""
Test filtering tasks by both problem location and student identifier.
"""
# Enroll the student
CourseEnrollmentFactory.create(
user=self.student,
course_id=self.course_key,
is_active=True
)
StudentModule.objects.create(
student=self.student,
course_id=self.course.id,
module_state_key=self.problem_location,
state=json.dumps({'attempts': 10}),
)
task_id = str(uuid4())
InstructorTaskFactory.create(
course_id=self.course_key,
task_state='PROGRESS',
requester=self.student,
task_id=task_id,
task_key="dummy key",
)
self.client.force_authenticate(user=self.instructor)
params = {
'problem_location_str': self.problem_location,
'unique_student_identifier': self.student.email,
}
url = f"{self._get_url()}?{urlencode(params)}"
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
self.assertIn('tasks', response.data) # noqa: PT009
def test_invalid_student_identifier(self):
"""
Test error handling for invalid student identifier.
"""
self.client.force_authenticate(user=self.instructor)
params = {
'problem_location_str': self.problem_location,
'unique_student_identifier': '[email protected]',
}
url = f"{self._get_url()}?{urlencode(params)}"
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
self.assertIn('error', response.data) # noqa: PT009
def test_invalid_problem_location(self):
"""
Test error handling for invalid problem location.
"""
self.client.force_authenticate(user=self.instructor)
url = f"{self._get_url()}?problem_location_str=invalid-location"
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
self.assertIn('error', response.data) # noqa: PT009
self.assertIn('Invalid problem location', response.data['error']) # noqa: PT009
@ddt.data(
('grade_problems', 'PROGRESS'),
('rescore_problem', 'SUCCESS'),
('reset_student_attempts', 'FAILURE'),
)
@ddt.unpack
def test_various_task_types_and_states(self, task_type, task_state):
"""
Test that various task types and states are properly returned.
"""
task_id = str(uuid4())
InstructorTaskFactory.create(
course_id=self.course_key,
task_type=task_type,
task_state=task_state,
requester=self.instructor,
task_id=task_id,
task_key="dummy key",
)
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
self.assertIn('tasks', response.data) # noqa: PT009
if task_state == 'PROGRESS':
self.assertEqual(task_id, response.data['tasks'][0]['task_id']) # noqa: PT009
self.assertEqual(task_type, response.data['tasks'][0]['task_type']) # noqa: PT009
self.assertEqual(task_state, response.data['tasks'][0]['task_state']) # noqa: PT009
def test_task_data_structure(self):
"""
Test that task data contains expected fields from extract_task_features.
"""
task_id = str(uuid4())
InstructorTaskFactory.create(
course_id=self.course_key,
task_type='grade_problems',
task_state='PROGRESS',
requester=self.instructor,
task_id=task_id,
task_key="dummy key",
)
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
tasks = response.data['tasks']
if tasks:
task_data = tasks[0]
# Verify key fields are present (these come from extract_task_features)
self.assertIn('task_type', task_data) # noqa: PT009
self.assertIn('task_state', task_data) # noqa: PT009
self.assertIn('created', task_data) # noqa: PT009
@ddt.ddt
class GradedSubsectionsViewTest(SharedModuleStoreTestCase):
"""
Tests for the GradedSubsectionsView API endpoint.
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.course = CourseFactory.create(
org='edX',
number='DemoX',
run='Demo_Course',
display_name='Demonstration Course',
)
cls.course_key = cls.course.id
def setUp(self):
super().setUp()
self.client = APIClient()
self.instructor = InstructorFactory.create(course_key=self.course_key)
self.staff = StaffFactory.create(course_key=self.course_key)
self.student = UserFactory.create()
CourseEnrollmentFactory.create(
user=self.student,
course_id=self.course_key,
mode='audit',
is_active=True
)
# Create some subsections with due dates
self.chapter = BlockFactory.create(
parent=self.course,
category='chapter',
display_name='Test Chapter'
)
self.due_date = datetime(2024, 12, 31, 23, 59, 59, tzinfo=UTC)
self.subsection_with_due_date = BlockFactory.create(
parent=self.chapter,
category='sequential',
display_name='Homework 1',
due=self.due_date
)
self.subsection_without_due_date = BlockFactory.create(
parent=self.chapter,
category='sequential',
display_name='Reading Material'