Skip to content
test_enrollment.py 75 KiB
Newer Older
from __future__ import annotations


__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
Andreas Klöckner's avatar
Andreas Klöckner committed

Josh Asplund's avatar
Josh Asplund committed
import pytest
from django.conf import settings
from django.contrib.auth import get_user_model
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.core import mail
from django.test import RequestFactory, TestCase
from django.test.utils import override_settings  # noqa
from django.urls import reverse

Andreas Klöckner's avatar
Andreas Klöckner committed
from course import constants, enrollment
Dong Zhuang's avatar
Dong Zhuang committed
from course.constants import (
    participation_status as p_status,
    user_status as u_status,
Andreas Klöckner's avatar
Andreas Klöckner committed
)
from course.models import Participation, ParticipationPreapproval, ParticipationRole
from relate.utils import string_concat
from tests import factories
Dong Zhuang's avatar
Dong Zhuang committed
from tests.base_test_mixins import (
    CoursesTestMixinBase,
    MockAddMessageMixing,
    SingleCoursePageTestMixin,
Andreas Klöckner's avatar
Andreas Klöckner committed
    SingleCourseTestMixin,
)
Dong Zhuang's avatar
Dong Zhuang committed
from tests.utils import LocmemBackendTestsMixin, mock
Andreas Klöckner's avatar
Andreas Klöckner committed


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 notification "
    "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):
        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 assertParticipationStatusCallCount(self, expected_counts):  # noqa
Dong Zhuang's avatar
Dong Zhuang committed
        from collections import OrderedDict
        d = OrderedDict()
        counts = []
        for status in sorted(
                dict(constants.PARTICIPATION_STATUS_CHOICES).keys()):
Dong Zhuang's avatar
Dong Zhuang committed
            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(
            status=p_status.requested)
        self.assertParticipationStatusCallCount([0, 0, 0, 1])
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(participation.user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_ENROLL_REQUEST_ALREADY_PENDING_TEXT)
        self.assertParticipationStatusCallCount([0, 0, 0, 1])
        self.assertEqual(len(mail.outbox), 0)

Dong Zhuang's avatar
Dong Zhuang committed
    def test_participation_status_denied(self):
        participation = self.get_test_participation(
            status=p_status.denied)
        self.assertParticipationStatusCallCount([0, 1, 0, 0])
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(participation.user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_ENROLL_DENIED_NOT_ALLOWED_TEXT)
        self.assertParticipationStatusCallCount([0, 1, 0, 0])
        self.assertEqual(len(mail.outbox), 0)

Dong Zhuang's avatar
Dong Zhuang committed
    def test_participation_status_dropped(self):
        participation = self.get_test_participation(
            status=p_status.dropped)
        self.assertParticipationStatusCallCount([0, 0, 1, 0])
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(participation.user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_ENROLL_DROPPED_NOT_ALLOWED_TEXT)
        self.assertParticipationStatusCallCount([0, 0, 1, 0])
        self.assertEqual(len(mail.outbox), 0)
Dong Zhuang's avatar
Dong Zhuang committed

Dong Zhuang's avatar
Dong Zhuang committed
    def test_participation_status_active(self):
        participation = self.get_test_participation(
            status=p_status.active)
        self.assertParticipationStatusCallCount([1, 0, 0, 0])
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(participation.user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_CANNOT_REENROLL_TEXT)
        self.assertParticipationStatusCallCount([1, 0, 0, 0])
        self.assertEqual(len(mail.outbox), 0)

Dong Zhuang's avatar
Dong Zhuang committed
    def test_not_accepts_enrollment(self):
        self.update_course(accepts_enrollment=False)
        user = factories.UserFactory()

        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_NOT_ACCEPTING_ENROLLMENTS_TEXT)
        self.assertParticipationStatusCallCount([0, 0, 0, 0])
        self.assertEqual(len(mail.outbox), 0)

