test_email.py 28.1 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4
"""
Unit tests for sending course email
"""
5
import json
6
import os
7
from unittest import skip, skipIf
8

9
import ddt
10
from django.conf import settings
11
from django.core import mail
12
from django.core.mail.message import forbid_multi_line_headers
13
from django.core.management import call_command
14
from django.core.urlresolvers import reverse
15
from django.test.utils import override_settings
Omar Al-Ithawi committed
16
from django.utils.translation import get_language
17 18 19
from markupsafe import escape
from mock import Mock, patch
from nose.plugins.attrib import attr
20

21 22
from bulk_email.models import BulkEmailFlag, Optout
from bulk_email.tasks import _get_course_email_context, _get_source_address
23
from course_modes.models import CourseMode
24
from courseware.tests.factories import InstructorFactory, StaffFactory
25
from enrollment.api import update_enrollment
26
from lms.djangoapps.instructor_task.subtasks import update_subtask_status
27 28
from openedx.core.djangoapps.course_groups.cohorts import add_user_to_cohort
from openedx.core.djangoapps.course_groups.models import CourseCohort
29
from student.models import CourseEnrollment
30
from student.roles import CourseStaffRole
31
from student.tests.factories import CourseEnrollmentFactory, UserFactory
32 33
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
34
from xmodule.modulestore.tests.factories import CourseFactory
35

36 37
STAFF_COUNT = 3
STUDENT_COUNT = 10
38 39 40 41 42 43 44 45 46 47
LARGE_NUM_EMAILS = 137


class MockCourseEmailResult(object):
    """
    A small closure-like class to keep count of emails sent over all tasks, recorded
    by mock object side effects
    """
    emails_sent = 0

48
    def get_mock_update_subtask_status(self):
49
        """Wrapper for mock email function."""
50
        def mock_update_subtask_status(entry_id, current_task_id, new_subtask_status):
51
            """Increments count of number of emails sent."""
52 53 54
            self.emails_sent += new_subtask_status.succeeded
            return update_subtask_status(entry_id, current_task_id, new_subtask_status)
        return mock_update_subtask_status
55 56


57
class EmailSendFromDashboardTestCase(SharedModuleStoreTestCase):
58 59 60 61
    """
    Test that emails send correctly.
    """

62 63 64 65 66 67
    def create_staff_and_instructor(self):
        """
        Creates one instructor and several course staff for self.course. Assigns
        them to self.instructor (single user) and self.staff (list of users),
        respectively.
        """
68
        self.instructor = InstructorFactory(course_key=self.course.id)
69

70 71 72
        self.staff = [
            StaffFactory(course_key=self.course.id) for __ in xrange(STAFF_COUNT)
        ]
73

74 75 76 77 78
    def create_students(self):
        """
        Creates users and enrolls them in self.course. Assigns these users to
        self.students.
        """
79 80 81 82
        self.students = [UserFactory() for _ in xrange(STUDENT_COUNT)]
        for student in self.students:
            CourseEnrollmentFactory.create(user=student, course_id=self.course.id)

83 84 85 86 87
    def login_as_user(self, user):
        """
        Log in self.client as user.
        """
        self.client.login(username=user.username, password="test")
88

89 90 91 92 93 94
    def goto_instructor_dash_email_view(self):
        """
        Goes to the instructor dashboard to verify that the email section is
        there.
        """
        url = reverse('instructor_dashboard', kwargs={'course_id': unicode(self.course.id)})
95 96
        # Response loads the whole instructor dashboard, so no need to explicitly
        # navigate to a particular email section
97
        response = self.client.get(url)
98
        email_section = '<div class="vert-left send-email" id="section-send-email">'
99
        # If this fails, it is likely because BulkEmailFlag.is_enabled() is set to False
100 101 102 103 104 105 106 107 108 109 110 111 112
        self.assertIn(email_section, response.content)

    @classmethod
    def setUpClass(cls):
        super(EmailSendFromDashboardTestCase, cls).setUpClass()
        course_title = u"ẗëṡẗ title イ乇丂イ ᄊ乇丂丂ムg乇 キo尺 ムレレ тэѕт мэѕѕаБэ"
        cls.course = CourseFactory.create(
            display_name=course_title,
            default_store=ModuleStoreEnum.Type.split
        )

    def setUp(self):
        super(EmailSendFromDashboardTestCase, self).setUp()
113
        BulkEmailFlag.objects.create(enabled=True, require_course_email_auth=False)
