forked from openedx/edx-platform
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_tasks_helper.py
2718 lines (2406 loc) · 113 KB
/
test_tasks_helper.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
"""
Unit tests for LMS instructor-initiated background tasks helper functions.
- Tests that CSV grade report generation works with unicode emails.
- Tests all of the existing reports.
"""
import os
import shutil
import tempfile
from collections import OrderedDict
from contextlib import ExitStack, contextmanager
from datetime import datetime, timedelta
from unittest.mock import ANY, MagicMock, Mock, patch
import ddt
import pytest
import unicodecsv
from django.conf import settings
from django.test.utils import override_settings
from edx_django_utils.cache import RequestCache
from freezegun import freeze_time
from pytz import UTC
import openedx.core.djangoapps.user_api.course_tag.api as course_tag_api
from xmodule.capa.tests.response_xml_factory import MultipleChoiceResponseXMLFactory # lint-amnesty, pylint: disable=wrong-import-order
from common.djangoapps.course_modes.models import CourseMode
from common.djangoapps.student.models import CourseEnrollment, CourseEnrollmentAllowed
from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory
from lms.djangoapps.certificates.data import CertificateStatuses
from lms.djangoapps.certificates.models import GeneratedCertificate
from lms.djangoapps.certificates.tests.factories import CertificateAllowlistFactory, GeneratedCertificateFactory
from lms.djangoapps.courseware.models import StudentModule
from lms.djangoapps.grades.course_data import CourseData
from lms.djangoapps.grades.models import PersistentCourseGrade, PersistentSubsectionGradeOverride
from lms.djangoapps.grades.subsection_grade import CreateSubsectionGrade
from lms.djangoapps.grades.transformer import GradesTransformer
from lms.djangoapps.instructor_analytics.basic import UNAVAILABLE, list_problem_responses
from lms.djangoapps.instructor_task.tasks_helper.certs import generate_students_certificates
from lms.djangoapps.instructor_task.tasks_helper.enrollments import upload_may_enroll_csv, upload_students_csv
from lms.djangoapps.instructor_task.tasks_helper.grades import (
ENROLLED_IN_COURSE,
NOT_ENROLLED_IN_COURSE,
CourseGradeReport,
ProblemGradeReport,
ProblemResponses,
)
from lms.djangoapps.instructor_task.tasks_helper.misc import (
cohort_students_and_upload,
upload_course_survey_report,
upload_ora2_data,
upload_ora2_submission_files,
upload_ora2_summary
)
from lms.djangoapps.instructor_task.tests.test_base import (
InstructorTaskCourseTestCase,
InstructorTaskModuleTestCase,
TestReportMixin
)
from lms.djangoapps.survey.models import SurveyAnswer, SurveyForm
from lms.djangoapps.teams.tests.factories import CourseTeamFactory, CourseTeamMembershipFactory
from lms.djangoapps.verify_student.tests.factories import SoftwareSecurePhotoVerificationFactory
from openedx.core.djangoapps.course_groups.models import CohortMembership, CourseUserGroupPartitionGroup
from openedx.core.djangoapps.course_groups.tests.helpers import CohortFactory
from openedx.core.djangoapps.credit.tests.factories import CreditCourseFactory
from openedx.core.djangoapps.user_api.partition_schemes import RandomUserPartitionScheme
from openedx.core.djangoapps.util.testing import ContentGroupTestCase, TestConditionalContent
from openedx.core.lib.teams_config import TeamsConfig
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase # lint-amnesty, pylint: disable=wrong-import-order
from xmodule.modulestore.tests.factories import CourseFactory, BlockFactory, check_mongo_calls # lint-amnesty, pylint: disable=wrong-import-order
from xmodule.partitions.partitions import Group, UserPartition # lint-amnesty, pylint: disable=wrong-import-order
# noinspection PyUnresolvedReferences
from xmodule.tests.helpers import override_descriptor_system # pylint: disable=unused-import
from ..models import ReportStore
from ..tasks_helper.utils import UPDATE_STATUS_FAILED, UPDATE_STATUS_SUCCEEDED
_TEAMS_CONFIG = TeamsConfig({
'max_size': 2,
'topics': [{'id': 'topic', 'name': 'Topic', 'description': 'A Topic'}],
})
USE_ON_DISK_GRADE_REPORT = 'lms.djangoapps.instructor_task.tasks_helper.grades.use_on_disk_grade_reporting'
class InstructorGradeReportTestCase(TestReportMixin, InstructorTaskCourseTestCase):
""" Base class for grade report tests. """
def _verify_cell_data_for_user(
self, username, course_id, column_header, expected_cell_content, num_rows=2, use_tempfile=False
):
"""
Verify cell data in the grades CSV for a particular user.
"""
with patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task'):
with patch(USE_ON_DISK_GRADE_REPORT, return_value=use_tempfile):
result = CourseGradeReport.generate(None, None, course_id, {}, 'graded')
self.assertDictContainsSubset({'attempted': num_rows, 'succeeded': num_rows, 'failed': 0}, result)
report_store = ReportStore.from_config(config_name='GRADES_DOWNLOAD')
report_csv_filename = report_store.links_for(course_id)[0][0]
report_path = report_store.path_to(course_id, report_csv_filename)
found_user = False
with report_store.storage.open(report_path) as csv_file:
for row in unicodecsv.DictReader(csv_file):
if row.get('Username') == username:
assert row[column_header] == expected_cell_content
found_user = True
assert found_user
@ddt.ddt
class TestInstructorGradeReport(InstructorGradeReportTestCase):
"""
Tests that CSV grade report generation works.
"""
def setUp(self):
super().setUp()
self.course = CourseFactory.create()
@ddt.data(True, False)
def test_unicode_emails(self, use_tempfile):
"""
Test that students with unicode characters in emails is handled.
"""
emails = ['[email protected]', 'ni\[email protected]']
for i, email in enumerate(['[email protected]', 'ni\[email protected]']):
self.create_student(f'student{i}', email)
self.current_task = Mock() # pylint: disable=attribute-defined-outside-init
self.current_task.update_state = Mock()
with patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task') as mock_current_task:
mock_current_task.return_value = self.current_task
with patch(USE_ON_DISK_GRADE_REPORT, return_value=use_tempfile):
result = CourseGradeReport.generate(None, None, self.course.id, {}, 'graded')
num_students = len(emails)
self.assertDictContainsSubset({'attempted': num_students, 'succeeded': num_students, 'failed': 0}, result)
@ddt.data(True, False)
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
@patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.iter')
def test_grading_failure(self, use_tempfile, mock_grades_iter, _mock_current_task):
"""
Test that any grading errors are properly reported in the
progress dict and uploaded to the report store.
"""
mock_grades_iter.return_value = [
(self.create_student('username', '[email protected]'), None, TypeError('Cannot grade student'))
]
with patch(USE_ON_DISK_GRADE_REPORT, return_value=use_tempfile):
result = CourseGradeReport.generate(None, None, self.course.id, {}, 'graded')
self.assertDictContainsSubset({'attempted': 1, 'succeeded': 0, 'failed': 1}, result)
report_store = ReportStore.from_config(config_name='GRADES_DOWNLOAD')
assert any(('grade_report_err' in item[0]) for item in report_store.links_for(self.course.id))
def test_cohort_data_in_grading(self):
"""
Test that cohort data is included in grades csv if cohort configuration is enabled for course.
"""
cohort_groups = ['cohort 1', 'cohort 2']
course = CourseFactory.create(cohort_config={'cohorted': True, 'auto_cohort': True,
'auto_cohort_groups': cohort_groups})
user_1 = 'user_1'
user_2 = 'user_2'
CourseEnrollment.enroll(UserFactory.create(username=user_1), course.id)
CourseEnrollment.enroll(UserFactory.create(username=user_2), course.id)
# In auto cohorting a group will be assigned to a user only when user visits a problem
# In grading calculation we only add a group in csv if group is already assigned to
# user rather than creating a group automatically at runtime
self._verify_cell_data_for_user(user_1, course.id, 'Cohort Name', '')
self._verify_cell_data_for_user(user_2, course.id, 'Cohort Name', '')
def test_unicode_cohort_data_in_grading(self):
"""
Test that cohorts can contain unicode characters.
"""
course = CourseFactory.create(cohort_config={'cohorted': True})
# Create users and manually assign cohorts
user1 = UserFactory.create(username='user1')
user2 = UserFactory.create(username='user2')
CourseEnrollment.enroll(user1, course.id)
CourseEnrollment.enroll(user2, course.id)
professor_x = 'ÞrÖfessÖr X'
magneto = 'MàgnëtÖ'
cohort1 = CohortFactory(course_id=course.id, name=professor_x)
cohort2 = CohortFactory(course_id=course.id, name=magneto)
membership1 = CohortMembership(course_user_group=cohort1, user=user1)
membership1.save()
membership2 = CohortMembership(course_user_group=cohort2, user=user2)
membership2.save()
self._verify_cell_data_for_user(user1.username, course.id, 'Cohort Name', professor_x)
self._verify_cell_data_for_user(user2.username, course.id, 'Cohort Name', magneto)
def test_unicode_user_partitions(self):
"""
Test that user partition groups can contain unicode characters.
"""
user_groups = ['ÞrÖfessÖr X', 'MàgnëtÖ']
user_partition = UserPartition(
0,
'x_man',
'X Man',
[
Group(0, user_groups[0]),
Group(1, user_groups[1])
]
)
# Create course with group configurations
self.initialize_course(
course_factory_kwargs={
'user_partitions': [user_partition]
}
)
_groups = [group.name for group in self.course.user_partitions[0].groups]
assert _groups == user_groups
def test_cohort_scheme_partition(self):
"""
Test that cohort-schemed user partitions are ignored in the
grades export.
"""
# Set up a course with 'cohort' and 'random' user partitions.
cohort_scheme_partition = UserPartition(
0,
'Cohort-schemed Group Configuration',
'Group Configuration based on Cohorts',
[Group(0, 'Group A'), Group(1, 'Group B')],
scheme_id='cohort'
)
experiment_group_a = Group(2, 'Expériment Group A')
experiment_group_b = Group(3, 'Expériment Group B')
experiment_partition = UserPartition(
1,
'Content Expériment Configuration',
'Group Configuration for Content Expériments',
[experiment_group_a, experiment_group_b],
scheme_id='random'
)
course = CourseFactory.create(
cohort_config={'cohorted': True},
user_partitions=[cohort_scheme_partition, experiment_partition]
)
# Create user_a and user_b which are enrolled in the course
# and assigned to experiment_group_a and experiment_group_b,
# respectively.
user_a = UserFactory.create(username='user_a')
user_b = UserFactory.create(username='user_b')
CourseEnrollment.enroll(user_a, course.id)
CourseEnrollment.enroll(user_b, course.id)
course_tag_api.set_course_tag(
user_a,
course.id,
RandomUserPartitionScheme.key_for_partition(experiment_partition),
experiment_group_a.id
)
course_tag_api.set_course_tag(
user_b,
course.id,
RandomUserPartitionScheme.key_for_partition(experiment_partition),
experiment_group_b.id
)
# Assign user_a to a group in the 'cohort'-schemed user
# partition (by way of a cohort) to verify that the user
# partition group does not show up in the "Experiment Group"
# cell.
cohort_a = CohortFactory.create(course_id=course.id, name='Cohørt A', users=[user_a])
CourseUserGroupPartitionGroup(
course_user_group=cohort_a,
partition_id=cohort_scheme_partition.id,
group_id=cohort_scheme_partition.groups[0].id
).save()
# Verify that we see user_a and user_b in their respective
# content experiment groups, and that we do not see any
# content groups.
experiment_group_message = 'Experiment Group ({content_experiment})'
self._verify_cell_data_for_user(
user_a.username,
course.id,
experiment_group_message.format(
content_experiment=experiment_partition.name
),
experiment_group_a.name
)
self._verify_cell_data_for_user(
user_b.username,
course.id,
experiment_group_message.format(
content_experiment=experiment_partition.name
),
experiment_group_b.name
)
# Make sure cohort info is correct.
cohort_name_header = 'Cohort Name'
self._verify_cell_data_for_user(
user_a.username,
course.id,
cohort_name_header,
cohort_a.name
)
self._verify_cell_data_for_user(
user_b.username,
course.id,
cohort_name_header,
'',
)
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
@patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.iter')
def test_unicode_in_csv_header(self, mock_grades_iter, _mock_current_task):
"""
Tests that CSV grade report works if unicode in headers.
"""
mock_course_grade = MagicMock()
mock_course_grade.summary = {'section_breakdown': [{'label': '\u8282\u540e\u9898 01'}]}
mock_course_grade.letter_grade = None
mock_course_grade.percent = 0
mock_grades_iter.return_value = [
(
self.create_student('username', '[email protected]'),
mock_course_grade,
None,
)
]
result = CourseGradeReport.generate(None, None, self.course.id, {}, 'graded')
self.assertDictContainsSubset({'attempted': 1, 'succeeded': 1, 'failed': 0}, result)
def test_certificate_eligibility(self):
"""
Verifies that whether a learner has a failing grade in the database or the grade is
calculated on the fly, a failing grade will result in a Certificate Eligibility of
"N" in the report.
Also confirms that a persisted passing grade will result in a Certificate Eligibility
of "Y" for verified learners and "N" for audit learners.
"""
course = CourseFactory.create()
audit_user = CourseEnrollment.enroll(UserFactory.create(), course.id)
self._verify_cell_data_for_user(audit_user.username, course.id, 'Certificate Eligible', 'N', num_rows=1)
grading_policy_hash = GradesTransformer.grading_policy_hash(course)
PersistentCourseGrade.update_or_create(
user_id=audit_user.user_id,
course_id=course.id,
passed=False,
percent_grade=0.0,
grading_policy_hash=grading_policy_hash,
)
self._verify_cell_data_for_user(audit_user.username, course.id, 'Certificate Eligible', 'N', num_rows=1)
PersistentCourseGrade.update_or_create(
user_id=audit_user.user_id,
course_id=course.id,
passed=True,
percent_grade=0.8,
letter_grade="pass",
grading_policy_hash=grading_policy_hash,
)
# verifies that audit passing learner is not eligible for certificate
self._verify_cell_data_for_user(audit_user.username, course.id, 'Certificate Eligible', 'N', num_rows=1)
verified_user = CourseEnrollment.enroll(UserFactory.create(), course.id, 'verified')
PersistentCourseGrade.update_or_create(
user_id=verified_user.user_id,
course_id=course.id,
passed=True,
percent_grade=0.8,
letter_grade="pass",
grading_policy_hash=grading_policy_hash,
)
# verifies that verified passing learner is eligible for certificate
self._verify_cell_data_for_user(verified_user.username, course.id, 'Certificate Eligible', 'Y', num_rows=2)
def test_query_counts(self):
experiment_group_a = Group(2, 'Expériment Group A')
experiment_group_b = Group(3, 'Expériment Group B')
experiment_partition = UserPartition(
1,
'Content Expériment Configuration',
'Group Configuration for Content Expériments',
[experiment_group_a, experiment_group_b],
scheme_id='random'
)
course = CourseFactory.create(
cohort_config={'cohorted': True, 'auto_cohort': True, 'auto_cohort_groups': ['cohort 1', 'cohort 2']},
user_partitions=[experiment_partition],
teams_configuration=_TEAMS_CONFIG,
)
_ = CreditCourseFactory(course_key=course.id)
num_users = 5
for _ in range(num_users):
user = UserFactory.create()
CourseEnrollment.enroll(user, course.id, mode='verified')
SoftwareSecurePhotoVerificationFactory.create(user=user, status='approved')
RequestCache.clear_all_namespaces()
with patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task'):
with check_mongo_calls(2):
with self.assertNumQueries(58):
CourseGradeReport.generate(None, None, course.id, {}, 'graded')
def test_inactive_enrollments(self):
"""
Test that students with inactive enrollments are included in report.
"""
self.create_student('active-student', '[email protected]')
self.create_student('inactive-student', '[email protected]', enrollment_active=False)
self.current_task = Mock() # pylint: disable=attribute-defined-outside-init
self.current_task.update_state = Mock()
with patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task') as mock_current_task:
mock_current_task.return_value = self.current_task
result = CourseGradeReport.generate(None, None, self.course.id, {}, 'graded')
self._verify_cell_data_for_user('active-student', self.course.id, 'Enrollment Status', ENROLLED_IN_COURSE)
self._verify_cell_data_for_user('inactive-student', self.course.id, 'Enrollment Status', NOT_ENROLLED_IN_COURSE)
expected_students = 2
self.assertDictContainsSubset(
{'attempted': expected_students, 'succeeded': expected_students, 'failed': 0}, result
)
@ddt.ddt
class TestTeamGradeReport(InstructorGradeReportTestCase):
""" Test that teams appear correctly in the grade report when it is enabled for the course. """
def setUp(self):
super().setUp()
self.course = CourseFactory.create(teams_configuration=_TEAMS_CONFIG)
self.student1 = UserFactory.create()
CourseEnrollment.enroll(self.student1, self.course.id)
self.student2 = UserFactory.create()
CourseEnrollment.enroll(self.student2, self.course.id)
@ddt.data(True, False)
def test_team_in_grade_report(self, use_tempfile):
self._verify_cell_data_for_user(
self.student1.username, self.course.id, 'Team Name', '', use_tempfile=use_tempfile
)
def test_correct_team_name_in_grade_report(self):
team1 = CourseTeamFactory.create(course_id=self.course.id)
CourseTeamMembershipFactory.create(team=team1, user=self.student1)
team2 = CourseTeamFactory.create(course_id=self.course.id)
CourseTeamMembershipFactory.create(team=team2, user=self.student2)
self._verify_cell_data_for_user(self.student1.username, self.course.id, 'Team Name', team1.name)
self._verify_cell_data_for_user(self.student2.username, self.course.id, 'Team Name', team2.name)
def test_team_deleted(self):
team1 = CourseTeamFactory.create(course_id=self.course.id)
membership1 = CourseTeamMembershipFactory.create(team=team1, user=self.student1)
team2 = CourseTeamFactory.create(course_id=self.course.id)
CourseTeamMembershipFactory.create(team=team2, user=self.student2)
team1.delete()
membership1.delete()
self._verify_cell_data_for_user(self.student1.username, self.course.id, 'Team Name', '')
self._verify_cell_data_for_user(self.student2.username, self.course.id, 'Team Name', team2.name)
# pylint: disable=protected-access
@ddt.ddt
class TestProblemResponsesReport(TestReportMixin, InstructorTaskModuleTestCase):
"""
Tests that generation of CSV files listing student answers to a
given problem works.
"""
def setUp(self):
super().setUp()
self.initialize_course()
self.instructor = self.create_instructor('instructor')
self.student = self.create_student('student')
@contextmanager
def _remove_capa_report_generator(self):
"""
Temporarily removes the generate_report_data method so we can test
report generation when it's absent.
"""
from xmodule.capa_block import ProblemBlock
generate_report_data = ProblemBlock.generate_report_data
del ProblemBlock.generate_report_data
try:
yield
finally:
ProblemBlock.generate_report_data = generate_report_data
@patch.dict('django.conf.settings.FEATURES', {'MAX_PROBLEM_RESPONSES_COUNT': 4})
def test_build_student_data_limit(self):
"""
Ensure that the _build_student_data method respects the global setting for
maximum responses to return in a report.
"""
self.define_option_problem('Problem1')
for ctr in range(5):
student = self.create_student(f'student{ctr}')
self.submit_student_answer(student.username, 'Problem1', ['Option 1'])
student_data, _ = ProblemResponses._build_student_data(
user_id=self.instructor.id,
course_key=self.course.id,
usage_key_str_list=[str(self.course.location)],
)
assert len(student_data) == 4
@patch(
'lms.djangoapps.instructor_task.tasks_helper.grades.list_problem_responses',
wraps=list_problem_responses
)
def test_build_student_data_for_block_without_generate_report_data(self, mock_list_problem_responses):
"""
Ensure that building student data for a block the doesn't have the
``generate_report_data`` method works as expected.
"""
problem = self.define_option_problem('Problem1')
self.submit_student_answer(self.student.username, 'Problem1', ['Option 1'])
with self._remove_capa_report_generator():
student_data, student_data_keys_list = ProblemResponses._build_student_data(
user_id=self.instructor.id,
course_key=self.course.id,
usage_key_str_list=[str(problem.location)],
)
assert len(student_data) == 1
self.assertDictContainsSubset({
'username': 'student',
'location': 'test_course > Section > Subsection > Problem1',
'block_key': 'block-v1:edx+1.23x+test_course+type@problem+block@Problem1',
'title': 'Problem1',
}, student_data[0])
assert 'state' in student_data[0]
assert student_data_keys_list == ['username', 'title', 'location', 'block_key', 'state']
mock_list_problem_responses.assert_called_with(self.course.id, ANY, ANY)
@patch('xmodule.capa_block.ProblemBlock.generate_report_data', create=True)
def test_build_student_data_for_block_with_mock_generate_report_data(self, mock_generate_report_data):
"""
Ensure that building student data for a block that supports the
``generate_report_data`` method works as expected.
"""
self.define_option_problem('Problem1')
self.submit_student_answer(self.student.username, 'Problem1', ['Option 1'])
state1 = {'some': 'state1', 'more': 'state1!'}
state2 = {'some': 'state2', 'more': 'state2!'}
mock_generate_report_data.return_value = iter([
('student', state1),
('student', state2),
])
student_data, student_data_keys_list = ProblemResponses._build_student_data(
user_id=self.instructor.id,
course_key=self.course.id,
usage_key_str_list=[str(self.course.location)],
)
assert len(student_data) == 2
self.assertDictContainsSubset({
'username': 'student',
'location': 'test_course > Section > Subsection > Problem1',
'block_key': 'block-v1:edx+1.23x+test_course+type@problem+block@Problem1',
'title': 'Problem1',
'some': 'state1',
'more': 'state1!',
}, student_data[0])
self.assertDictContainsSubset({
'username': 'student',
'location': 'test_course > Section > Subsection > Problem1',
'block_key': 'block-v1:edx+1.23x+test_course+type@problem+block@Problem1',
'title': 'Problem1',
'some': 'state2',
'more': 'state2!',
}, student_data[1])
assert student_data[0]['state'] == student_data[1]['state']
assert student_data_keys_list == ['username', 'title', 'location', 'more', 'some', 'block_key', 'state']
@patch('xmodule.capa_block.ProblemBlock.generate_report_data', create=True)
def test_build_student_data_for_block_with_ordered_generate_report_data(self, mock_generate_report_data):
"""
Ensure that building student data for a block that returns OrderedDicts from the
``generate_report_data`` sorts the columns as expected.
"""
self.define_option_problem('Problem1')
self.submit_student_answer(self.student.username, 'Problem1', ['Option 1'])
state1 = OrderedDict()
state1['some'] = 'state1'
state1['more'] = 'state1!'
state2 = {'some': 'state2', 'more': 'state2!'}
mock_generate_report_data.return_value = iter([
('student', state1),
('student', state2),
])
student_data, student_data_keys_list = ProblemResponses._build_student_data(
user_id=self.instructor.id,
course_key=self.course.id,
usage_key_str_list=[str(self.course.location)],
)
assert len(student_data) == 2
self.assertDictContainsSubset({
'username': 'student',
'location': 'test_course > Section > Subsection > Problem1',
'block_key': 'block-v1:edx+1.23x+test_course+type@problem+block@Problem1',
'title': 'Problem1',
'some': 'state1',
'more': 'state1!',
}, student_data[0])
self.assertDictContainsSubset({
'username': 'student',
'location': 'test_course > Section > Subsection > Problem1',
'block_key': 'block-v1:edx+1.23x+test_course+type@problem+block@Problem1',
'title': 'Problem1',
'some': 'state2',
'more': 'state2!',
}, student_data[1])
assert student_data[0]['state'] == student_data[1]['state']
assert student_data_keys_list == ['username', 'title', 'location', 'some', 'more', 'block_key', 'state']
def test_build_student_data_for_block_with_real_generate_report_data(self):
"""
Ensure that building student data for a block that supports the
``generate_report_data`` method works as expected.
"""
self.define_option_problem('Problem1')
self.submit_student_answer(self.student.username, 'Problem1', ['Option 1'])
student_data, student_data_keys_list = ProblemResponses._build_student_data(
user_id=self.instructor.id,
course_key=self.course.id,
usage_key_str_list=[str(self.course.location)],
)
assert len(student_data) == 1
self.assertDictContainsSubset({
'username': 'student',
'location': 'test_course > Section > Subsection > Problem1',
'block_key': 'block-v1:edx+1.23x+test_course+type@problem+block@Problem1',
'title': 'Problem1',
'Answer ID': 'Problem1_2_1',
'Answer': 'Option 1',
'Correct Answer': 'Option 1',
'Question': 'The correct answer is Option 1',
}, student_data[0])
assert 'state' in student_data[0]
assert student_data_keys_list == ['username', 'title', 'location', 'Answer', 'Answer ID', 'Correct Answer',
'Question', 'block_key', 'state']
def test_build_student_data_for_multiple_problems(self):
"""
Ensure that building student data works when supplied multiple usage keys.
"""
problem1 = self.define_option_problem('Problem1')
problem2 = self.define_option_problem('Problem2')
self.submit_student_answer(self.student.username, 'Problem1', ['Option 1'])
self.submit_student_answer(self.student.username, 'Problem2', ['Option 1'])
student_data, _ = ProblemResponses._build_student_data(
user_id=self.instructor.id,
course_key=self.course.id,
usage_key_str_list=[str(problem1.location), str(problem2.location)],
)
assert len(student_data) == 2
for idx in range(1, 3):
self.assertDictContainsSubset({
'username': 'student',
'location': f'test_course > Section > Subsection > Problem{idx}',
'block_key': f'block-v1:edx+1.23x+test_course+type@problem+block@Problem{idx}',
'title': f'Problem{idx}',
'Answer ID': f'Problem{idx}_2_1',
'Answer': 'Option 1',
'Correct Answer': 'Option 1',
'Question': 'The correct answer is Option 1',
}, student_data[idx - 1])
assert 'state' in student_data[(idx - 1)]
@ddt.data(
(['problem'], 5),
(['other'], 0),
(None, 5),
)
@ddt.unpack
def test_build_student_data_with_filter(self, filters, filtered_count):
"""
Ensure that building student data works when supplied multiple usage keys.
"""
for idx in range(1, 6):
self.define_option_problem(f'Problem{idx}')
item = BlockFactory.create(
parent_location=self.problem_section.location,
parent=self.problem_section,
display_name=f"Item{idx}",
data=''
)
StudentModule.save_state(self.student, self.course.id, item.location, {})
for idx in range(1, 6):
self.submit_student_answer(self.student.username, f'Problem{idx}', ['Option 1'])
student_data, _ = ProblemResponses._build_student_data(
user_id=self.instructor.id,
course_key=self.course.id,
usage_key_str_list=[str(self.course.location)],
filter_types=filters,
)
assert len(student_data) == filtered_count
@patch('lms.djangoapps.instructor_task.tasks_helper.grades.list_problem_responses')
@patch('xmodule.capa_block.ProblemBlock.generate_report_data', create=True)
def test_build_student_data_for_block_with_generate_report_data_not_implemented(
self,
mock_generate_report_data,
mock_list_problem_responses,
):
"""
Ensure that if ``generate_report_data`` raises a NotImplementedError,
the report falls back to the alternative method.
"""
problem = self.define_option_problem('Problem1')
mock_generate_report_data.side_effect = NotImplementedError
ProblemResponses._build_student_data(
user_id=self.instructor.id,
course_key=self.course.id,
usage_key_str_list=[str(problem.location)],
)
mock_generate_report_data.assert_called_with(ANY, ANY)
mock_list_problem_responses.assert_called_with(self.course.id, ANY, ANY)
def test_success(self):
task_input = {
'problem_locations': str(self.course.location),
'user_id': self.instructor.id
}
with patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task'):
with patch('lms.djangoapps.instructor_task.tasks_helper.grades'
'.ProblemResponses._build_student_data') as mock_build_student_data:
mock_build_student_data.return_value = (
[
{'username': 'user0', 'state': 'state0'},
{'username': 'user1', 'state': 'state1'},
{'username': 'user2', 'state': 'state2'},
],
['username', 'state']
)
result = ProblemResponses.generate(
None, None, self.course.id, task_input, 'calculated'
)
report_store = ReportStore.from_config(config_name='GRADES_DOWNLOAD')
links = report_store.links_for(self.course.id)
assert len(links) == 1
assert set(({'attempted': 3, 'succeeded': 3, 'failed': 0}).items()).issubset(set(result.items()))
assert "report_name" in result
@ddt.data(
('blkid', None, 'edx_1.23x_test_course_student_state_from_blkid_2020-01-01-0000.csv'),
('blkid', 'poll,survey', 'edx_1.23x_test_course_student_state_from_blkid_for_poll,survey_2020-01-01-0000.csv'),
('blkid1,blkid2', None, 'edx_1.23x_test_course_student_state_from_multiple_blocks_2020-01-01-0000.csv'),
(
'blkid1,blkid2',
'poll,survey',
'edx_1.23x_test_course_student_state_from_multiple_blocks_for_poll,survey_2020-01-01-0000.csv',
),
)
@ddt.unpack
def test_file_names(self, problem_locations, problem_types_filter, file_name):
task_input = {
'problem_locations': problem_locations,
'problem_types_filter': problem_types_filter,
'user_id': self.instructor.id
}
with patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task'), \
freeze_time('2020-01-01'):
with patch('lms.djangoapps.instructor_task.tasks_helper.grades'
'.ProblemResponses._build_student_data') as mock_build_student_data:
mock_build_student_data.return_value = (
[
{'username': 'user0', 'state': 'state0'},
{'username': 'user1', 'state': 'state1'},
{'username': 'user2', 'state': 'state2'},
],
['username', 'state']
)
result = ProblemResponses.generate(
None, None, self.course.id, task_input, 'calculated'
)
assert result.get('report_name') == file_name
@ddt.ddt
class TestProblemGradeReport(TestReportMixin, InstructorTaskModuleTestCase):
"""
Test that the problem CSV generation works.
"""
def setUp(self):
super().setUp()
self.initialize_course()
# Add unicode data to CSV even though unicode usernames aren't
# technically possible in openedx.
self.student_1 = self.create_student('üser_1')
self.student_2 = self.create_student('üser_2')
self.csv_header_row = ['Student ID', 'Email', 'Username', 'Enrollment Status', 'Grade']
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
@ddt.data(True, False)
def test_no_problems(self, use_tempfile, _):
"""
Verify that we see no grade information for a course with no graded
problems.
"""
with patch(USE_ON_DISK_GRADE_REPORT, return_value=use_tempfile):
result = ProblemGradeReport.generate(None, None, self.course.id, {}, 'graded')
self.assertDictContainsSubset({'action_name': 'graded', 'attempted': 2, 'succeeded': 2, 'failed': 0}, result)
self.verify_rows_in_csv([
dict(list(zip(
self.csv_header_row,
[str(self.student_1.id), self.student_1.email, self.student_1.username, ENROLLED_IN_COURSE, '0.0']
))),
dict(list(zip(
self.csv_header_row,
[str(self.student_2.id), self.student_2.email, self.student_2.username, ENROLLED_IN_COURSE, '0.0']
)))
])
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
@ddt.data(True, False)
def test_single_problem(self, use_tempfile, _):
vertical = BlockFactory.create(
parent_location=self.problem_section.location,
category='vertical',
metadata={'graded': True},
display_name='Problem Vertical'
)
self.define_option_problem('Problem1', parent=vertical)
self.submit_student_answer(self.student_1.username, 'Problem1', ['Option 1'])
with patch(USE_ON_DISK_GRADE_REPORT, return_value=use_tempfile):
result = ProblemGradeReport.generate(None, None, self.course.id, {}, 'graded')
self.assertDictContainsSubset({'action_name': 'graded', 'attempted': 2, 'succeeded': 2, 'failed': 0}, result)
problem_name = 'Homework 1: Subsection - Problem1'
header_row = self.csv_header_row + [problem_name + ' (Earned)', problem_name + ' (Possible)']
self.verify_rows_in_csv([
dict(list(zip(
header_row,
[
str(self.student_1.id),
self.student_1.email,
self.student_1.username,
ENROLLED_IN_COURSE,
'0.01', '1.0', '2.0',
]
))),
dict(list(zip(
header_row,
[
str(self.student_2.id),
self.student_2.email,
self.student_2.username,
ENROLLED_IN_COURSE,
'0.0', 'Not Attempted', '2.0',
]
)))
])
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
@ddt.data(True, False)
def test_single_problem_verified_student_only(self, use_tempfile, _):
with patch(
'lms.djangoapps.instructor_task.tasks_helper.grades.problem_grade_report_verified_only',
return_value=True,
):
student_verified = self.create_student('user_verified', mode='verified')
vertical = BlockFactory.create(
parent_location=self.problem_section.location,
category='vertical',
metadata={'graded': True},
display_name='Problem Vertical'
)
self.define_option_problem('Problem1', parent=vertical)
self.submit_student_answer(self.student_1.username, 'Problem1', ['Option 1'])
self.submit_student_answer(student_verified.username, 'Problem1', ['Option 1'])
with patch(USE_ON_DISK_GRADE_REPORT, return_value=use_tempfile):
result = ProblemGradeReport.generate(None, None, self.course.id, {}, 'graded')
self.assertDictContainsSubset(
{'action_name': 'graded', 'attempted': 1, 'succeeded': 1, 'failed': 0}, result
)
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
@ddt.data(True, False)
def test_inactive_enrollment_included(self, use_tempfile, _):
"""
Students with inactive enrollments in a course should be included in Problem Grade Report.
"""
inactive_student = self.create_student('inactive-student', '[email protected]', enrollment_active=False)
vertical = BlockFactory.create(
parent_location=self.problem_section.location,
category='vertical',
metadata={'graded': True},
display_name='Problem Vertical'
)
self.define_option_problem('Problem1', parent=vertical)
self.submit_student_answer(self.student_1.username, 'Problem1', ['Option 1'])
with patch(USE_ON_DISK_GRADE_REPORT, return_value=use_tempfile):
result = ProblemGradeReport.generate(None, None, self.course.id, {}, 'graded')
self.assertDictContainsSubset({'action_name': 'graded', 'attempted': 3, 'succeeded': 3, 'failed': 0}, result)
problem_name = 'Homework 1: Subsection - Problem1'
header_row = self.csv_header_row + [problem_name + ' (Earned)', problem_name + ' (Possible)']
self.verify_rows_in_csv([
dict(list(zip(
header_row,
[
str(self.student_1.id),
self.student_1.email,
self.student_1.username,
ENROLLED_IN_COURSE,
'0.01', '1.0', '2.0',
]
))),
dict(list(zip(
header_row,
[
str(self.student_2.id),
self.student_2.email,
self.student_2.username,
ENROLLED_IN_COURSE,
'0.0', 'Not Attempted', '2.0',
]
))),
dict(list(zip(
header_row,
[
str(inactive_student.id),
inactive_student.email,
inactive_student.username,
NOT_ENROLLED_IN_COURSE,
'0.0', 'Not Attempted', '2.0',
]
)))
])
@ddt.ddt
class TestProblemReportSplitTestContent(TestReportMixin, TestConditionalContent, InstructorTaskModuleTestCase):
"""
Test the problem report on a course that has split tests.
"""
OPTION_1 = 'Option 1'
OPTION_2 = 'Option 2'
def setUp(self):
super().setUp()
self.problem_a_url = 'problem_a_url'
self.problem_b_url = 'problem_b_url'
self.define_option_problem(self.problem_a_url, parent=self.vertical_a)
self.define_option_problem(self.problem_b_url, parent=self.vertical_b)
@ddt.data(True, False)
def test_problem_grade_report(self, use_tempfile):
"""
Test that we generate the correct grade report when dealing with A/B tests.
In order to verify that the behavior of the grade report is correct, we submit answers for problems
that the student won't have access to. A/B tests won't restrict access to the problems, but it should
not show up in that student's course tree when generating the grade report, hence the Not Available's
in the grade report.
"""
# student A will get 100%, student B will get 50% because
# OPTION_1 is the correct option, and OPTION_2 is the
# incorrect option
self.submit_student_answer(self.student_a.username, self.problem_a_url, [self.OPTION_1, self.OPTION_1])
self.submit_student_answer(self.student_a.username, self.problem_b_url, [self.OPTION_1, self.OPTION_1])
self.submit_student_answer(self.student_b.username, self.problem_a_url, [self.OPTION_1, self.OPTION_2])
self.submit_student_answer(self.student_b.username, self.problem_b_url, [self.OPTION_1, self.OPTION_2])
with patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task'):
with patch(USE_ON_DISK_GRADE_REPORT, return_value=use_tempfile):
result = ProblemGradeReport.generate(None, None, self.course.id, {}, 'graded')
self.assertDictContainsSubset(
{'action_name': 'graded', 'attempted': 2, 'succeeded': 2, 'failed': 0}, result
)
problem_names = ['Homework 1: Subsection - problem_a_url', 'Homework 1: Subsection - problem_b_url']
header_row = ['Student ID', 'Email', 'Username', 'Enrollment Status', 'Grade']
for problem in problem_names:
header_row += [problem + ' (Earned)', problem + ' (Possible)']
self.verify_rows_in_csv([
dict(list(zip(
header_row,
[
str(self.student_a.id),