Dong Zhuang's avatar
Dong Zhuang committed
    def test_not_post_request(self):
        user = factories.UserFactory()
        with self.temporarily_switch_to_user(user):
            resp = self.client.get(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
            self.assertRedirects(
                resp, self.course_page_url, fetch_redirect_response=False)
            self.assertAddMessageCallCount(1)
            self.assertAddMessageCalledWith(
                MESSAGE_ENROLL_ONLY_ACCEPT_POST_REQUEST_TEXT)
        self.assertParticipationStatusCallCount([0, 0, 0, 0])
        self.assertEqual(len(mail.outbox), 0)

Dong Zhuang's avatar
Dong Zhuang committed
    def test_user_not_active(self):
        for status in dict(constants.USER_STATUS_CHOICES).keys():
            if status != u_status.active:
                with self.subTest(user_status=status):
                    user = factories.UserFactory(status=status)
                    with self.temporarily_switch_to_user(user):
                        resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
                    self.assertRedirects(
                        resp, self.course_page_url, fetch_redirect_response=False)
                    self.assertAddMessageCallCount(1)
                    self.assertAddMessageCalledWith(
                        MESSAGE_EMAIL_NOT_CONFIRMED_TEXT)
        self.assertParticipationStatusCallCount([0, 0, 0, 0])
        self.assertEqual(len(mail.outbox), 0)

Dong Zhuang's avatar
Dong Zhuang committed
    def test_no_restrictions(self):
        user = factories.UserFactory()
        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_SUCCESSFULLY_ENROLLED_TEXT)
Dong Zhuang's avatar
Dong Zhuang committed

        self.assertParticipationStatusCallCount([1, 0, 0, 0])
Dong Zhuang's avatar
Dong Zhuang committed

    def test_no_restrictions_user_has_no_instid(self):
        user = factories.UserFactory(institutional_id=None)
        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_SUCCESSFULLY_ENROLLED_TEXT)
Dong Zhuang's avatar
Dong Zhuang committed

        self.assertParticipationStatusCallCount([1, 0, 0, 0])
Dong Zhuang's avatar
Dong Zhuang committed

    def test_not_matching_preapproved_email(self):
        self.update_require_approval_course()
        user = factories.UserFactory()
        self.get_test_preapproval(email="blabla@com")

        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_ENROLLMENT_SENT_TEXT)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(len(mail.outbox), 1)
        self.assertParticipationStatusCallCount([0, 0, 0, 1])
Dong Zhuang's avatar
Dong Zhuang committed

    def test_matched_preapproved_email(self):
        self.update_require_approval_course()
        user = factories.UserFactory()
        self.get_test_preapproval(email=user.email)

        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_SUCCESSFULLY_ENROLLED_TEXT)
        self.assertParticipationStatusCallCount([1, 0, 0, 0])
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(len(mail.outbox), 1)
Dong Zhuang's avatar
Dong Zhuang committed

    def test_course_not_require_inst_id_verified(self):
Dong Zhuang's avatar
Dong Zhuang committed
        self.update_require_approval_course(
            preapproval_require_verified_inst_id=False)

        for verified in [True, False]:
            with self.subTest(user_inst_id_verified=verified):
                user = factories.UserFactory(institutional_id_verified=verified)
                self.get_test_preapproval(institutional_id=user.institutional_id)

                with self.temporarily_switch_to_user(user):
                    resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
                self.assertRedirects(
                    resp, self.course_page_url, fetch_redirect_response=False)
                self.assertAddMessageCallCount(1)
                self.assertAddMessageCalledWith(MESSAGE_SUCCESSFULLY_ENROLLED_TEXT)
Dong Zhuang's avatar
Dong Zhuang committed

        self.assertParticipationStatusCallCount([2, 0, 0, 0])
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(len(mail.outbox), 2)
    def test_course_require_inst_id_verified_user_inst_id_verified1(self):
