Skip to content
test_enrollment.py 51.9 KiB
Newer Older
from __future__ import division

__copyright__ = "Copyright (C) 2017 Dong Zhuang"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from django.test import TestCase, mock
from django.conf import settings
from django.test.utils import override_settings
from django.core import mail
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _

from relate.utils import string_concat

from course.models import (
    Course,
    Participation, ParticipationRole, ParticipationPreapproval)
from course.constants import participation_status, user_status

from .base_test_mixins import (
    SingleCourseTestMixin,
    NONE_PARTICIPATION_USER_CREATE_KWARG_LIST,
    FallBackStorageMessageTestMixin
)
from .utils import LocmemBackendTestsMixin


TEST_EMAIL_SUFFIX1 = "@suffix.com"
TEST_EMAIL_SUFFIX2 = "suffix.com"

EMAIL_CONNECTIONS = "EMAIL_CONNECTIONS"
EMAIL_CONNECTION_DEFAULT = "EMAIL_CONNECTION_DEFAULT"
NO_REPLY_EMAIL_FROM = "NO_REPLY_EMAIL_FROM"
NOTIFICATION_EMAIL_FROM = "NOTIFICATION_EMAIL_FROM"
GRADER_FEEDBACK_EMAIL_FROM = "GRADER_FEEDBACK_EMAIL_FROM"
STUDENT_INTERACT_EMAIL_FROM = "STUDENT_INTERACT_EMAIL_FROM"
ENROLLMENT_EMAIL_FROM = "ENROLLMENT_EMAIL_FROM"

# {{{ message constants

MESSAGE_ENROLLMENT_SENT_TEXT = _(
    "Enrollment request sent. You will receive notifcation "
    "by email once your request has been acted upon.")
MESSAGE_ENROLL_REQUEST_PENDING_TEXT = _(
    "Your enrollment request is pending. You will be "
    "notified once it has been acted upon.")
MESSAGE_ENROLL_DENIED_NOT_ALLOWED_TEXT = _(
    "Your enrollment request had been denied. Enrollment is not allowed.")
MESSAGE_ENROLL_DROPPED_NOT_ALLOWED_TEXT = _(
    "You had been dropped from the course. Re-enrollment is not allowed.")
MESSAGE_ENROLL_REQUEST_ALREADY_PENDING_TEXT = _(
    "You have previously sent the enrollment request. "
    "Re-sending the request is not allowed.")
MESSAGE_PARTICIPATION_ALREADY_EXIST_TEXT = _(
    "A participation already exists. Enrollment attempt aborted.")
MESSAGE_CANNOT_REENROLL_TEXT = _("Already enrolled. Cannot re-enroll.")
MESSAGE_SUCCESSFULLY_ENROLLED_TEXT = _("Successfully enrolled.")
MESSAGE_EMAIL_SUFFIX_REQUIRED_PATTERN = _(
    "Enrollment not allowed. Please use your '%s' email to enroll.")
MESSAGE_NOT_ACCEPTING_ENROLLMENTS_TEXT = _("Course is not accepting enrollments.")
MESSAGE_ENROLL_ONLY_ACCEPT_POST_REQUEST_TEXT = _(
    "Can only enroll using POST request")
MESSAGE_ENROLLMENT_DENIED_TEXT = _("Successfully denied.")
MESSAGE_ENROLLMENT_DROPPED_TEXT = _("Successfully dropped.")

MESSAGE_BATCH_PREAPPROVED_RESULT_PATTERN = _(
    "%(n_created)d preapprovals created, "
    "%(n_exist)d already existed, "
    "%(n_requested_approved)d pending requests approved.")

MESSAGE_EMAIL_NOT_CONFIRMED_TEXT = _(
    "Your email address is not yet confirmed. "
    "Confirm your email to continue.")
MESSAGE_PARTICIPATION_CHANGE_SAVED_TEXT = _("Changes saved.")

EMAIL_NEW_ENROLLMENT_REQUEST_TITLE_PATTERN = (
    string_concat("[%s] ", _("New enrollment request")))
EMAIL_ENROLLMENT_DECISION_TITLE_PATTERN = (
    string_concat("[%s] ", _("Your enrollment request")))

