Skip to content
test_enrollment.py 75 KiB
Newer Older
__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 unittest
Josh Asplund's avatar
Josh Asplund committed
import pytest
from django.test import TestCase, RequestFactory
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.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,
    SingleCoursePageTestMixin, MockAddMessageMixing)
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.")

# }}}


Andreas Klöckner's avatar
Andreas Klöckner committed
def get_not_empty_count_from_list(lst):
    return len([data for data in lst if data.strip()])
class EnrollmentTestMixin(MockAddMessageMixing, CoursesTestMixinBase):

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

    def setUp(self):
        super().setUp()
Dong Zhuang's avatar
Dong Zhuang committed
        self.course.refresh_from_db()
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 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)]

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

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

    def get_preapproval_count(self):
        return ParticipationPreapproval.objects.all().count()

Dong Zhuang's avatar
Dong Zhuang committed
class EnrollViewTest(EnrollmentTestMixin, TestCase):
    # test enrollment.enroll_view

    def test_participation_status_requested(self):
        participation = self.get_test_participation(
Loading
Loading full blame...