Dong Zhuang's avatar
Dong Zhuang committed
        # matched
        self.update_require_approval_course(
            preapproval_require_verified_inst_id=True)

        user = factories.UserFactory(institutional_id_verified=True)
        self.get_test_preapproval(institutional_id=user.institutional_id)

        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_SUCCESSFULLY_ENROLLED_TEXT)
        self.assertParticipationStatusCallCount([1, 0, 0, 0])
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(len(mail.outbox), 1)
Dong Zhuang's avatar
Dong Zhuang committed

    def test_course_require_inst_id_verified_user_inst_id_verified2(self):
Dong Zhuang's avatar
Dong Zhuang committed
        # not matched
        self.update_require_approval_course(
            preapproval_require_verified_inst_id=True)
Dong Zhuang's avatar
Dong Zhuang committed
        user = factories.UserFactory(institutional_id_verified=True)
        self.get_test_preapproval(institutional_id="not_exist_instid")
Dong Zhuang's avatar
Dong Zhuang committed

Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_ENROLLMENT_SENT_TEXT)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(len(mail.outbox), 1)
        self.assertParticipationStatusCallCount([0, 0, 0, 1])
Dong Zhuang's avatar
Dong Zhuang committed

    def test_preapprved_user_updated_inst_id_after_req_enrollment_roles_match(self):
        # Check assigned roles, testing issue #735
        self.update_require_approval_course(
            preapproval_require_verified_inst_id=True)

        user = factories.UserFactory()
        inst_id = user.institutional_id

        # Temporarily remove his/her inst_id
        user.institutional_id = None
        user.save()

        expected_role_identifier = "test_student"

        self.get_test_preapproval(
            institutional_id=inst_id, roles=[expected_role_identifier])

        with self.temporarily_switch_to_user(user):
            self.client.post(self.enroll_request_url)

        # Add back the inst_id
        user.institutional_id = inst_id
        user.institutional_id_verified = True
        user.save()

        user_participation = Participation.objects.get(user=user)
        self.assertIn(expected_role_identifier,
                      [role.identifier for role in user_participation.roles.all()])

    def test_course_require_inst_id_verified_user_inst_id_not_verified1(self):
Dong Zhuang's avatar
Dong Zhuang committed
        # thought matched
        self.update_require_approval_course(
            preapproval_require_verified_inst_id=True)

        user = factories.UserFactory(institutional_id_verified=False)
        self.get_test_preapproval(institutional_id=user.institutional_id)

        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_ENROLLMENT_SENT_TEXT)
        self.assertParticipationStatusCallCount([0, 0, 0, 1])
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(len(mail.outbox), 1)
    def test_course_require_inst_id_verified_user_inst_id_not_verified2(self):
Dong Zhuang's avatar
Dong Zhuang committed
        # not matched
        self.update_require_approval_course(
            preapproval_require_verified_inst_id=True)

        user = factories.UserFactory(institutional_id_verified=False)
        self.get_test_preapproval(institutional_id="not_exist_instid")

        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_ENROLLMENT_SENT_TEXT)
        self.assertParticipationStatusCallCount([0, 0, 0, 1])
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(len(mail.outbox), 1)
    def test_course_require_email_suffix_but_need_approval(self):
Dong Zhuang's avatar
Dong Zhuang committed
        self.update_require_approval_course(
            enrollment_required_email_suffix="@blabla.com")
Dong Zhuang's avatar
Dong Zhuang committed
        user = factories.UserFactory(email="abc@blabla.com")
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_ENROLLMENT_SENT_TEXT)
        self.assertParticipationStatusCallCount([0, 0, 0, 1])
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(len(mail.outbox), 1)
Dong Zhuang's avatar
Dong Zhuang committed

    def test_course_require_email_suffix_passed_without_at(self):