VALIDATION_ERROR_USER_NOT_CONFIRMED = _(
    "This user has not confirmed his/her email.")

# }}}


def course_get_object_or_404_sf_enroll_apprv_not_required(klass, *args, **kwargs):
    assert klass == Course
    course_object = get_object_or_404(klass, *args, **kwargs)
    course_object.enrollment_approval_required = False
    return course_object


def course_get_object_or_404_sf_not_accepts_enrollment(klass, *args, **kwargs):
    assert klass == Course
    course_object = get_object_or_404(klass, *args, **kwargs)
    course_object.accepts_enrollment = False
    return course_object


def course_get_object_or_404_sf_not_email_suffix1(klass, *args, **kwargs):
    assert klass == Course
    course_object = get_object_or_404(klass, *args, **kwargs)
    course_object.enrollment_required_email_suffix = TEST_EMAIL_SUFFIX1
    return course_object


def course_get_object_or_404_sf_not_email_suffix2(klass, *args, **kwargs):
    assert klass == Course
    course_object = get_object_or_404(klass, *args, **kwargs)
    course_object.enrollment_required_email_suffix = TEST_EMAIL_SUFFIX2
    return course_object


class BaseEmailConnectionMixin:
    EMAIL_CONNECTIONS = None
    EMAIL_CONNECTION_DEFAULT = None
    NO_REPLY_EMAIL_FROM = None
    NOTIFICATION_EMAIL_FROM = None
    GRADER_FEEDBACK_EMAIL_FROM = None
    STUDENT_INTERACT_EMAIL_FROM = None
    ENROLLMENT_EMAIL_FROM = None
    ROBOT_EMAIL_FROM = "robot@example.com"

    def setUp(self):
        kwargs = {}
        for attr in [EMAIL_CONNECTIONS, EMAIL_CONNECTION_DEFAULT,
                     NO_REPLY_EMAIL_FROM, NOTIFICATION_EMAIL_FROM,
                     GRADER_FEEDBACK_EMAIL_FROM, STUDENT_INTERACT_EMAIL_FROM,
                     ENROLLMENT_EMAIL_FROM]:
            attr_value = getattr(self, attr, None)
            if attr_value:
                kwargs.update({attr: attr_value})

        self.settings_email_connection_override = (
            override_settings(**kwargs))
        self.settings_email_connection_override.enable()

    def tearDown(self):
        self.settings_email_connection_override.disable()


class EnrollmentTestBaseMixin(SingleCourseTestMixin,
                              FallBackStorageMessageTestMixin):
    none_participation_user_create_kwarg_list = (
        NONE_PARTICIPATION_USER_CREATE_KWARG_LIST)

    @classmethod
    def setUpTestData(cls):  # noqa
        super(EnrollmentTestBaseMixin, cls).setUpTestData()
        assert cls.non_participation_users.count() >= 4
        cls.non_participation_user1 = cls.non_participation_users[0]
        cls.non_participation_user2 = cls.non_participation_users[1]
        cls.non_participation_user3 = cls.non_participation_users[2]
        cls.non_participation_user4 = cls.non_participation_users[3]
        if cls.non_participation_user1.status != user_status.active:
            cls.non_participation_user1.status = user_status.active
            cls.non_participation_user1.save()
        if cls.non_participation_user2.status != user_status.active:
            cls.non_participation_user2.status = user_status.active
            cls.non_participation_user2.save()
        if cls.non_participation_user3.status != user_status.unconfirmed:
            cls.non_participation_user3.status = user_status.unconfirmed
            cls.non_participation_user3.save()
        if cls.non_participation_user4.status != user_status.unconfirmed:
            cls.non_participation_user4.status = user_status.unconfirmed
            cls.non_participation_user4.save()

    @property
    def enroll_request_url(self):
        return reverse("relate-enroll", args=[self.course.identifier])

    @classmethod
    def get_participation_edit_url(cls, participation_id):
        return reverse("relate-edit_participation",
                       args=[cls.course.identifier, participation_id])

    def get_participation_count_by_status(self, status):
Loading
Loading full blame...