114 115 116 117 118 119 120 121
        self.create_staff_and_instructor()
        self.create_students()

        # load initial content (since we don't run migrations as part of tests):
        call_command("loaddata", "course_email_template.json")

        self.login_as_user(self.instructor)

122
        # Pulling up the instructor dash email view here allows us to test sending emails in tests
123 124 125 126
        self.goto_instructor_dash_email_view()
        self.send_mail_url = reverse(
            'send_email', kwargs={'course_id': unicode(self.course.id)}
        )
127
        self.success_content = {
128
            'course_id': unicode(self.course.id),
129 130
            'success': True,
        }
131

132 133 134 135
    def tearDown(self):
        super(EmailSendFromDashboardTestCase, self).tearDown()
        BulkEmailFlag.objects.all().delete()

Christine Lytwynec committed
136

137 138 139 140
class SendEmailWithMockedUgettextMixin(object):
    """
    Mock uggetext for EmailSendFromDashboardTestCase.
    """
141 142 143 144 145 146 147 148 149 150 151
    def send_email(self):
        """
        Sends a dummy email to check the `from_addr` translation.
        """
        test_email = {
            'action': 'send',
            'send_to': '["myself"]',
            'subject': 'test subject for myself',
            'message': 'test message for myself'
        }

Omar Al-Ithawi committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
        def mock_ugettext(text):
            """
            Mocks ugettext to return the lang code with the original string.

            e.g.

            >>> mock_ugettext('Hello') == '@AR Hello@'
            """
            return u'@{lang} {text}@'.format(
                lang=get_language().upper(),
                text=text,
            )

        with patch('bulk_email.tasks._', side_effect=mock_ugettext):
            self.client.post(self.send_mail_url, test_email)
167 168 169

        return mail.outbox[0]

170 171 172 173 174 175 176 177

@attr(shard=1)
@patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': False})
@ddt.ddt
class LocalizedFromAddressPlatformLangTestCase(SendEmailWithMockedUgettextMixin, EmailSendFromDashboardTestCase):
    """
    Tests to ensure that the bulk email has the "From" address localized according to LANGUAGE_CODE.
    """
178 179 180
    @override_settings(LANGUAGE_CODE='en')
    def test_english_platform(self):
        """
Omar Al-Ithawi committed
181
        Ensures that the source-code language (English) works well.
182
        """
183
        self.assertIsNone(self.course.language)  # Sanity check
184
        message = self.send_email()
Omar Al-Ithawi committed
185
        self.assertRegexpMatches(message.from_email, '.*Course Staff.*')
186

Omar Al-Ithawi committed
187 188
    @override_settings(LANGUAGE_CODE='eo')
    def test_esperanto_platform(self):
189
        """
Omar Al-Ithawi committed
190
        Tests the fake Esperanto language to ensure proper gettext calls.
191
        """
192
        self.assertIsNone(self.course.language)  # Sanity check
193
        message = self.send_email()
Omar Al-Ithawi committed
194
        self.assertRegexpMatches(message.from_email, '@EO .* Course Staff@')
195 196 197


@attr(shard=1)
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
@patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': False})
@ddt.ddt
class LocalizedFromAddressCourseLangTestCase(SendEmailWithMockedUgettextMixin, EmailSendFromDashboardTestCase):
    """
    Test if the bulk email "From" address uses the course.language if present instead of LANGUAGE_CODE.

    This is similiar to LocalizedFromAddressTestCase but creating a different test case to allow
    changing the class-wide course object.
    """

    @classmethod
    def setUpClass(cls):
        """
        Creates a different course.
        """
        super(LocalizedFromAddressCourseLangTestCase, cls).setUpClass()
        course_title = u"ẗëṡẗ イэ"
        cls.course = CourseFactory.create(
            display_name=course_title,
            language='ar',
            default_store=ModuleStoreEnum.Type.split
        )

    @override_settings(LANGUAGE_CODE='eo')
    def test_esperanto_platform_arabic_course(self):
        """
        The course language should override the platform's.
        """
        message = self.send_email()
        self.assertRegexpMatches(message.from_email, '@AR .* Course Staff@')


@attr(shard=1)
231
@patch('bulk_email.models.html_to_text', Mock(return_value='Mocking CourseEmail.text_message', autospec=True))
Christine Lytwynec committed
232 233 234 235
class TestEmailSendFromDashboardMockedHtmlToText(EmailSendFromDashboardTestCase):
    """
    Tests email sending with mocked html_to_text.
    """