Dong Zhuang's avatar
Dong Zhuang committed
        # without @ in suffix config
        self.update_require_approval_course(
            enrollment_required_email_suffix="blabla.com")
        user = factories.UserFactory(email="abc@blabla.com")

        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_ENROLLMENT_SENT_TEXT)
        self.assertParticipationStatusCallCount([0, 0, 0, 1])
        self.assertEqual(len(mail.outbox), 1)

    def test_course_require_email_suffix_passed_without_at_pattern2(self):
Dong Zhuang's avatar
Dong Zhuang committed
        # without @ in suffix config
        self.update_require_approval_course(
            enrollment_required_email_suffix="blabla.com")
        user = factories.UserFactory(email="abc@edu.blabla.com")

        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_ENROLLMENT_SENT_TEXT)
        self.assertParticipationStatusCallCount([0, 0, 0, 1])
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(len(mail.outbox), 1)
Dong Zhuang's avatar
Dong Zhuang committed

    def test_course_require_email_suffix_failed(self):
Dong Zhuang's avatar
Dong Zhuang committed
        required_suffix = "blabla.com"
        self.update_require_approval_course(
            enrollment_required_email_suffix=required_suffix)
        user = factories.UserFactory(email="abc@blabla.com.hk")

        with self.temporarily_switch_to_user(user):
            resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertRedirects(
            resp, self.course_page_url, fetch_redirect_response=False)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(
Dong Zhuang's avatar
Dong Zhuang committed
            MESSAGE_EMAIL_SUFFIX_REQUIRED_PATTERN % required_suffix)
        self.assertParticipationStatusCallCount([0, 0, 0, 0])
        self.assertEqual(len(mail.outbox), 0)
Dong Zhuang's avatar
Dong Zhuang committed

Dong Zhuang's avatar
Dong Zhuang committed
    def test_integrity_error(self):
        with mock.patch(
                "course.enrollment.handle_enrollment_request"
        ) as mock_handle_enrollment_request:
            from django.db import IntegrityError
            mock_handle_enrollment_request.side_effect = IntegrityError
            user = factories.UserFactory()
            with self.temporarily_switch_to_user(user):
                resp = self.client.post(self.enroll_request_url)
Dong Zhuang's avatar
Dong Zhuang committed
            self.assertRedirects(
                resp, self.course_page_url, fetch_redirect_response=False)
            self.assertAddMessageCallCount(1)
            self.assertAddMessageCalledWith(MESSAGE_PARTICIPATION_ALREADY_EXIST_TEXT)
Dong Zhuang's avatar
Dong Zhuang committed

            self.assertParticipationStatusCallCount([0, 0, 0, 0])
Dong Zhuang's avatar
Dong Zhuang committed


class HandleEnrollmentRequestTest(SingleCourseTestMixin,
                                  EnrollmentTestMixin, TestCase):
    # test enrollment.handle_enrollment_request
    def setUp(self):
        super().setUp()
