Skip to content
test_enrollment.py 54.4 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.
"""

Dong Zhuang's avatar
Dong Zhuang committed
import six
Dong Zhuang's avatar
Dong Zhuang committed
import unittest
Dong Zhuang's avatar
Dong Zhuang committed
from django.test import TestCase
from django.conf import settings
Dong Zhuang's avatar
Dong Zhuang committed
from django.test.utils import override_settings  # noqa
from django.core import mail
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.urls import reverse

from relate.utils import string_concat

Dong Zhuang's avatar
Dong Zhuang committed
from course import constants
Dong Zhuang's avatar
Dong Zhuang committed
from course import enrollment
from course.models import (
    Participation, ParticipationRole, ParticipationPreapproval)
Dong Zhuang's avatar
Dong Zhuang committed
from course.constants import (
    participation_status as p_status, user_status as u_status)
Dong Zhuang's avatar
Dong Zhuang committed
from tests.base_test_mixins import (
Dong Zhuang's avatar
Dong Zhuang committed
    CoursesTestMixinBase, SingleCourseTestMixin,
    FallBackStorageMessageTestMixin
)
Dong Zhuang's avatar
Dong Zhuang committed
from tests.utils import LocmemBackendTestsMixin, mock
Dong Zhuang's avatar
Dong Zhuang committed
from tests import factories

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

Dong Zhuang's avatar
Dong Zhuang committed
MESSAGE_ENROLLMENT_SENT_TEXT = (
    "Enrollment request sent. You will receive notifcation "
    "by email once your request has been acted upon.")
Dong Zhuang's avatar
Dong Zhuang committed
MESSAGE_ENROLL_REQUEST_PENDING_TEXT = (
    "Your enrollment request is pending. You will be "
    "notified once it has been acted upon.")
Dong Zhuang's avatar
Dong Zhuang committed
MESSAGE_ENROLL_DENIED_NOT_ALLOWED_TEXT = (
    "Your enrollment request had been denied. Enrollment is not allowed.")
Dong Zhuang's avatar
Dong Zhuang committed
MESSAGE_ENROLL_DROPPED_NOT_ALLOWED_TEXT = (
    "You had been dropped from the course. Re-enrollment is not allowed.")
Dong Zhuang's avatar
Dong Zhuang committed
MESSAGE_ENROLL_REQUEST_ALREADY_PENDING_TEXT = (
    "You have previously sent the enrollment request. "
    "Re-sending the request is not allowed.")
Dong Zhuang's avatar
Dong Zhuang committed
MESSAGE_PARTICIPATION_ALREADY_EXIST_TEXT = (
    "A participation already exists. Enrollment attempt aborted.")
Dong Zhuang's avatar
Dong Zhuang committed
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.")
Dong Zhuang's avatar
Dong Zhuang committed
MESSAGE_NOT_ACCEPTING_ENROLLMENTS_TEXT = ("Course is not accepting enrollments.")
MESSAGE_ENROLL_ONLY_ACCEPT_POST_REQUEST_TEXT = (
    "Can only enroll using POST request")
Dong Zhuang's avatar
Dong Zhuang committed
MESSAGE_ENROLLMENT_DENIED_TEXT = "Successfully denied."
MESSAGE_ENROLLMENT_DROPPED_TEXT = "Successfully dropped."
Dong Zhuang's avatar
Dong Zhuang committed
MESSAGE_BATCH_PREAPPROVED_RESULT_PATTERN = (
    "%(n_created)d preapprovals created, "
    "%(n_exist)d already existed, "
    "%(n_requested_approved)d pending requests approved.")

Dong Zhuang's avatar
Dong Zhuang committed
MESSAGE_EMAIL_NOT_CONFIRMED_TEXT = (
    "Your email address is not yet confirmed. "
    "Confirm your email to continue.")
Dong Zhuang's avatar
Dong Zhuang committed
MESSAGE_PARTICIPATION_CHANGE_SAVED_TEXT = ("Changes saved.")

EMAIL_NEW_ENROLLMENT_REQUEST_TITLE_PATTERN = (
Dong Zhuang's avatar
Dong Zhuang committed
    string_concat("[%s] ", "New enrollment request"))
EMAIL_ENROLLMENT_DECISION_TITLE_PATTERN = (
Dong Zhuang's avatar
Dong Zhuang committed
    string_concat("[%s] ", "Your enrollment request"))
Dong Zhuang's avatar
Dong Zhuang committed
VALIDATION_ERROR_USER_NOT_CONFIRMED = (
    "This user has not confirmed his/her email.")

# }}}


Dong Zhuang's avatar
Dong Zhuang committed
class EnrollmentTestMixin(CoursesTestMixinBase):
    @classmethod
    def setUpTestData(cls):  # noqa
        super(EnrollmentTestMixin, cls).setUpTestData()
        cls.course = factories.CourseFactory()

    def setUp(self):
Dong Zhuang's avatar
Dong Zhuang committed
        super(EnrollmentTestMixin, self).setUp()
        self.course.refresh_from_db()
        fake_add_message = mock.patch('course.enrollment.messages.add_message')
        self.mock_add_message = fake_add_message.start()
        self.addCleanup(fake_add_message.stop)
Dong Zhuang's avatar
Dong Zhuang committed
    @property
    def course_page_url(self):
        return self.get_course_page_url(self.course.identifier)

    @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):
        return Participation.objects.filter(
            course__identifier=self.course.identifier,
            status=status
        ).count()

Dong Zhuang's avatar
Dong Zhuang committed
    def update_course(self, **kwargs):
        self.course.__dict__.update(kwargs)
        self.course.save()

    def update_require_approval_course(self, **kwargs):
        self.course.__dict__.update(kwargs)
        self.course.enrollment_approval_required = True
        self.course.save()

    def get_test_participation(self, **kwargs):
        return factories.ParticipationFactory(
            course=self.course, **kwargs)

    def get_test_preapproval(self, **kwargs):
        defaults = {"course": self.course,
                    "email": None,
                    "institutional_id": None}
        defaults.update(kwargs)

        return factories.ParticipationPreapprovalFactory(**defaults)

    def assertMockAddedMessagesCalledWith(self, expected_messages, reset=True):  # noqa
        args = "; ".join([
            "'%s'" % str(arg[2])
            for arg, _ in self.mock_add_message.call_args_list])
        if not isinstance(expected_messages, list):
            expected_messages = [expected_messages]

        not_called = []
        for msg in expected_messages:
            if msg not in args:
                not_called.append(msg)

        if not_called:
            self.fail(
                "%s unexpectedly not added in messages, "
                "the actual message are \"%s\"" % (repr(not_called), args))
        if reset:
            self.mock_add_message.reset_mock()

    def assertParticiaptionStatusCallCount(self, expected_counts):  # noqa
        from collections import OrderedDict
        d = OrderedDict()
        counts = []
        for status in sorted(
                list(dict(constants.PARTICIPATION_STATUS_CHOICES).keys())):
            count = Participation.objects.filter(
                course=self.course, status=status
            ).count()
            d[status] = count
            counts.append(count)

        self.assertListEqual(counts, expected_counts, repr(d))

    @property
    def student_role_post_data(self):
        role, _ = (ParticipationRole.objects.get_or_create(
            course=self.course, identifier="student"))
        return [str(role.pk)]
Loading
Loading full blame...