236 237 238 239
    def test_email_disabled(self):
        """
        Test response when email is disabled for course.
        """
240
        BulkEmailFlag.objects.create(enabled=True, require_course_email_auth=True)
241 242
        test_email = {
            'action': 'Send email',
243
            'send_to': '["myself"]',
244 245 246
            'subject': 'test subject for myself',
            'message': 'test message for myself'
        }
247 248 249
        response = self.client.post(self.send_mail_url, test_email)
        # We should get back a HttpResponseForbidden (status code 403)
        self.assertContains(response, "Email is not enabled for this course.", status_code=403)
250

251
    @patch('bulk_email.models.html_to_text', Mock(return_value='Mocking CourseEmail.text_message', autospec=True))
252 253 254 255
    def test_send_to_self(self):
        """
        Make sure email send to myself goes to myself.
        """
256
        test_email = {
257
            'action': 'send',
258
            'send_to': '["myself"]',
259 260 261
            'subject': 'test subject for myself',
            'message': 'test message for myself'
        }
262 263
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)
264

265
        # Check that outbox is as expected
266 267 268
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(len(mail.outbox[0].to), 1)
        self.assertEquals(mail.outbox[0].to[0], self.instructor.email)
269
        self.assertEquals(mail.outbox[0].subject, 'test subject for myself')
270 271
        """
        TODO - uncomment this assertion and delete the following alternate once django-ses is fixed. EDUCATOR-1773
272 273 274 275 276 277 278
        self.assertEquals(
            mail.outbox[0].from_email,
            u'"{course_display_name}" Course Staff <{course_name}-no-reply@example.com>'.format(
                course_display_name=self.course.display_name,
                course_name=self.course.id.course
            )
        )
279 280 281 282 283 284 285 286
        """  # pylint: disable=pointless-string-statement
        self.assertEquals(
            mail.outbox[0].from_email,
            u'"{course_display_name}" Course Staff <{course_name}-no-reply@example.com>'.format(
                course_display_name=self.course.number,
                course_name=self.course.id.course
            )
        )
287 288 289 290 291

    def test_send_to_staff(self):
        """
        Make sure email send to staff and instructors goes there.
        """
292 293
        test_email = {
            'action': 'Send email',
294
            'send_to': '["staff"]',
295 296 297
            'subject': 'test subject for staff',
            'message': 'test message for subject'
        }
298 299
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)
300

301
        # the 1 is for the instructor in this test and others
302
        self.assertEquals(len(mail.outbox), 1 + len(self.staff))
303 304 305 306
        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [self.instructor.email] + [s.email for s in self.staff]
        )
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
    def test_send_to_cohort(self):
        """
        Make sure email sent to a cohort goes there.
        """
        cohort = CourseCohort.create(cohort_name='test cohort', course_id=self.course.id)
        for student in self.students:
            add_user_to_cohort(cohort.course_user_group, student.username)
        test_email = {
            'action': 'Send email',
            'send_to': '["cohort:{}"]'.format(cohort.course_user_group.name),
            'subject': 'test subject for cohort',
            'message': 'test message for cohort'
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [s.email for s in self.students]
        )

    def test_send_to_cohort_unenrolled(self):
        """
        Make sure email sent to a cohort does not go to unenrolled members of the cohort.
        """
        self.students.append(UserFactory())  # user will be added to cohort, but not enrolled in course
        cohort = CourseCohort.create(cohort_name='test cohort', course_id=self.course.id)
        for student in self.students:
            add_user_to_cohort(cohort.course_user_group, student.username)
        test_email = {
            'action': 'Send email',
            'send_to': '["cohort:{}"]'.format(cohort.course_user_group.name),
            'subject': 'test subject for cohort',
            'message': 'test message for cohort'
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        self.assertEquals(len(mail.outbox), len(self.students) - 1)
        self.assertNotIn(self.students[-1].email, [e.to[0] for e in mail.outbox])

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
    def test_send_to_track(self):
        """
        Make sure email sent to a registration track goes there.
        """
        CourseMode.objects.create(mode_slug='test', course_id=self.course.id)
        for student in self.students:
            update_enrollment(student, unicode(self.course.id), 'test')
        test_email = {
            'action': 'Send email',
            'send_to': '["track:test"]',
            'subject': 'test subject for test track',
            'message': 'test message for test track',
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [s.email for s in self.students]
        )

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
    def test_send_to_track_other_enrollments(self):
        """
        Failing test for EDUCATOR-217: verifies that emails are only sent to
        users in a specific track if they're in that track in the course the
        email is being sent from.
        """
        # Create a mode and designate an enrolled user to be placed in that mode
        CourseMode.objects.create(mode_slug='test_mode', course_id=self.course.id)
        test_mode_student = self.students[0]
        update_enrollment(test_mode_student, unicode(self.course.id), 'test_mode')

        # Take another user already enrolled in the course, then enroll them in
        # another course but in that same test mode
        test_mode_student_other_course = self.students[1]
        other_course = CourseFactory.create()
        CourseMode.objects.create(mode_slug='test_mode', course_id=other_course.id)
        CourseEnrollmentFactory.create(
            user=test_mode_student_other_course,
            course_id=other_course.id
        )
        update_enrollment(test_mode_student_other_course, unicode(other_course.id), 'test_mode')

        # Send the emails...
        test_email = {
            'action': 'Send email',
            'send_to': '["track:test_mode"]',
            'subject': 'test subject for test_mode track',
            'message': 'test message for test_mode track',
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        # Only the the student in the test mode in the course the email was
        # sent from should receive an email
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].to[0], test_mode_student.email)