Dong Zhuang's avatar
Dong Zhuang committed
        fake_send_enrollment_decision = mock.patch(
            "course.enrollment.send_enrollment_decision")
        self.mock_send_enrollment_decision = fake_send_enrollment_decision.start()
        self.addCleanup(fake_send_enrollment_decision.stop)

    def test_approve_new(self):
        user = factories.UserFactory()
        status = p_status.active
        roles = [
            factories.ParticipationRoleFactory(course=self.course, identifier="1"),
            factories.ParticipationRoleFactory(course=self.course, identifier="2")]
        request = mock.MagicMock()

        participation = enrollment.handle_enrollment_request(
            self.course, user, status, roles, request=request)

        self.assertEqual(participation.user, user)
        self.assertEqual(participation.status, status)
        self.assertSetEqual(
            set(participation.roles.all()), set(roles))
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(self.mock_send_enrollment_decision.call_count, 1)
        self.mock_send_enrollment_decision.assert_called_with(
            participation, True, request)

    def test_approve_new_none_roles(self):
        user = factories.UserFactory()
        status = p_status.active
        roles = None
        request = mock.MagicMock()

        participation = enrollment.handle_enrollment_request(
            self.course, user, status, roles, request=request)

        self.assertEqual(participation.user, user)
        self.assertEqual(participation.status, status)
        self.assertSetEqual(set(participation.roles.all()), set())
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(self.mock_send_enrollment_decision.call_count, 1)
        self.mock_send_enrollment_decision.assert_called_with(
            participation, True, request)

    def test_deny_new(self):
        user = factories.UserFactory()
        status = p_status.denied
        roles = [
            factories.ParticipationRoleFactory(course=self.course, identifier="3"),
            factories.ParticipationRoleFactory(course=self.course, identifier="4")]
        request = mock.MagicMock()

        participation = enrollment.handle_enrollment_request(
            self.course, user, status, roles, request=request)

        self.assertEqual(participation.user, user)
        self.assertEqual(participation.status, status)
        self.assertSetEqual(set(participation.roles.all()), set(roles))
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(self.mock_send_enrollment_decision.call_count, 1)
        self.mock_send_enrollment_decision.assert_called_with(
            participation, False, request)

    def test_approve_requested(self):
        user = factories.UserFactory()
        request_participation = factories.ParticipationFactory(
            course=self.course, user=user, status=p_status.requested,
        )
        status = p_status.active
        roles = [
            factories.ParticipationRoleFactory(course=self.course, identifier="1"),
            factories.ParticipationRoleFactory(course=self.course, identifier="2")]
        request = mock.MagicMock()

        participation = enrollment.handle_enrollment_request(
            self.course, user, status, roles, request=request)

        self.assertEqual(participation.user, user)
        self.assertEqual(participation.status, status)
        self.assertSetEqual(
            set(participation.roles.all()),
            set(request_participation.roles.all()))
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(self.mock_send_enrollment_decision.call_count, 1)
        self.mock_send_enrollment_decision.assert_called_with(
            participation, True, request)

    def test_deny_requested(self):
        user = factories.UserFactory()
        request_participation = factories.ParticipationFactory(
            course=self.course, user=user, status=p_status.requested,
        )
        status = p_status.denied
        roles = [
            factories.ParticipationRoleFactory(course=self.course, identifier="1"),
            factories.ParticipationRoleFactory(course=self.course, identifier="2")]
        request = mock.MagicMock()

        participation = enrollment.handle_enrollment_request(
            self.course, user, status, roles, request=request)

        self.assertEqual(participation.user, user)
        self.assertEqual(participation.status, status)
        self.assertSetEqual(
            set(participation.roles.all()),
            set(request_participation.roles.all()))
Dong Zhuang's avatar
Dong Zhuang committed
        self.assertEqual(self.mock_send_enrollment_decision.call_count, 1)
        self.mock_send_enrollment_decision.assert_called_with(
            participation, False, request)


class SendEnrollmentDecisionTest(SingleCourseTestMixin, TestCase):
    # test enrollment.send_enrollment_decision
    def test_request_none(self):
        participation = factories.ParticipationFactory()
        enrollment.send_enrollment_decision(participation, True, None)
        self.assertEqual(len(mail.outbox), 1)
Dong Zhuang's avatar
Dong Zhuang committed

class EnrollmentTestBaseMixin(MockAddMessageMixing, SingleCourseTestMixin):
Dong Zhuang's avatar
Dong Zhuang committed
    @classmethod
    def setUpTestData(cls):
        super().setUpTestData()
Dong Zhuang's avatar
Dong Zhuang committed
        (cls.non_ptcp_active_user1, cls.non_ptcp_active_user2) = (
            factories.UserFactory.create_batch(
                size=2))
        (cls.non_ptcp_unconfirmed_user1, cls.non_ptcp_unconfirmed_user2) = (
            factories.UserFactory.create_batch(
                size=2, status=u_status.unconfirmed))
Dong Zhuang's avatar
Dong Zhuang committed

Dong Zhuang's avatar
Dong Zhuang committed
    @property
    def enroll_request_url(self):
        return reverse("relate-enroll", args=[self.course.identifier])
