|
10 | 10 | from django.core.management import call_command |
11 | 11 | from django.urls import reverse |
12 | 12 |
|
| 13 | +from common.djangoapps.student.models import CourseEnrollment |
13 | 14 | from common.djangoapps.student.tests.factories import AdminFactory, CourseEnrollmentFactory, UserFactory |
14 | 15 | from lms.djangoapps.bulk_email.models import BulkEmailFlag, Optout |
15 | 16 | from lms.djangoapps.bulk_email.signals import force_optout_all |
| 17 | +from opaque_keys.edx.keys import CourseKey |
16 | 18 | from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase # lint-amnesty, pylint: disable=wrong-import-order |
17 | 19 | from xmodule.modulestore.tests.factories import CourseFactory # lint-amnesty, pylint: disable=wrong-import-order |
18 | 20 |
|
@@ -85,3 +87,41 @@ def test_optout_course(self): |
85 | 87 | assert len(mail.outbox) == 1 |
86 | 88 | assert len(mail.outbox[0].to) == 1 |
87 | 89 | assert mail.outbox[0].to[0] == self.instructor.email |
| 90 | + |
| 91 | + @patch('lms.djangoapps.bulk_email.signals.log.warning') |
| 92 | + def test_optout_handles_missing_course_overview(self, mock_log_warning): |
| 93 | + """ |
| 94 | + Test that force_optout_all gracefully handles CourseEnrollments |
| 95 | + with missing CourseOverview records |
| 96 | + """ |
| 97 | + # Create a course key for a course that doesn't exist in CourseOverview |
| 98 | + nonexistent_course_key = CourseKey.from_string('course-v1:TestX+Missing+2023') |
| 99 | + |
| 100 | + # Create an enrollment with a course_id that doesn't have a CourseOverview |
| 101 | + CourseEnrollment.objects.create( |
| 102 | + user=self.student, |
| 103 | + course_id=nonexistent_course_key, |
| 104 | + mode='honor' |
| 105 | + ) |
| 106 | + |
| 107 | + # Verify the orphaned enrollment exists |
| 108 | + assert CourseEnrollment.objects.filter( |
| 109 | + user=self.student, |
| 110 | + course_id=nonexistent_course_key |
| 111 | + ).exists() |
| 112 | + |
| 113 | + force_optout_all(sender=self.__class__, user=self.student) |
| 114 | + |
| 115 | + # Verify that a warning was logged for the missing CourseOverview |
| 116 | + mock_log_warning.assert_called() |
| 117 | + call_args = mock_log_warning.call_args[0][0] |
| 118 | + assert "CourseOverview not found for enrollment" in call_args |
| 119 | + assert f"user: {self.student.id}" in call_args |
| 120 | + assert "skipping optout creation" in call_args |
| 121 | + |
| 122 | + # Verify that optouts were created for valid courses only |
| 123 | + valid_course_optouts = Optout.objects.filter(user=self.student, course_id=self.course.id) |
| 124 | + missing_course_optouts = Optout.objects.filter(user=self.student, course_id=nonexistent_course_key) |
| 125 | + |
| 126 | + assert valid_course_optouts.count() == 1 |
| 127 | + assert missing_course_optouts.count() == 0 |
0 commit comments