407 408 409 410
    def test_send_to_all(self):
        """
        Make sure email send to all goes there.
        """
411 412 413

        test_email = {
            'action': 'Send email',
414
            'send_to': '["myself", "staff", "learners"]',
415 416 417
            'subject': 'test subject for all',
            'message': 'test message for all'
        }
418 419
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)
420

421
        # the 1 is for the instructor
422
        self.assertEquals(len(mail.outbox), 1 + len(self.staff) + len(self.students))
423 424 425 426 427
        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [self.instructor.email] + [s.email for s in self.staff] + [s.email for s in self.students]
        )

428 429 430 431 432 433 434
    @override_settings(BULK_EMAIL_JOB_SIZE_THRESHOLD=1)
    def test_send_to_all_high_queue(self):
        """
        Test that email is still sent when the high priority queue is used
        """
        self.test_send_to_all()

435 436 437 438 439 440 441 442 443 444
    def test_no_duplicate_emails_staff_instructor(self):
        """
        Test that no duplicate emails are sent to a course instructor that is
        also course staff
        """
        CourseStaffRole(self.course.id).add_users(self.instructor)
        self.test_send_to_all()

    def test_no_duplicate_emails_enrolled_staff(self):
        """
445
        Test that no duplicate emails are sent to a course instructor that is
446 447 448 449 450
        also enrolled in the course
        """
        CourseEnrollment.enroll(self.instructor, self.course.id)
        self.test_send_to_all()

451 452 453 454 455 456 457 458 459 460 461 462 463
    def test_no_duplicate_emails_unenrolled_staff(self):
        """
        Test that no duplicate emails are sent to a course staff that is
        not enrolled in the course, but is enrolled in other courses
        """
        course_1 = CourseFactory.create()
        course_2 = CourseFactory.create()
        # make sure self.instructor isn't enrolled in the course
        self.assertFalse(CourseEnrollment.is_enrolled(self.instructor, self.course.id))
        CourseEnrollment.enroll(self.instructor, course_1.id)
        CourseEnrollment.enroll(self.instructor, course_2.id)
        self.test_send_to_all()

464 465 466 467 468
    def test_unicode_subject_send_to_all(self):
        """
        Make sure email (with Unicode characters) send to all goes there.
        """

469
        uni_subject = u'téśt śúbjéćt főŕ áĺĺ'
470 471
        test_email = {
            'action': 'Send email',
472
            'send_to': '["myself", "staff", "learners"]',
473
            'subject': uni_subject,
474 475
            'message': 'test message for all'
        }
476 477
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)
478 479 480 481 482 483

        self.assertEquals(len(mail.outbox), 1 + len(self.staff) + len(self.students))
        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [self.instructor.email] + [s.email for s in self.staff] + [s.email for s in self.students]
        )
484
        self.assertEquals(mail.outbox[0].subject, uni_subject)
