Skip to content
test_exam.py 43.9 KiB
Newer Older
from __future__ import annotations


Dong Zhuang's avatar
Dong Zhuang committed
__copyright__ = "Copyright (C) 2014 Andreas Kloeckner, Zesheng Wang, 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.
"""

import datetime
import unittest
Andreas Klöckner's avatar
Andreas Klöckner committed

Andreas Klöckner's avatar
Andreas Klöckner committed
from django.test import Client, TestCase, override_settings
Dong Zhuang's avatar
Dong Zhuang committed
from django.urls import reverse
from django.utils.timezone import now, timedelta

from course import constants, exam
Andreas Klöckner's avatar
Andreas Klöckner committed
from course.models import ExamTicket, FlowSession
from tests import factories
Dong Zhuang's avatar
Dong Zhuang committed
from tests.base_test_mixins import (
    MockAddMessageMixing,
    SingleCoursePageTestMixin,
    SingleCourseTestMixin,
Andreas Klöckner's avatar
Andreas Klöckner committed
)
from tests.constants import DATE_TIME_PICKER_TIME_FORMAT
from tests.utils import mock, reload_urlconf
Dong Zhuang's avatar
Dong Zhuang committed


Dong Zhuang's avatar
Dong Zhuang committed
class GenTicketCodeTest(unittest.TestCase):
    """test exam.gen_ticket_code"""

    def test_unique(self):
        code = set()
        for _i in range(10):
Dong Zhuang's avatar
Dong Zhuang committed
            code.add(exam.gen_ticket_code())

        self.assertEqual(len(code), 10)


class ExamTestMixin(SingleCourseTestMixin, MockAddMessageMixing):
    force_login_student_for_each_test = False

    default_faked_now = datetime.datetime(2019, 1, 1, tzinfo=UTC)
Dong Zhuang's avatar
Dong Zhuang committed

    default_valid_start_time = default_faked_now
    default_valid_end_time = default_valid_start_time + timedelta(hours=3)

    @classmethod
    def setUpTestData(cls):
        super().setUpTestData()
Dong Zhuang's avatar
Dong Zhuang committed
        cls.add_user_permission(
            cls.instructor_participation.user, "can_issue_exam_tickets",
            model=ExamTicket)
        cls.exam = factories.ExamFactory(course=cls.course)

    def setUp(self):
        super().setUp()
        self.client.force_login(self.instructor_participation.user)
Dong Zhuang's avatar
Dong Zhuang committed

        fake_get_now_or_fake_time = mock.patch(
            "course.views.get_now_or_fake_time")
        self.mock_get_now_or_fake_time = fake_get_now_or_fake_time.start()
        self.mock_get_now_or_fake_time.return_value = now()
        self.addCleanup(fake_get_now_or_fake_time.stop)

Dong Zhuang's avatar
Dong Zhuang committed
    def get_post_data(self, **kwargs):
        data = {
            "user": self.student_participation.user.pk,
            "exam": self.exam.pk,
            "valid_start_time": (
                self.default_valid_start_time.strftime(
                    DATE_TIME_PICKER_TIME_FORMAT)),
            "valid_end_time": (
                self.default_valid_end_time.strftime(
                    DATE_TIME_PICKER_TIME_FORMAT))}
        data.update(kwargs)
        return data


class IssueExamTicketTest(ExamTestMixin, TestCase):
    """test exam.issue_exam_ticket
    """

    def get_issue_exam_ticket_url(self):
        from django.urls import reverse
        return reverse("relate-issue_exam_ticket")

    def get_issue_exam_ticket_view(self):
        return self.client.get(self.get_issue_exam_ticket_url())
Dong Zhuang's avatar
Dong Zhuang committed

    def post_issue_exam_ticket_view(self, data):
        return self.client.post(self.get_issue_exam_ticket_url(), data)
Dong Zhuang's avatar
Dong Zhuang committed

    def test_not_authenticated(self):
        with self.temporarily_switch_to_user(None):
            resp = self.get_issue_exam_ticket_view()
            self.assertEqual(resp.status_code, 403)

            resp = self.post_issue_exam_ticket_view(data={})
            self.assertEqual(resp.status_code, 403)
            self.assertEqual(ExamTicket.objects.count(), 0)

    def test_no_pperm(self):
        with self.temporarily_switch_to_user(self.student_participation.user):
            resp = self.get_issue_exam_ticket_view()
            self.assertEqual(resp.status_code, 403)

            resp = self.post_issue_exam_ticket_view(data={})
            self.assertEqual(resp.status_code, 403)
            self.assertEqual(ExamTicket.objects.count(), 0)

    def test_get_success(self):
        resp = self.get_issue_exam_ticket_view()
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(ExamTicket.objects.count(), 0)

    def test_post_success(self):
        self.mock_get_now_or_fake_time.return_value = self.default_faked_now

Dong Zhuang's avatar
Dong Zhuang committed
        resp = self.post_issue_exam_ticket_view(data=self.get_post_data())
        self.assertFormErrorLoose(resp, None)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(ExamTicket.objects.count(), 1)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith("Ticket issued for", reset=False)
        self.assertAddMessageCalledWith("The ticket code is")

    def test_form_invalid(self):
        self.mock_get_now_or_fake_time.return_value = self.default_faked_now

Dong Zhuang's avatar
Dong Zhuang committed
        with mock.patch("course.exam.IssueTicketForm.is_valid") as mock_is_valid:
            mock_is_valid.return_value = False
            resp = self.post_issue_exam_ticket_view(data=self.get_post_data())
            self.assertFormErrorLoose(resp, None)
            self.assertEqual(resp.status_code, 200)
            self.assertEqual(ExamTicket.objects.count(), 0)

    def test_participation_not_match(self):
        self.mock_get_now_or_fake_time.return_value = self.default_faked_now

Dong Zhuang's avatar
Dong Zhuang committed
        another_exam = factories.ExamFactory(
            course=factories.CourseFactory(identifier="another-course"))
        resp = self.post_issue_exam_ticket_view(
            data=self.get_post_data(exam=another_exam.pk))
        self.assertFormErrorLoose(resp, None)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(ExamTicket.objects.count(), 0)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith("User is not enrolled in course.")

    def test_revoke_revoke_prior_ticket(self):
        self.mock_get_now_or_fake_time.return_value = self.default_faked_now

Dong Zhuang's avatar
Dong Zhuang committed
        prior_ticket = factories.ExamTicketFactory(
            exam=self.exam,
            participation=self.student_participation,
            state=constants.exam_ticket_states.valid)

        resp = self.post_issue_exam_ticket_view(
            data=self.get_post_data(revoke_prior=True))
        self.assertFormErrorLoose(resp, None)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(ExamTicket.objects.count(), 2)
        prior_ticket.refresh_from_db()
        self.assertEqual(prior_ticket.state, constants.exam_ticket_states.revoked)
        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith("Ticket issued for", reset=False)
        self.assertAddMessageCalledWith("The ticket code is")


class BatchIssueExamTicketsTest(ExamTestMixin, TestCase):
    def get_batch_issue_exam_ticket_url(self, course_identifier=None):
        course_identifier = course_identifier or self.get_default_course_identifier()
        return self.get_course_view_url(
            "relate-batch_issue_exam_tickets",
            course_identifier=course_identifier)

    def get_batch_issue_exam_ticket_view(self):
        return self.client.get(self.get_batch_issue_exam_ticket_url())
Loading
Loading full blame...