test_forms.py 12.1 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4 5 6
"""
Unit tests for bulk-email-related forms.
"""
from django.conf import settings
from mock import patch
7
from nose.plugins.attrib import attr
8

9 10
from bulk_email.models import CourseAuthorization, CourseEmailTemplate
from bulk_email.forms import CourseAuthorizationAdminForm, CourseEmailTemplateForm
Ned Batchelder committed
11
from xmodule.modulestore.tests.django_utils import TEST_DATA_MIXED_TOY_MODULESTORE
12
from opaque_keys.edx.locations import SlashSeparatedCourseKey
13 14 15 16
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.django import modulestore
from xmodule.modulestore import ModuleStoreEnum
17 18


19
@attr('shard_1')
20 21 22 23
class CourseAuthorizationFormTest(ModuleStoreTestCase):
    """Test the CourseAuthorizationAdminForm form for Mongo-backed courses."""

    def setUp(self):
24
        super(CourseAuthorizationFormTest, self).setUp()
25 26
        course_title = u"ẗëṡẗ title イ乇丂イ ᄊ乇丂丂ムg乇 キo尺 ムレレ тэѕт мэѕѕаБэ"
        self.course = CourseFactory.create(display_name=course_title)
27

28
    @patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': True})
29 30 31 32
    def test_authorize_mongo_course(self):
        # Initially course shouldn't be authorized
        self.assertFalse(CourseAuthorization.instructor_email_enabled(self.course.id))
        # Test authorizing the course, which should totally work
33
        form_data = {'course_id': self.course.id.to_deprecated_string(), 'email_enabled': True}
34 35 36 37 38 39 40
        form = CourseAuthorizationAdminForm(data=form_data)
        # Validation should work
        self.assertTrue(form.is_valid())
        form.save()
        # Check that this course is authorized
        self.assertTrue(CourseAuthorization.instructor_email_enabled(self.course.id))

41
    @patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': True})
42 43 44 45
    def test_repeat_course(self):
        # Initially course shouldn't be authorized
        self.assertFalse(CourseAuthorization.instructor_email_enabled(self.course.id))
        # Test authorizing the course, which should totally work
46
        form_data = {'course_id': self.course.id.to_deprecated_string(), 'email_enabled': True}
47 48 49 50 51 52 53 54
        form = CourseAuthorizationAdminForm(data=form_data)
        # Validation should work
        self.assertTrue(form.is_valid())
        form.save()
        # Check that this course is authorized
        self.assertTrue(CourseAuthorization.instructor_email_enabled(self.course.id))

        # Now make a new course authorization with the same course id that tries to turn email off
55
        form_data = {'course_id': self.course.id.to_deprecated_string(), 'email_enabled': False}
56 57 58 59 60 61 62 63 64 65 66 67 68 69
        form = CourseAuthorizationAdminForm(data=form_data)
        # Validation should not work because course_id field is unique
        self.assertFalse(form.is_valid())
        self.assertEquals(
            "Course authorization with this Course id already exists.",
            form._errors['course_id'][0]  # pylint: disable=protected-access
        )
        with self.assertRaisesRegexp(ValueError, "The CourseAuthorization could not be created because the data didn't validate."):
            form.save()

        # Course should still be authorized (invalid attempt had no effect)
        self.assertTrue(CourseAuthorization.instructor_email_enabled(self.course.id))

    @patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': True})
70 71
    def test_form_typo(self):
        # Munge course id
72
        bad_id = SlashSeparatedCourseKey(u'Broken{}'.format(self.course.id.org), 'hello', self.course.id.run + '_typo')
73

74
        form_data = {'course_id': bad_id.to_deprecated_string(), 'email_enabled': True}
75 76 77 78
        form = CourseAuthorizationAdminForm(data=form_data)
        # Validation shouldn't work
        self.assertFalse(form.is_valid())

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
        msg = u'COURSE NOT FOUND'
        msg += u' --- Entered course id was: "{0}". '.format(bad_id.to_deprecated_string())
        msg += 'Please recheck that you have supplied a valid course id.'
        self.assertEquals(msg, form._errors['course_id'][0])  # pylint: disable=protected-access

        with self.assertRaisesRegexp(ValueError, "The CourseAuthorization could not be created because the data didn't validate."):
            form.save()

    @patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': True})
    def test_form_invalid_key(self):
        form_data = {'course_id': "asd::**!@#$%^&*())//foobar!!", 'email_enabled': True}
        form = CourseAuthorizationAdminForm(data=form_data)
        # Validation shouldn't work
        self.assertFalse(form.is_valid())

        msg = u'Course id invalid.'
        msg += u' --- Entered course id was: "asd::**!@#$%^&*())//foobar!!". '
        msg += 'Please recheck that you have supplied a valid course id.'
97 98 99 100 101
        self.assertEquals(msg, form._errors['course_id'][0])  # pylint: disable=protected-access

        with self.assertRaisesRegexp(ValueError, "The CourseAuthorization could not be created because the data didn't validate."):
            form.save()

102
    @patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': True})
103 104
    def test_course_name_only(self):
        # Munge course id - common
105
        form_data = {'course_id': self.course.id.run, 'email_enabled': True}
106 107 108 109
        form = CourseAuthorizationAdminForm(data=form_data)
        # Validation shouldn't work
        self.assertFalse(form.is_valid())

110
        error_msg = form._errors['course_id'][0]
111 112
        self.assertIn(u'--- Entered course id was: "{0}". '.format(self.course.id.run), error_msg)
        self.assertIn(u'Please recheck that you have supplied a valid course id.', error_msg)
113 114 115 116 117 118 119

        with self.assertRaisesRegexp(ValueError, "The CourseAuthorization could not be created because the data didn't validate."):
            form.save()