485 486 487 488 489 490 491 492 493 494 495 496 497

    def test_unicode_students_send_to_all(self):
        """
        Make sure email (with Unicode characters) send to all goes there.
        """

        # Create a student with Unicode in their first & last names
        unicode_user = UserFactory(first_name=u'Ⓡⓞⓑⓞⓣ', last_name=u'ՇﻉรՇ')
        CourseEnrollmentFactory.create(user=unicode_user, course_id=self.course.id)
        self.students.append(unicode_user)

        test_email = {
            'action': 'Send email',
498
            'send_to': '["myself", "staff", "learners"]',
499 500 501
            'subject': 'test subject for all',
            'message': 'test message for all'
        }
502 503
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)
504 505 506 507 508 509 510

        self.assertEquals(len(mail.outbox), 1 + len(self.staff) + len(self.students))

        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [self.instructor.email] + [s.email for s in self.staff] + [s.email for s in self.students]
        )
511

512
    @skip("Unicode course names are broken, see EDUCATOR-1773 for details. Un-skip after django-ses is fixed.")
513
    @override_settings(BULK_EMAIL_DEFAULT_FROM_EMAIL="no-reply@courseupdates.edx.org")
514 515 516 517 518 519 520 521
    def test_long_course_display_name(self):
        """
        This test tests that courses with exorbitantly large display names
        can still send emails, since it appears that 320 appears to be the
        character length limit of from emails for Amazon SES.
        """
        test_email = {
            'action': 'Send email',
522
            'send_to': '["myself", "staff", "learners"]',
523 524 525 526
            'subject': 'test subject for self',
            'message': 'test message for self'
        }

527
        # make display_name that's longer than 320 characters when encoded
528 529
        # to ascii and escaped, but shorter than 320 unicode characters
        long_name = u"Финансовое программирование и политика, часть 1: макроэкономические счета и анализ"
530

531
        course = CourseFactory.create(
532 533 534 535
            display_name=long_name,
            org="IMF",
            number="FPP.1x",
            run="2016",
536 537 538
        )
        instructor = InstructorFactory(course_key=course.id)

539
        unexpected_from_addr = _get_source_address(
540
            course.id, course.display_name, course_language=None, truncate=False
541 542 543 544
        )
        __, encoded_unexpected_from_addr = forbid_multi_line_headers(
            "from", unexpected_from_addr, 'utf-8'
        )
545
        escaped_encoded_unexpected_from_addr = escape(encoded_unexpected_from_addr)
546 547 548 549 550 551 552

        # it's shorter than 320 characters when just encoded
        self.assertEqual(len(encoded_unexpected_from_addr), 318)
        # escaping it brings it over that limit
        self.assertEqual(len(escaped_encoded_unexpected_from_addr), 324)
        # when not escaped or encoded, it's well below 320 characters
        self.assertEqual(len(unexpected_from_addr), 137)
553

554 555 556 557 558 559 560 561
        self.login_as_user(instructor)
        send_mail_url = reverse('send_email', kwargs={'course_id': unicode(course.id)})
        response = self.client.post(send_mail_url, test_email)
        self.assertTrue(json.loads(response.content)['success'])

        self.assertEqual(len(mail.outbox), 1)
        from_email = mail.outbox[0].from_email

562
        expected_from_addr = (
563
            u'"{course_name}" Course Staff <{course_name}-no-reply@courseupdates.edx.org>'
564 565
        ).format(course_name=course.id.course)

566 567
        self.assertEqual(
            from_email,
568
            expected_from_addr
569
        )
570
        self.assertEqual(len(from_email), 61)
571

572
    @override_settings(BULK_EMAIL_EMAILS_PER_TASK=3)
573
    @patch('bulk_email.tasks.update_subtask_status')
574 575 576 577 578
    def test_chunked_queries_send_numerous_emails(self, email_mock):
        """
        Test sending a large number of emails, to test the chunked querying
        """
        mock_factory = MockCourseEmailResult()
579
        email_mock.side_effect = mock_factory.get_mock_update_subtask_status()
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
        added_users = []
        for _ in xrange(LARGE_NUM_EMAILS):
            user = UserFactory()
            added_users.append(user)
            CourseEnrollmentFactory.create(user=user, course_id=self.course.id)

        optouts = []
        for i in [1, 3, 9, 10, 18]:  # 5 random optouts
            user = added_users[i]
            optouts.append(user)
            optout = Optout(user=user, course_id=self.course.id)
            optout.save()

        test_email = {
            'action': 'Send email',
595
            'send_to': '["myself", "staff", "learners"]',
596 597 598
            'subject': 'test subject for all',
            'message': 'test message for all'
        }
599 600 601
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

