-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathtest_course_settings.py
2023 lines (1791 loc) · 88.6 KB
/
test_course_settings.py
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
"""
Tests for Studio Course Settings.
"""
import copy
import datetime
import json
import unittest
from unittest import mock
from unittest.mock import Mock, patch
import ddt
from crum import set_current_request
from django.conf import settings
from django.test import RequestFactory
from django.test.utils import override_settings
from edx_toggles.toggles.testutils import override_waffle_flag
from milestones.models import MilestoneRelationshipType
from milestones.tests.utils import MilestonesTestCaseMixin
from pytz import UTC
from cms.djangoapps.contentstore.utils import reverse_course_url, reverse_usage_url
from cms.djangoapps.models.settings.course_grading import (
GRADING_POLICY_CHANGED_EVENT_TYPE,
CourseGradingModel,
hash_grading_policy
)
from cms.djangoapps.models.settings.course_metadata import CourseMetadata
from cms.djangoapps.models.settings.encoder import CourseSettingsEncoder
from cms.djangoapps.models.settings.waffle import MATERIAL_RECOMPUTE_ONLY_FLAG
from common.djangoapps.course_modes.models import CourseMode
from common.djangoapps.student.roles import CourseInstructorRole, CourseStaffRole
from common.djangoapps.student.tests.factories import UserFactory
from common.djangoapps.util import milestones_helpers
from common.djangoapps.xblock_django.models import XBlockStudioConfigurationFlag
from openedx.core.djangoapps.discussions.config.waffle import (
ENABLE_PAGES_AND_RESOURCES_MICROFRONTEND,
OVERRIDE_DISCUSSION_LEGACY_SETTINGS_FLAG
)
from openedx.core.djangoapps.models.course_details import CourseDetails
from openedx.core.lib.teams_config import TeamsConfig
from xmodule.fields import Date # lint-amnesty, pylint: disable=wrong-import-order
from xmodule.modulestore.django import modulestore # lint-amnesty, pylint: disable=wrong-import-order
from xmodule.modulestore.tests.factories import CourseFactory # lint-amnesty, pylint: disable=wrong-import-order
from .utils import AjaxEnabledTestClient, CourseTestCase
def get_url(course_id, handler_name='settings_handler'):
return reverse_course_url(handler_name, course_id)
class CourseSettingsEncoderTest(CourseTestCase):
"""
Tests for CourseSettingsEncoder.
"""
def test_encoder(self):
details = CourseDetails.fetch(self.course.id)
jsondetails = json.dumps(details, cls=CourseSettingsEncoder)
jsondetails = json.loads(jsondetails)
self.assertEqual(jsondetails['course_image_name'], self.course.course_image)
self.assertIsNone(jsondetails['end_date'], "end date somehow initialized ")
self.assertIsNone(jsondetails['enrollment_start'], "enrollment_start date somehow initialized ")
self.assertIsNone(jsondetails['enrollment_end'], "enrollment_end date somehow initialized ")
self.assertIsNone(jsondetails['syllabus'], "syllabus somehow initialized")
self.assertIsNone(jsondetails['intro_video'], "intro_video somehow initialized")
self.assertIsNone(jsondetails['effort'], "effort somehow initialized")
self.assertIsNone(jsondetails['language'], "language somehow initialized")
def test_pre_1900_date(self):
"""
Tests that the encoder can handle a pre-1900 date, since strftime
doesn't work for these dates.
"""
details = CourseDetails.fetch(self.course.id)
pre_1900 = datetime.datetime(1564, 4, 23, 1, 1, 1, tzinfo=UTC)
details.enrollment_start = pre_1900
dumped_jsondetails = json.dumps(details, cls=CourseSettingsEncoder)
loaded_jsondetails = json.loads(dumped_jsondetails)
self.assertEqual(loaded_jsondetails['enrollment_start'], pre_1900.isoformat())
def test_ooc_encoder(self):
"""
Test the encoder out of its original constrained purpose to see if it functions for general use
"""
details = {
'number': 1,
'string': 'string',
'datetime': datetime.datetime.now(UTC)
}
jsondetails = json.dumps(details, cls=CourseSettingsEncoder)
jsondetails = json.loads(jsondetails)
self.assertEqual(1, jsondetails['number'])
self.assertEqual(jsondetails['string'], 'string')
@ddt.ddt
class CourseAdvanceSettingViewTest(CourseTestCase, MilestonesTestCaseMixin):
"""
Tests for AdvanceSettings View.
"""
def setUp(self):
super().setUp()
self.fullcourse = CourseFactory.create()
self.course_setting_url = get_url(self.course.id, 'advanced_settings_handler')
self.non_staff_client, self.nonstaff = self.create_non_staff_authed_user_client()
# "nonstaff" means "non Django staff" here. We assign this user to course staff
# role to check that even so they won't have advanced settings access when explicitly
# restricted.
CourseStaffRole(self.course.id).add_users(self.nonstaff)
@override_settings(FEATURES={'DISABLE_MOBILE_COURSE_AVAILABLE': True})
def test_mobile_field_available(self):
"""
Test to check `Mobile Course Available` field is not viewable in Studio
when DISABLE_MOBILE_COURSE_AVAILABLE is true.
"""
response = self.client.get_html(self.course_setting_url)
start = response.content.decode('utf-8').find("mobile_available")
end = response.content.decode('utf-8').find("}", start)
settings_fields = json.loads(response.content.decode('utf-8')[start + len("mobile_available: "):end + 1])
self.assertEqual(settings_fields["display_name"], "Mobile Course Available")
self.assertEqual(settings_fields["deprecated"], True)
@ddt.data(
(False, False, True),
(True, False, False),
(True, True, True),
(False, True, True)
)
@ddt.unpack
def test_discussion_fields_available(self, is_pages_and_resources_enabled,
is_legacy_discussion_setting_enabled, fields_visible):
"""
Test to check the availability of discussion related fields when relevant flags are enabled
"""
with override_waffle_flag(ENABLE_PAGES_AND_RESOURCES_MICROFRONTEND, is_pages_and_resources_enabled):
with override_waffle_flag(OVERRIDE_DISCUSSION_LEGACY_SETTINGS_FLAG, is_legacy_discussion_setting_enabled):
response = self.client.get_html(self.course_setting_url).content.decode('utf-8')
self.assertEqual('allow_anonymous' in response, fields_visible)
self.assertEqual('allow_anonymous_to_peers' in response, fields_visible)
self.assertEqual('discussion_blackouts' in response, fields_visible)
self.assertEqual('discussion_topics' in response, fields_visible)
@ddt.data(False, True)
def test_disable_advanced_settings_feature(self, disable_advanced_settings):
"""
If this feature is enabled, only Django Staff/Superuser should be able to access the "Advanced Settings" page.
For non-staff users the "Advanced Settings" tab link should not be visible.
"""
advanced_settings_link_html = f"<a href=\"{self.course_setting_url}\">Advanced Settings</a>".encode('utf-8')
with override_settings(FEATURES={'DISABLE_ADVANCED_SETTINGS': disable_advanced_settings}):
for handler in (
'import_handler',
'export_handler',
'course_team_handler',
'course_info_handler',
'assets_handler',
'tabs_handler',
'settings_handler',
'grading_handler',
'textbooks_list_handler',
):
# Test that non-staff users don't see the "Advanced Settings" tab link.
response = self.non_staff_client.get_html(
get_url(self.course.id, handler)
)
self.assertEqual(response.status_code, 200)
if disable_advanced_settings:
self.assertNotIn(advanced_settings_link_html, response.content)
else:
self.assertIn(advanced_settings_link_html, response.content)
# Test that staff users see the "Advanced Settings" tab link.
response = self.client.get_html(
get_url(self.course.id, handler)
)
self.assertEqual(response.status_code, 200)
self.assertIn(advanced_settings_link_html, response.content)
# Test that non-staff users can't access the "Advanced Settings" page.
response = self.non_staff_client.get_html(self.course_setting_url)
self.assertEqual(response.status_code, 403 if disable_advanced_settings else 200)
# Test that staff users can access the "Advanced Settings" page.
response = self.client.get_html(self.course_setting_url)
self.assertEqual(response.status_code, 200)
@ddt.ddt
class CourseDetailsViewTest(CourseTestCase, MilestonesTestCaseMixin):
"""
Tests for modifying content on the first course settings page (course dates, overview, etc.).
"""
def alter_field(self, url, details, field, val):
"""
Change the one field to the given value and then invoke the update post to see if it worked.
"""
setattr(details, field, val)
# Need to partially serialize payload b/c the mock doesn't handle it correctly
payload = copy.copy(details.__dict__)
payload['start_date'] = CourseDetailsViewTest.convert_datetime_to_iso(details.start_date)
payload['end_date'] = CourseDetailsViewTest.convert_datetime_to_iso(details.end_date)
payload['enrollment_start'] = CourseDetailsViewTest.convert_datetime_to_iso(details.enrollment_start)
payload['enrollment_end'] = CourseDetailsViewTest.convert_datetime_to_iso(details.enrollment_end)
resp = self.client.ajax_post(url, payload)
self.compare_details_with_encoding(json.loads(resp.content.decode('utf-8')), details.__dict__, field + str(val))
MilestoneRelationshipType.objects.get_or_create(name='requires')
MilestoneRelationshipType.objects.get_or_create(name='fulfills')
@staticmethod
def convert_datetime_to_iso(datetime_obj):
"""
Use the xblock serializer to convert the datetime
"""
return Date().to_json(datetime_obj)
def test_update_and_fetch(self):
details = CourseDetails.fetch(self.course.id)
# resp s/b json from here on
url = get_url(self.course.id)
resp = self.client.get_json(url)
self.compare_details_with_encoding(json.loads(resp.content.decode('utf-8')), details.__dict__, "virgin get")
self.alter_field(url, details, 'start_date', datetime.datetime(2012, 11, 12, 1, 30, tzinfo=UTC))
self.alter_field(url, details, 'start_date', datetime.datetime(2012, 11, 1, 13, 30, tzinfo=UTC))
self.alter_field(url, details, 'end_date', datetime.datetime(2013, 2, 12, 1, 30, tzinfo=UTC))
self.alter_field(url, details, 'enrollment_start', datetime.datetime(2012, 10, 12, 1, 30, tzinfo=UTC))
self.alter_field(url, details, 'enrollment_end', datetime.datetime(2012, 11, 15, 1, 30, tzinfo=UTC))
self.alter_field(url, details, 'short_description', "Short Description")
self.alter_field(url, details, 'about_sidebar_html', "About Sidebar HTML")
self.alter_field(url, details, 'overview', "Overview")
self.alter_field(url, details, 'intro_video', "intro_video")
self.alter_field(url, details, 'effort', "effort")
self.alter_field(url, details, 'course_image_name', "course_image_name")
self.alter_field(url, details, 'language', "en")
self.alter_field(url, details, 'self_paced', "true")
def compare_details_with_encoding(self, encoded, details, context):
"""
compare all of the fields of the before and after dicts
"""
self.compare_date_fields(details, encoded, context, 'start_date')
self.compare_date_fields(details, encoded, context, 'end_date')
self.compare_date_fields(details, encoded, context, 'enrollment_start')
self.compare_date_fields(details, encoded, context, 'enrollment_end')
self.assertEqual(
details['short_description'], encoded['short_description'], context + " short_description not =="
)
self.assertEqual(
details['about_sidebar_html'], encoded['about_sidebar_html'], context + " about_sidebar_html not =="
)
self.assertEqual(details['overview'], encoded['overview'], context + " overviews not ==")
self.assertEqual(details['intro_video'], encoded.get('intro_video', None), context + " intro_video not ==")
self.assertEqual(details['effort'], encoded['effort'], context + " efforts not ==")
self.assertEqual(details['course_image_name'], encoded['course_image_name'], context + " images not ==")
self.assertEqual(details['language'], encoded['language'], context + " languages not ==")
def compare_date_fields(self, details, encoded, context, field):
"""
Compare the given date fields between the before and after doing json deserialization
"""
if details[field] is not None:
date = Date()
if field in encoded and encoded[field] is not None:
dt1 = date.from_json(encoded[field])
dt2 = details[field]
self.assertEqual(dt1, dt2, msg=f"{dt1} != {dt2} at {context}")
else:
self.fail(field + " missing from encoded but in details at " + context)
elif field in encoded and encoded[field] is not None:
self.fail(field + " included in encoding but missing from details at " + context)
@ddt.data(
(False, False),
(True, False),
(True, True),
)
@ddt.unpack
def test_upgrade_deadline(self, has_verified_mode, has_expiration_date):
if has_verified_mode:
deadline = None
if has_expiration_date:
deadline = self.course.start + datetime.timedelta(days=2)
CourseMode.objects.get_or_create(
course_id=self.course.id,
mode_display_name="Verified",
mode_slug="verified",
min_price=1,
_expiration_datetime=deadline,
)
settings_details_url = get_url(self.course.id)
response = self.client.get_html(settings_details_url)
self.assertEqual(b"Upgrade Deadline Date" in response.content, has_expiration_date and has_verified_mode)
@mock.patch.dict("django.conf.settings.FEATURES", {'ENABLE_PREREQUISITE_COURSES': True})
def test_pre_requisite_course_list_present(self):
settings_details_url = get_url(self.course.id)
response = self.client.get_html(settings_details_url)
self.assertContains(response, "Prerequisite Course")
@mock.patch.dict("django.conf.settings.FEATURES", {'ENABLE_PREREQUISITE_COURSES': True})
def test_pre_requisite_course_update_and_fetch(self):
self.assertFalse(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id),
msg='The initial empty state should be: no prerequisite courses')
url = get_url(self.course.id)
resp = self.client.get_json(url)
course_detail_json = json.loads(resp.content.decode('utf-8'))
# assert pre_requisite_courses is initialized
self.assertEqual([], course_detail_json['pre_requisite_courses'])
# update pre requisite courses with a new course keys
pre_requisite_course = CourseFactory.create(org='edX', course='900', run='test_run')
pre_requisite_course2 = CourseFactory.create(org='edX', course='902', run='test_run')
pre_requisite_course_keys = [str(pre_requisite_course.id), str(pre_requisite_course2.id)]
course_detail_json['pre_requisite_courses'] = pre_requisite_course_keys
self.client.ajax_post(url, course_detail_json)
# fetch updated course to assert pre_requisite_courses has new values
resp = self.client.get_json(url)
course_detail_json = json.loads(resp.content.decode('utf-8'))
self.assertEqual(pre_requisite_course_keys, course_detail_json['pre_requisite_courses'])
self.assertTrue(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id),
msg='Should have prerequisite courses')
# remove pre requisite course
course_detail_json['pre_requisite_courses'] = []
self.client.ajax_post(url, course_detail_json)
resp = self.client.get_json(url)
course_detail_json = json.loads(resp.content.decode('utf-8'))
self.assertEqual([], course_detail_json['pre_requisite_courses'])
self.assertFalse(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id),
msg='Should not have prerequisite courses anymore')
@mock.patch.dict("django.conf.settings.FEATURES", {'ENABLE_PREREQUISITE_COURSES': True})
def test_invalid_pre_requisite_course(self):
url = get_url(self.course.id)
resp = self.client.get_json(url)
course_detail_json = json.loads(resp.content.decode('utf-8'))
# update pre requisite courses one valid and one invalid key
pre_requisite_course = CourseFactory.create(org='edX', course='900', run='test_run')
pre_requisite_course_keys = [str(pre_requisite_course.id), 'invalid_key']
course_detail_json['pre_requisite_courses'] = pre_requisite_course_keys
response = self.client.ajax_post(url, course_detail_json)
self.assertEqual(400, response.status_code)
@ddt.data(
(False, False, False),
(True, False, True),
(False, True, False),
(True, True, True),
)
def test_visibility_of_entrance_exam_section(self, feature_flags):
"""
Tests entrance exam section is available if ENTRANCE_EXAMS feature is enabled no matter any other
feature is enabled or disabled i.e ENABLE_PUBLISHER.
"""
with patch.dict("django.conf.settings.FEATURES", {
'ENTRANCE_EXAMS': feature_flags[0],
'ENABLE_PUBLISHER': feature_flags[1]
}):
course_details_url = get_url(self.course.id)
resp = self.client.get_html(course_details_url)
self.assertEqual(
feature_flags[2],
b'<h3 id="heading-entrance-exam">' in resp.content
)
def test_marketing_site_fetch(self):
settings_details_url = get_url(self.course.id)
with mock.patch.dict('django.conf.settings.FEATURES', {
'ENABLE_PUBLISHER': True,
'ENABLE_MKTG_SITE': True,
'ENTRANCE_EXAMS': False,
'ENABLE_PREREQUISITE_COURSES': False
}):
response = self.client.get_html(settings_details_url)
self.assertNotContains(response, "Course Summary Page")
self.assertNotContains(response, "Send a note to students via email")
self.assertContains(response, "course summary page will not be viewable")
self.assertContains(response, "Course Start Date")
self.assertContains(response, "Course End Date")
self.assertContains(response, "Enrollment Start Date")
self.assertContains(response, "Enrollment End Date")
self.assertContains(response, "Course Short Description")
self.assertNotContains(response, "Course About Sidebar HTML")
self.assertNotContains(response, "Course Title")
self.assertNotContains(response, "Course Subtitle")
self.assertNotContains(response, "Course Duration")
self.assertNotContains(response, "Course Description")
self.assertNotContains(response, "Course Overview")
self.assertNotContains(response, "Course Introduction Video")
self.assertNotContains(response, "Requirements")
self.assertNotContains(response, "Course Banner Image")
self.assertNotContains(response, "Course Video Thumbnail Image")
@unittest.skipUnless(settings.FEATURES.get('ENTRANCE_EXAMS', False), True)
def test_entrance_exam_created_updated_and_deleted_successfully(self):
"""
This tests both of the entrance exam settings and the `any_unfulfilled_milestones` helper.
Splitting the test requires significant refactoring `settings_handler()` view.
"""
self.assertFalse(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id),
msg='The initial empty state should be: no entrance exam')
settings_details_url = get_url(self.course.id)
data = {
'entrance_exam_enabled': 'true',
'entrance_exam_minimum_score_pct': '60',
'syllabus': 'none',
'short_description': 'empty',
'overview': '',
'effort': '',
'intro_video': '',
'start_date': '2012-01-01',
'end_date': '2012-12-31',
}
response = self.client.post(settings_details_url, data=json.dumps(data), content_type='application/json',
HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
course = modulestore().get_course(self.course.id)
self.assertTrue(course.entrance_exam_enabled)
self.assertEqual(course.entrance_exam_minimum_score_pct, .60)
# Update the entrance exam
data['entrance_exam_enabled'] = "true"
data['entrance_exam_minimum_score_pct'] = "80"
response = self.client.post(
settings_details_url,
data=json.dumps(data),
content_type='application/json',
HTTP_ACCEPT='application/json'
)
self.assertEqual(response.status_code, 200)
course = modulestore().get_course(self.course.id)
self.assertTrue(course.entrance_exam_enabled)
self.assertEqual(course.entrance_exam_minimum_score_pct, .80)
self.assertTrue(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id),
msg='The entrance exam should be required.')
# Delete the entrance exam
data['entrance_exam_enabled'] = "false"
response = self.client.post(
settings_details_url,
data=json.dumps(data),
content_type='application/json',
HTTP_ACCEPT='application/json'
)
course = modulestore().get_course(self.course.id)
self.assertEqual(response.status_code, 200)
self.assertFalse(course.entrance_exam_enabled)
self.assertEqual(course.entrance_exam_minimum_score_pct, None)
self.assertFalse(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id),
msg='The entrance exam should not be required anymore')
@unittest.skipUnless(settings.FEATURES.get('ENTRANCE_EXAMS', False), True)
def test_entrance_exam_store_default_min_score(self):
"""
test that creating an entrance exam should store the default value, if key missing in json request
or entrance_exam_minimum_score_pct is an empty string
"""
settings_details_url = get_url(self.course.id)
test_data_1 = {
'entrance_exam_enabled': 'true',
'syllabus': 'none',
'short_description': 'empty',
'overview': '',
'effort': '',
'intro_video': '',
'start_date': '2012-01-01',
'end_date': '2012-12-31',
}
response = self.client.post(
settings_details_url,
data=json.dumps(test_data_1),
content_type='application/json',
HTTP_ACCEPT='application/json'
)
self.assertEqual(response.status_code, 200)
course = modulestore().get_course(self.course.id)
self.assertTrue(course.entrance_exam_enabled)
# entrance_exam_minimum_score_pct is not present in the request so default value should be saved.
self.assertEqual(course.entrance_exam_minimum_score_pct, .5)
#add entrance_exam_minimum_score_pct with empty value in json request.
test_data_2 = {
'entrance_exam_enabled': 'true',
'entrance_exam_minimum_score_pct': '',
'syllabus': 'none',
'short_description': 'empty',
'overview': '',
'effort': '',
'intro_video': '',
'start_date': '2012-01-01',
'end_date': '2012-12-31',
}
response = self.client.post(
settings_details_url,
data=json.dumps(test_data_2),
content_type='application/json',
HTTP_ACCEPT='application/json'
)
self.assertEqual(response.status_code, 200)
course = modulestore().get_course(self.course.id)
self.assertTrue(course.entrance_exam_enabled)
self.assertEqual(course.entrance_exam_minimum_score_pct, .5)
@unittest.skipUnless(settings.FEATURES.get('ENTRANCE_EXAMS', False), True)
@mock.patch.dict("django.conf.settings.FEATURES", {'ENABLE_PREREQUISITE_COURSES': True})
def test_entrance_after_changing_other_setting(self):
"""
Test entrance exam is not deactivated when prerequisites removed.
This test ensures that the entrance milestone is not deactivated after
course details are saves without pre-requisite courses active.
The test was implemented after a bug fixing, correcting the behaviour
that every time course details were saved,
if there wasn't any pre-requisite course in the POST
the view just deleted all the pre-requisite courses, including entrance exam,
despite the fact that the entrance_exam_enabled was True.
"""
assert not milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id), \
'The initial empty state should be: no entrance exam'
settings_details_url = get_url(self.course.id)
data = {
'entrance_exam_enabled': 'true',
'entrance_exam_minimum_score_pct': '60',
'syllabus': 'none',
'short_description': 'empty',
'overview': '',
'effort': '',
'intro_video': '',
'start_date': '2012-01-01',
'end_date': '2012-12-31',
}
response = self.client.post(
settings_details_url,
data=json.dumps(data),
content_type='application/json',
HTTP_ACCEPT='application/json'
)
assert response.status_code == 200
course = modulestore().get_course(self.course.id)
assert course.entrance_exam_enabled
assert course.entrance_exam_minimum_score_pct == .60
assert milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id), \
'The entrance exam should be required.'
# Call the settings handler again then ensure it didn't delete the settings of the entrance exam
data.update({
'start_date': '2018-01-01',
'end_date': '{year}-12-31'.format(year=datetime.datetime.now().year + 4),
})
response = self.client.post(
settings_details_url,
data=json.dumps(data),
content_type='application/json',
HTTP_ACCEPT='application/json'
)
assert response.status_code == 200
assert milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id), \
'The entrance exam should be required.'
def test_editable_short_description_fetch(self):
settings_details_url = get_url(self.course.id)
with mock.patch.dict('django.conf.settings.FEATURES', {'EDITABLE_SHORT_DESCRIPTION': False}):
response = self.client.get_html(settings_details_url)
self.assertNotContains(response, "Course Short Description")
def test_empty_course_overview_keep_default_value(self):
"""
Test saving the course with an empty course overview.
If the overview is empty - the save method should use the default
value for the field.
"""
settings_details_url = get_url(self.course.id)
# add overview with empty value in json request.
test_data = {
'syllabus': 'none',
'short_description': 'test',
'overview': '',
'effort': '',
'intro_video': '',
'start_date': '2022-01-01',
'end_date': '2022-12-31',
}
response = self.client.post(
settings_details_url,
data=json.dumps(test_data),
content_type='application/json',
HTTP_ACCEPT='application/json'
)
course_details = CourseDetails.fetch(self.course.id)
self.assertEqual(response.status_code, 200)
self.assertEqual(course_details.overview, '<p> </p>')
def test_regular_site_fetch(self):
settings_details_url = get_url(self.course.id)
with mock.patch.dict('django.conf.settings.FEATURES', {'ENABLE_PUBLISHER': False,
'ENABLE_EXTENDED_COURSE_DETAILS': True}):
response = self.client.get_html(settings_details_url)
self.assertContains(response, "Course Summary Page")
self.assertContains(response, "Send a note to students via email")
self.assertNotContains(response, "course summary page will not be viewable")
self.assertContains(response, "Course Start Date")
self.assertContains(response, "Course End Date")
self.assertContains(response, "Enrollment Start Date")
self.assertContains(response, "Enrollment End Date")
self.assertContains(response, "Introducing Your Course")
self.assertContains(response, "Course Card Image")
self.assertContains(response, "Course Title")
self.assertContains(response, "Course Subtitle")
self.assertContains(response, "Course Duration")
self.assertContains(response, "Course Description")
self.assertContains(response, "Course Short Description")
self.assertNotContains(response, "Course About Sidebar HTML")
self.assertContains(response, "Course Overview")
self.assertContains(response, "Course Introduction Video")
self.assertContains(response, "Requirements")
self.assertContains(response, "Course Banner Image")
self.assertContains(response, "Course Video Thumbnail Image")
@ddt.ddt
class CourseGradingTest(CourseTestCase):
"""
Tests for the course settings grading page.
"""
def test_initial_grader(self):
test_grader = CourseGradingModel(self.course)
self.assertIsNotNone(test_grader.graders)
self.assertIsNotNone(test_grader.grade_cutoffs)
def test_fetch_grader(self):
test_grader = CourseGradingModel.fetch(self.course.id)
self.assertIsNotNone(test_grader.graders, "No graders")
self.assertIsNotNone(test_grader.grade_cutoffs, "No cutoffs")
for i, grader in enumerate(test_grader.graders):
subgrader = CourseGradingModel.fetch_grader(self.course.id, i)
self.assertDictEqual(grader, subgrader, str(i) + "th graders not equal")
@mock.patch('common.djangoapps.track.event_transaction_utils.uuid4')
@mock.patch('cms.djangoapps.models.settings.course_grading.tracker')
@mock.patch('cms.djangoapps.contentstore.signals.signals.GRADING_POLICY_CHANGED.send')
def test_update_from_json(self, send_signal, tracker, uuid):
uuid.return_value = "mockUUID"
self.course = CourseFactory.create()
test_grader = CourseGradingModel.fetch(self.course.id)
# there should be no event raised after this call, since nothing got modified
altered_grader = CourseGradingModel.update_from_json(self.course.id, test_grader.__dict__, self.user)
self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__, "Noop update")
test_grader.graders[0]['weight'] = test_grader.graders[0].get('weight') * 2
altered_grader = CourseGradingModel.update_from_json(self.course.id, test_grader.__dict__, self.user)
self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__, "Weight[0] * 2")
grading_policy_2 = self._grading_policy_hash_for_course()
# test for bug LMS-11485
with modulestore().bulk_operations(self.course.id):
new_grader = test_grader.graders[0].copy()
new_grader['type'] += '_foo'
new_grader['short_label'] += '_foo'
new_grader['id'] = len(test_grader.graders)
test_grader.graders.append(new_grader)
# don't use altered cached def, get a fresh one
CourseGradingModel.update_from_json(self.course.id, test_grader.__dict__, self.user)
altered_grader = CourseGradingModel.fetch(self.course.id)
self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__)
grading_policy_3 = self._grading_policy_hash_for_course()
test_grader.grade_cutoffs['D'] = 0.3
altered_grader = CourseGradingModel.update_from_json(self.course.id, test_grader.__dict__, self.user)
self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__, "cutoff add D")
grading_policy_4 = self._grading_policy_hash_for_course()
test_grader.grace_period = {'hours': 4, 'minutes': 5, 'seconds': 0}
altered_grader = CourseGradingModel.update_from_json(self.course.id, test_grader.__dict__, self.user)
self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__, "4 hour grace period")
# one for each of the calls to update_from_json()
send_signal.assert_has_calls([
# pylint: disable=line-too-long
mock.call(sender=CourseGradingModel, user_id=self.user.id, course_key=self.course.id, grading_policy_hash=grading_policy_2),
mock.call(sender=CourseGradingModel, user_id=self.user.id, course_key=self.course.id, grading_policy_hash=grading_policy_3),
mock.call(sender=CourseGradingModel, user_id=self.user.id, course_key=self.course.id, grading_policy_hash=grading_policy_4),
# pylint: enable=line-too-long
])
# one for each of the calls to update_from_json(); the last update doesn't actually change the parts of the
# policy that get hashed
tracker.emit.assert_has_calls([
mock.call(
GRADING_POLICY_CHANGED_EVENT_TYPE,
{
'course_id': str(self.course.id),
'event_transaction_type': 'edx.grades.grading_policy_changed',
'grading_policy_hash': policy_hash,
'user_id': str(self.user.id),
'event_transaction_id': 'mockUUID',
}
) for policy_hash in (
grading_policy_2, grading_policy_3, grading_policy_4
)
])
def test_must_fire_grading_event_and_signal_multiple_type(self):
"""
Verifies that 'must_fire_grading_event_and_signal' ignores (returns False) if we modify
short_label and or name
use test_must_fire_grading_event_and_signal_multiple_type_2_split to run this test only
"""
self.course = CourseFactory.create()
# .raw_grader approximates what our UI sends down. It uses decimal representation of percent
# without it, the weights would be percentages
raw_grader_list = modulestore().get_course(self.course.id).raw_grader
course_grading_model = CourseGradingModel.fetch(self.course.id)
raw_grader_list[0]['type'] += '_foo'
raw_grader_list[0]['short_label'] += '_foo'
raw_grader_list[2]['type'] += '_foo'
raw_grader_list[3]['type'] += '_foo'
result = CourseGradingModel.must_fire_grading_event_and_signal(
self.course.id,
raw_grader_list,
modulestore().get_course(self.course.id),
course_grading_model.__dict__
)
self.assertTrue(result)
@override_waffle_flag(MATERIAL_RECOMPUTE_ONLY_FLAG, True)
def test_must_fire_grading_event_and_signal_multiple_type_waffle_on(self):
"""
Verifies that 'must_fire_grading_event_and_signal' ignores (returns False) if we modify
short_label and or name
use test_must_fire_grading_event_and_signal_multiple_type_2_split to run this test only
"""
self.course = CourseFactory.create()
# .raw_grader approximates what our UI sends down. It uses decimal representation of percent
# without it, the weights would be percentages
raw_grader_list = modulestore().get_course(self.course.id).raw_grader
course_grading_model = CourseGradingModel.fetch(self.course.id)
raw_grader_list[0]['type'] += '_foo'
raw_grader_list[0]['short_label'] += '_foo'
raw_grader_list[2]['type'] += '_foo'
raw_grader_list[3]['type'] += '_foo'
result = CourseGradingModel.must_fire_grading_event_and_signal(
self.course.id,
raw_grader_list,
modulestore().get_course(self.course.id),
course_grading_model.__dict__
)
self.assertFalse(result)
def test_must_fire_grading_event_and_signal_return_true(self):
"""
Verifies that 'must_fire_grading_event_and_signal' ignores (returns False) if we modify
short_label and or name
use _2_split suffix to run this test only
"""
self.course = CourseFactory.create()
# .raw_grader approximates what our UI sends down. It uses decimal representation of percent
# without it, the weights would be percentages
raw_grader_list = modulestore().get_course(self.course.id).raw_grader
course_grading_model = CourseGradingModel.fetch(self.course.id)
raw_grader_list[0]['weight'] *= 2
raw_grader_list[0]['short_label'] += '_foo'
raw_grader_list[2]['type'] += '_foo'
raw_grader_list[3]['type'] += '_foo'
result = CourseGradingModel.must_fire_grading_event_and_signal(
self.course.id,
raw_grader_list,
modulestore().get_course(self.course.id),
course_grading_model.__dict__
)
self.assertTrue(result)
@mock.patch('common.djangoapps.track.event_transaction_utils.uuid4')
@mock.patch('cms.djangoapps.models.settings.course_grading.tracker')
@mock.patch('cms.djangoapps.contentstore.signals.signals.GRADING_POLICY_CHANGED.send')
def test_update_grader_from_json(self, send_signal, tracker, uuid):
uuid.return_value = 'mockUUID'
test_grader = CourseGradingModel.fetch(self.course.id)
altered_grader = CourseGradingModel.update_grader_from_json(
self.course.id, test_grader.graders[1], self.user
)
self.assertDictEqual(test_grader.graders[1], altered_grader, "Noop update")
test_grader.graders[1]['min_count'] = test_grader.graders[1].get('min_count') + 2
altered_grader = CourseGradingModel.update_grader_from_json(
self.course.id, test_grader.graders[1], self.user)
self.assertDictEqual(test_grader.graders[1], altered_grader, "min_count[1] + 2")
grading_policy_2 = self._grading_policy_hash_for_course()
test_grader.graders[1]['drop_count'] = test_grader.graders[1].get('drop_count') + 1
altered_grader = CourseGradingModel.update_grader_from_json(
self.course.id, test_grader.graders[1], self.user)
self.assertDictEqual(test_grader.graders[1], altered_grader, "drop_count[1] + 2")
grading_policy_3 = self._grading_policy_hash_for_course()
# one for each of the calls to update_grader_from_json()
send_signal.assert_has_calls([
# pylint: disable=line-too-long
mock.call(sender=CourseGradingModel, user_id=self.user.id, course_key=self.course.id, grading_policy_hash=grading_policy_2),
mock.call(sender=CourseGradingModel, user_id=self.user.id, course_key=self.course.id, grading_policy_hash=grading_policy_3),
# pylint: enable=line-too-long
])
# one for each of the calls to update_grader_from_json()
tracker.emit.assert_has_calls([
mock.call(
GRADING_POLICY_CHANGED_EVENT_TYPE,
{
'course_id': str(self.course.id),
'user_id': str(self.user.id),
'grading_policy_hash': policy_hash,
'event_transaction_id': 'mockUUID',
'event_transaction_type': 'edx.grades.grading_policy_changed',
}
) for policy_hash in [grading_policy_2, grading_policy_3]
], any_order=True)
@mock.patch('common.djangoapps.track.event_transaction_utils.uuid4')
@mock.patch('cms.djangoapps.models.settings.course_grading.tracker')
def test_update_cutoffs_from_json(self, tracker, uuid):
uuid.return_value = 'mockUUID'
test_grader = CourseGradingModel.fetch(self.course.id)
CourseGradingModel.update_cutoffs_from_json(self.course.id, test_grader.grade_cutoffs, self.user)
# Unlike other tests, need to actually perform a db fetch for this test since update_cutoffs_from_json
# simply returns the cutoffs you send into it, rather than returning the db contents.
altered_grader = CourseGradingModel.fetch(self.course.id)
self.assertDictEqual(test_grader.grade_cutoffs, altered_grader.grade_cutoffs, "Noop update")
grading_policy_1 = self._grading_policy_hash_for_course()
test_grader.grade_cutoffs['D'] = 0.3
CourseGradingModel.update_cutoffs_from_json(self.course.id, test_grader.grade_cutoffs, self.user)
altered_grader = CourseGradingModel.fetch(self.course.id)
self.assertDictEqual(test_grader.grade_cutoffs, altered_grader.grade_cutoffs, "cutoff add D")
grading_policy_2 = self._grading_policy_hash_for_course()
test_grader.grade_cutoffs['Pass'] = 0.75
CourseGradingModel.update_cutoffs_from_json(self.course.id, test_grader.grade_cutoffs, self.user)
altered_grader = CourseGradingModel.fetch(self.course.id)
self.assertDictEqual(test_grader.grade_cutoffs, altered_grader.grade_cutoffs, "cutoff change 'Pass'")
grading_policy_3 = self._grading_policy_hash_for_course()
# one for each of the calls to update_cutoffs_from_json()
tracker.emit.assert_has_calls([
mock.call(
GRADING_POLICY_CHANGED_EVENT_TYPE,
{
'course_id': str(self.course.id),
'event_transaction_type': 'edx.grades.grading_policy_changed',
'grading_policy_hash': policy_hash,
'user_id': str(self.user.id),
'event_transaction_id': 'mockUUID',
}
) for policy_hash in (grading_policy_1, grading_policy_2, grading_policy_3)
])
def test_delete_grace_period(self):
test_grader = CourseGradingModel.fetch(self.course.id)
CourseGradingModel.update_grace_period_from_json(
self.course.id, test_grader.grace_period, self.user
)
# update_grace_period_from_json doesn't return anything, so query the db for its contents.
altered_grader = CourseGradingModel.fetch(self.course.id)
self.assertEqual(test_grader.grace_period, altered_grader.grace_period, "Noop update")
test_grader.grace_period = {'hours': 15, 'minutes': 5, 'seconds': 30}
CourseGradingModel.update_grace_period_from_json(
self.course.id, test_grader.grace_period, self.user)
altered_grader = CourseGradingModel.fetch(self.course.id)
self.assertDictEqual(test_grader.grace_period, altered_grader.grace_period, "Adding in a grace period")
test_grader.grace_period = {'hours': 1, 'minutes': 10, 'seconds': 0}
# Now delete the grace period
CourseGradingModel.delete_grace_period(self.course.id, self.user)
# update_grace_period_from_json doesn't return anything, so query the db for its contents.
altered_grader = CourseGradingModel.fetch(self.course.id)
# Once deleted, the grace period should simply be None
self.assertEqual(None, altered_grader.grace_period, "Delete grace period")
@mock.patch('common.djangoapps.track.event_transaction_utils.uuid4')
@mock.patch('cms.djangoapps.models.settings.course_grading.tracker')
@mock.patch('cms.djangoapps.contentstore.signals.signals.GRADING_POLICY_CHANGED.send')
def test_update_section_grader_type(self, send_signal, tracker, uuid):
uuid.return_value = 'mockUUID'
# Get the block and the section_grader_type and assert they are the default values
block = modulestore().get_item(self.course.location)
section_grader_type = CourseGradingModel.get_section_grader_type(self.course.location)
self.assertEqual('notgraded', section_grader_type['graderType'])
self.assertEqual(None, block.format)
self.assertEqual(False, block.graded)
# Change the default grader type to Homework, which should also mark the section as graded
CourseGradingModel.update_section_grader_type(self.course, 'Homework', self.user)
block = modulestore().get_item(self.course.location)
section_grader_type = CourseGradingModel.get_section_grader_type(self.course.location)
grading_policy_1 = self._grading_policy_hash_for_course()
self.assertEqual('Homework', section_grader_type['graderType'])
self.assertEqual('Homework', block.format)
self.assertEqual(True, block.graded)
# Change the grader type back to notgraded, which should also unmark the section as graded
CourseGradingModel.update_section_grader_type(self.course, 'notgraded', self.user)
block = modulestore().get_item(self.course.location)
section_grader_type = CourseGradingModel.get_section_grader_type(self.course.location)
grading_policy_2 = self._grading_policy_hash_for_course()
self.assertEqual('notgraded', section_grader_type['graderType'])
self.assertEqual(None, block.format)
self.assertEqual(False, block.graded)
# one for each call to update_section_grader_type()
send_signal.assert_has_calls([
# pylint: disable=line-too-long
mock.call(sender=CourseGradingModel, user_id=self.user.id, course_key=self.course.id, grading_policy_hash=grading_policy_1),
mock.call(sender=CourseGradingModel, user_id=self.user.id, course_key=self.course.id, grading_policy_hash=grading_policy_2),
# pylint: enable=line-too-long
])
tracker.emit.assert_has_calls([
mock.call(
GRADING_POLICY_CHANGED_EVENT_TYPE,
{
'course_id': str(self.course.id),
'event_transaction_type': 'edx.grades.grading_policy_changed',
'grading_policy_hash': policy_hash,
'user_id': str(self.user.id),
'event_transaction_id': 'mockUUID',
}
) for policy_hash in (grading_policy_1, grading_policy_2)
])
def _model_from_url(self, url_base):
response = self.client.get_json(url_base)
return json.loads(response.content.decode('utf-8'))
def test_get_set_grader_types_ajax(self):
"""
Test creating and fetching the graders via ajax calls.
"""
grader_type_url_base = get_url(self.course.id, 'grading_handler')
whole_model = self._model_from_url(grader_type_url_base)
self.assertIn('graders', whole_model)
self.assertIn('grade_cutoffs', whole_model)
self.assertIn('grace_period', whole_model)
# test post/update whole
whole_model['grace_period'] = {'hours': 1, 'minutes': 30, 'seconds': 0}
response = self.client.ajax_post(grader_type_url_base, whole_model)
self.assertEqual(200, response.status_code)
whole_model = self._model_from_url(grader_type_url_base)
self.assertEqual(whole_model['grace_period'], {'hours': 1, 'minutes': 30, 'seconds': 0})
# test get one grader
self.assertGreater(len(whole_model['graders']), 1) # ensure test will make sense