class CourseAuthorizationXMLFormTest(ModuleStoreTestCase):
    """Check that XML courses cannot be authorized for email."""
120
    MODULESTORE = TEST_DATA_MIXED_TOY_MODULESTORE
121

122
    @patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': True})
123
    def test_xml_course_authorization(self):
124
        course_id = SlashSeparatedCourseKey('edX', 'toy', '2012_Fall')
125
        # Assert this is an XML course
126
        self.assertEqual(modulestore().get_modulestore_type(course_id), ModuleStoreEnum.Type.xml)
127

128
        form_data = {'course_id': course_id.to_deprecated_string(), 'email_enabled': True}
129 130 131 132 133
        form = CourseAuthorizationAdminForm(data=form_data)
        # Validation shouldn't work
        self.assertFalse(form.is_valid())

        msg = u"Course Email feature is only available for courses authored in Studio. "
134
        msg += u'"{0}" appears to be an XML backed course.'.format(course_id.to_deprecated_string())
135 136 137 138
        self.assertEquals(msg, form._errors['course_id'][0])  # pylint: disable=protected-access

        with self.assertRaisesRegexp(ValueError, "The CourseAuthorization could not be created because the data didn't validate."):
            form.save()
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


class CourseEmailTemplateFormTest(ModuleStoreTestCase):
    """Test the CourseEmailTemplateForm that is used in the Django admin subsystem."""

    def test_missing_message_body_in_html(self):
        """
        Asserts that we fail validation if we do not have the {{message_body}} tag
        in the submitted HTML template
        """
        form_data = {
            'html_template': '',
            'plain_template': '{{message_body}}',
            'name': ''
        }
        form = CourseEmailTemplateForm(form_data)
        self.assertFalse(form.is_valid())

    def test_missing_message_body_in_plain(self):
        """
        Asserts that we fail validation if we do not have the {{message_body}} tag
        in the submitted plain template
        """
        form_data = {
            'html_template': '{{message_body}}',
            'plain_template': '',
            'name': ''
        }
        form = CourseEmailTemplateForm(form_data)
        self.assertFalse(form.is_valid())

    def test_blank_name_is_null(self):
        """
        Asserts that submitting a CourseEmailTemplateForm with a blank name is stored
        as a NULL in the database
        """
        form_data = {
            'html_template': '{{message_body}}',
            'plain_template': '{{message_body}}',
            'name': ''
        }
        form = CourseEmailTemplateForm(form_data)
        self.assertTrue(form.is_valid())
        form.save()

        # now inspect the database and make sure the blank name was stored as a NULL
        # Note this will throw an exception if it is not found
        cet = CourseEmailTemplate.objects.get(name=None)
        self.assertIsNotNone(cet)

    def test_name_with_only_spaces_is_null(self):
        """
        Asserts that submitting a CourseEmailTemplateForm just blank whitespace is stored
        as a NULL in the database
        """
        form_data = {
            'html_template': '{{message_body}}',
            'plain_template': '{{message_body}}',
            'name': '   '
        }
        form = CourseEmailTemplateForm(form_data)
        self.assertTrue(form.is_valid())
        form.save()

        # now inspect the database and make sure the whitespace only name was stored as a NULL
        # Note this will throw an exception if it is not found
        cet = CourseEmailTemplate.objects.get(name=None)
        self.assertIsNotNone(cet)

    def test_name_with_spaces_is_trimmed(self):
        """
        Asserts that submitting a CourseEmailTemplateForm with a name that contains
        whitespace at the beginning or end of a name is stripped
        """
        form_data = {
            'html_template': '{{message_body}}',
            'plain_template': '{{message_body}}',
            'name': ' foo  '
        }
        form = CourseEmailTemplateForm(form_data)
        self.assertTrue(form.is_valid())
        form.save()

        # now inspect the database and make sure the name is properly
        # stripped
        cet = CourseEmailTemplate.objects.get(name='foo')
        self.assertIsNotNone(cet)

    def test_non_blank_name(self):
        """
        Asserts that submitting a CourseEmailTemplateForm with a non-blank name
        can be found in the database under than name as a look-up key
        """
        form_data = {
            'html_template': '{{message_body}}',
            'plain_template': '{{message_body}}',
            'name': 'foo'
        }
        form = CourseEmailTemplateForm(form_data)
        self.assertTrue(form.is_valid())
        form.save()

        # now inspect the database and make sure the blank name was stored as a NULL
        # Note this will throw an exception if it is not found
        cet = CourseEmailTemplate.objects.get(name='foo')
        self.assertIsNotNone(cet)

    def test_duplicate_name(self):
        """
        Assert that we cannot submit a CourseEmailTemplateForm with a name
        that already exists
        """

        # first set up one template
        form_data = {
            'html_template': '{{message_body}}',
            'plain_template': '{{message_body}}',
            'name': 'foo'
        }
        form = CourseEmailTemplateForm(form_data)
        self.assertTrue(form.is_valid())
        form.save()

        # try to submit form with the same name
        form = CourseEmailTemplateForm(form_data)
        self.assertFalse(form.is_valid())

        # try again with a name with extra whitespace
        # this should fail as we strip the whitespace away
        form_data = {
            'html_template': '{{message_body}}',
            'plain_template': '{{message_body}}',
            'name': '  foo '
        }
        form = CourseEmailTemplateForm(form_data)
        self.assertFalse(form.is_valid())

        # then try a different name
        form_data = {
            'html_template': '{{message_body}}',
            'plain_template': '{{message_body}}',
            'name': 'bar'
        }
        form = CourseEmailTemplateForm(form_data)
        self.assertTrue(form.is_valid())
        form.save()

        form = CourseEmailTemplateForm(form_data)
        self.assertFalse(form.is_valid())