Dong Zhuang's avatar
Dong Zhuang committed
    @classmethod
    def get_participation_edit_url(cls, participation_id):
        return reverse("relate-edit_participation",
                       args=[cls.course.identifier, participation_id])
Dong Zhuang's avatar
Dong Zhuang committed

Dong Zhuang's avatar
Dong Zhuang committed
    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
    @property
    def student_role_post_data(self):
        role, _ = (ParticipationRole.objects.get_or_create(
            course=self.course, identifier="student"))
        return [str(role.pk)]


class EnrollmentDecisionTestMixin(LocmemBackendTestsMixin, EnrollmentTestBaseMixin):
    courses_attributes_extra_list = [{"enrollment_approval_required": True}]

    @classmethod
    def setUpTestData(cls):
        super().setUpTestData()
        cls.my_participation = cls.create_participation(
Dong Zhuang's avatar
Dong Zhuang committed
            cls.course, cls.non_ptcp_active_user1,
            status=p_status.requested)
        cls.my_participation_edit_url = (
            cls.get_participation_edit_url(cls.my_participation.pk))

    def get_edit_participation_form_data(self, op, **post_form_kwargs):
        time_factor = [str(self.my_participation.time_factor)]
        roles = [str(r.pk) for r in self.my_participation.roles.all()]
        notes = [str(self.my_participation.notes)]

        form_data = {"time_factor": time_factor,
                     "roles": roles, "notes": notes,
                     op: ""}
        form_data.update(post_form_kwargs)

        return form_data


class EnrollmentDecisionTest(EnrollmentDecisionTestMixin, TestCase):
    courses_attributes_extra_list = [{"enrollment_approval_required": True}]

    @property
    def add_new_url(self):
        return self.get_participation_edit_url(-1)

    def test_edit_participation_view_enroll_decision_approve(self):
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.requested),
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(self.instructor_participation.user):
            resp = self.client.post(self.my_participation_edit_url,
                               self.get_edit_participation_form_data("approve"))
Dong Zhuang's avatar
Dong Zhuang committed

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.requested),
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith(MESSAGE_SUCCESSFULLY_ENROLLED_TEXT)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.requested),
            0)

    def test_edit_participation_view_enroll_decision_approve_no_permission1(self):
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(self.student_participation.user):
            resp = self.client.post(self.my_participation_edit_url,
                               self.get_edit_participation_form_data("approve"))
Dong Zhuang's avatar
Dong Zhuang committed

        self.assertEqual(resp.status_code, 403)
        self.assertEqual(len(mail.outbox), 0)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.requested),
            1)

    def test_edit_participation_view_enroll_decision_approve_no_permission2(self):
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(self.non_ptcp_active_user1):
            resp = self.client.post(self.my_participation_edit_url,
                               self.get_edit_participation_form_data("approve"))
Dong Zhuang's avatar
Dong Zhuang committed

        self.assertEqual(resp.status_code, 403)
        self.assertEqual(len(mail.outbox), 0)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.requested),
    def test_edit_participation_view_course_not_match(self):
        other_course_participation = factories.ParticipationFactory(
            course=factories.CourseFactory(identifier="another-course")
        )
        url = self.get_participation_edit_url(other_course_participation.pk)
        with self.temporarily_switch_to_user(self.instructor_participation.user):
            resp = self.client.get(url)
            self.assertEqual(resp.status_code, 400)

            resp = self.client.post(url, data={})
            self.assertEqual(resp.status_code, 400)

    def test_edit_participation_update_individual_permission(self):
        url = self.get_participation_edit_url(self.student_participation.pk)
        with self.temporarily_switch_to_user(self.instructor_participation.user):
            resp = self.client.post(
                url,
                self.get_edit_participation_form_data(
                    "submit", individual_permissions=[
                        "view_participant_masked_profile",
                        "view_hidden_course_page",
                    ]))
            self.assertEqual(resp.status_code, 200)
            self.assertFormErrorLoose(resp, None)
            self.student_participation.refresh_from_db()
            from course.constants import participation_permission as pperm
            self.assertTrue(
                self.student_participation.has_permission(
                    pperm.view_participant_masked_profile)
            )
            self.assertTrue(
                self.student_participation.has_permission(
                    pperm.view_hidden_course_page)
            )
            self.assertFalse(
                self.student_participation.has_permission(
                    pperm.edit_course)
            )

    def test_edit_participation_view_enroll_decision_deny(self):
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(self.instructor_participation.user):
            resp = self.client.post(
                self.my_participation_edit_url,
                self.get_edit_participation_form_data("deny"))