602 603
        self.assertEquals(mock_factory.emails_sent,
                          1 + len(self.staff) + len(self.students) + LARGE_NUM_EMAILS - len(optouts))
604 605 606 607 608 609
        outbox_contents = [e.to[0] for e in mail.outbox]
        should_send_contents = ([self.instructor.email] +
                                [s.email for s in self.staff] +
                                [s.email for s in self.students] +
                                [s.email for s in added_users if s not in optouts])
        self.assertItemsEqual(outbox_contents, should_send_contents)
Christine Lytwynec committed
610 611


612
@attr(shard=1)
Christine Lytwynec committed
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
@skipIf(os.environ.get("TRAVIS") == 'true', "Skip this test in Travis CI.")
class TestEmailSendFromDashboard(EmailSendFromDashboardTestCase):
    """
    Tests email sending without mocked html_to_text.

    Note that these tests are skipped on Travis because we can't use the
    function `html_to_text` as it is currently implemented on Travis.
    """

    def test_unicode_message_send_to_all(self):
        """
        Make sure email (with Unicode characters) send to all goes there.
        """

        uni_message = u'ẗëṡẗ ṁëṡṡäġë ḟöṛ äḷḷ イ乇丂イ ᄊ乇丂丂ムg乇 キo尺 ムレレ тэѕт мэѕѕаБэ fоѓ аll'
        test_email = {
            'action': 'Send email',
630
            'send_to': '["myself", "staff", "learners"]',
Christine Lytwynec committed
631 632 633 634 635 636 637 638 639 640 641 642 643 644
            'subject': 'test subject for all',
            'message': uni_message
        }
        response = self.client.post(self.send_mail_url, test_email)
        self.assertEquals(json.loads(response.content), self.success_content)

        self.assertEquals(len(mail.outbox), 1 + len(self.staff) + len(self.students))
        self.assertItemsEqual(
            [e.to[0] for e in mail.outbox],
            [self.instructor.email] + [s.email for s in self.staff] + [s.email for s in self.students]
        )

        message_body = mail.outbox[0].body
        self.assertIn(uni_message, message_body)
645 646 647 648 649 650 651 652 653 654


class TestCourseEmailContext(SharedModuleStoreTestCase):
    """
    Test the course email context hash used to send bulk emails.
    """

    @classmethod
    def setUpClass(cls):
        """
655
        Create a course shared by all tests.
656 657 658 659 660 661 662 663 664 665 666 667 668
        """
        super(TestCourseEmailContext, cls).setUpClass()
        cls.course_title = u"Финансовое программирование и политика, часть 1: макроэкономические счета и анализ"
        cls.course_org = 'IMF'
        cls.course_number = "FPP.1x"
        cls.course_run = "2016"
        cls.course = CourseFactory.create(
            display_name=cls.course_title,
            org=cls.course_org,
            number=cls.course_number,
            run=cls.course_run,
        )

669
    def verify_email_context(self, email_context, scheme):
670 671 672
        """
        This test tests that the bulk email context uses http or https urls as appropriate.
        """
673
        self.assertEquals(email_context['platform_name'], settings.PLATFORM_NAME)
674 675 676 677 678 679 680 681 682 683 684 685 686
        self.assertEquals(email_context['course_title'], self.course_title)
        self.assertEquals(email_context['course_url'],
                          '{}://edx.org/courses/{}/{}/{}/'.format(scheme,
                                                                  self.course_org,
                                                                  self.course_number,
                                                                  self.course_run))
        self.assertEquals(email_context['course_image_url'],
                          '{}://edx.org/c4x/{}/{}/asset/images_course_image.jpg'.format(scheme,
                                                                                        self.course_org,
                                                                                        self.course_number))
        self.assertEquals(email_context['email_settings_url'], '{}://edx.org/dashboard'.format(scheme))
        self.assertEquals(email_context['account_settings_url'], '{}://edx.org/account/settings'.format(scheme))

687
    @override_settings(LMS_ROOT_URL="http://edx.org")
688 689 690 691 692 693 694
    def test_insecure_email_context(self):
        """
        This test tests that the bulk email context uses http urls
        """
        email_context = _get_course_email_context(self.course)
        self.verify_email_context(email_context, 'http')

695
    @override_settings(LMS_ROOT_URL="https://edx.org")
696 697 698 699 700 701
    def test_secure_email_context(self):
        """
        This test tests that the bulk email context uses https urls
        """
        email_context = _get_course_email_context(self.course)
        self.verify_email_context(email_context, 'https')