Dong Zhuang's avatar
Dong Zhuang committed

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.requested),
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith([MESSAGE_ENROLLMENT_DENIED_TEXT])
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.requested),
            0)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.denied),
    def test_edit_participation_view_unknown_post_op(self):
        post_data = self.get_edit_participation_form_data("approve").copy()
        del post_data["approve"]

        # add an unknown post operation
        post_data["unknown"] = ""

        with self.temporarily_switch_to_user(self.instructor_participation.user):
            resp = self.client.post(
                self.my_participation_edit_url, data=post_data)

        self.assertEqual(resp.status_code, 200)
        self.assertFormErrorLoose(resp, None)
        self.assertEqual(
            self.get_participation_count_by_status(p_status.requested),
            1)
        self.assertAddMessageCallCount(0)
        self.assertEqual(len(mail.outbox), 0)

    def test_edit_participation_view_enroll_decision_drop(self):
Dong Zhuang's avatar
Dong Zhuang committed
        self.create_participation(self.course, self.non_ptcp_unconfirmed_user1,
                                  status=p_status.active)
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(self.instructor_participation.user):
            resp = self.client.post(self.my_participation_edit_url,
                               self.get_edit_participation_form_data("drop"))
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.dropped),
        self.assertAddMessageCalledWith([MESSAGE_ENROLLMENT_DROPPED_TEXT])
        self.assertEqual(len(mail.outbox), 0)

    def test_edit_participation_view_add_new_unconfirmed_user(self):
        self.client.force_login(self.instructor_participation.user)
        resp = self.client.get(self.add_new_url)
        self.assertTrue(resp.status_code, 200)

Dong Zhuang's avatar
Dong Zhuang committed
        if self.non_ptcp_unconfirmed_user1.status != u_status.unconfirmed:
            self.non_ptcp_unconfirmed_user1.status = u_status.unconfirmed
            self.non_ptcp_unconfirmed_user1.save()

        expected_active_user_count = (
            get_user_model()
Dong Zhuang's avatar
Dong Zhuang committed
            .objects.filter(status=u_status.unconfirmed).count())

        expected_active_participation_count = (
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.active))
Dong Zhuang's avatar
Dong Zhuang committed
        form_data = {"user": [str(self.non_ptcp_unconfirmed_user1.pk)],
                     "time_factor": 1,
                     "roles": self.student_role_post_data, "notes": [""],
                     "add_new": True
                     }
        add_post_data = {"submit": [""]}
        add_post_data.update(form_data)
        resp = self.client.post(self.add_new_url, add_post_data, follow=True)
        self.assertFormError(resp.context["form"], "user",
                             VALIDATION_ERROR_USER_NOT_CONFIRMED)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.active),
            expected_active_participation_count)

        self.assertEqual(
            get_user_model()
Dong Zhuang's avatar
Dong Zhuang committed
            .objects.filter(status=u_status.unconfirmed).count(),
            expected_active_user_count)
        self.assertAddMessageCallCount(0)
        self.assertEqual(len(mail.outbox), 0)

    def test_edit_participation_view_add_new_active_user(self):
        self.client.force_login(self.instructor_participation.user)
        resp = self.client.get(self.add_new_url)
        self.assertTrue(resp.status_code, 200)

Dong Zhuang's avatar
Dong Zhuang committed
        if self.non_ptcp_unconfirmed_user2.status != u_status.active:
            self.non_ptcp_unconfirmed_user2.status = u_status.active
            self.non_ptcp_unconfirmed_user2.save()

        expected_active_user_count = (
            get_user_model()
Dong Zhuang's avatar
Dong Zhuang committed
            .objects.filter(status=u_status.unconfirmed).count()
        )

        expected_active_participation_count = (
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.active) + 1
Dong Zhuang's avatar
Dong Zhuang committed
        form_data = {"user": [str(self.non_ptcp_unconfirmed_user2.pk)],
                     "time_factor": 1,
                     "roles": self.student_role_post_data, "notes": [""],
                     "add_new": True
                     }
        add_post_data = {"submit": [""]}
        add_post_data.update(form_data)
        resp = self.client.post(self.add_new_url, add_post_data, follow=True)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.active),
            expected_active_participation_count)

        self.assertEqual(
            get_user_model()
Dong Zhuang's avatar
Dong Zhuang committed
            .objects.filter(status=u_status.unconfirmed).count(),
            expected_active_user_count)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith([MESSAGE_PARTICIPATION_CHANGE_SAVED_TEXT])
        self.assertEqual(len(mail.outbox), 0)

    def test_edit_participation_view_add_new_invalid_choice(self):
        form_data = {"user": [str(self.student_participation.user.pk)],
                     "time_factor": 0.5,
                     "roles": self.student_role_post_data, "notes": [""],
                     "add_new": True
                     }
        add_post_data = {"submit": [""]}
        add_post_data.update(form_data)
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(self.instructor_participation.user):
            resp = self.client.post(self.add_new_url, add_post_data, follow=True)
Dong Zhuang's avatar
Dong Zhuang committed

        from django.forms.models import ModelChoiceField
        self.assertFormError(
            resp.context["form"], "user",
            ModelChoiceField.default_error_messages["invalid_choice"])

    def test_edit_participation_view_enroll_decision_deny_no_permission1(self):
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(self.student_participation.user):
            resp = self.client.post(
                self.my_participation_edit_url,
                self.get_edit_participation_form_data("deny"))
Dong Zhuang's avatar
Dong Zhuang committed

        self.assertEqual(resp.status_code, 403)
        self.assertEqual(len(mail.outbox), 0)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.requested),
            1)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.denied),
            0)

    def test_edit_participation_view_enroll_decision_deny_no_permission2(self):
Dong Zhuang's avatar
Dong Zhuang committed
        with self.temporarily_switch_to_user(self.non_ptcp_active_user1):
            resp = self.client.post(
                self.my_participation_edit_url,
                self.get_edit_participation_form_data("deny"))
Dong Zhuang's avatar
Dong Zhuang committed

        self.assertEqual(resp.status_code, 403)
        self.assertEqual(len(mail.outbox), 0)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.requested),
            1)
        self.assertEqual(
Dong Zhuang's avatar
Dong Zhuang committed
            self.get_participation_count_by_status(p_status.denied),
    def test_edit_participation_view_save_integrity_error(self):
        with mock.patch(
                "course.enrollment.Participation.save"
        ) as mock_participation_save, mock.patch(
            "course.enrollment.EditParticipationForm.save"
        ) as mock_form_save:
            from django.db import IntegrityError
            mock_participation_save.side_effect = IntegrityError("my_error")
            mock_form_save.side_effect = IntegrityError("my_error")

            with self.temporarily_switch_to_user(
                    self.instructor_participation.user):
                resp = self.client.post(
                    self.my_participation_edit_url,
                    self.get_edit_participation_form_data("deny"))

            self.assertEqual(resp.status_code, 200)
            self.assertEqual(
                self.get_participation_count_by_status(p_status.requested),
                1)
            expected_error_msg = (
                "A data integrity issue was detected when saving "