Skip to content
test_exam.py 43.7 KiB
Newer Older
Dong Zhuang's avatar
Dong Zhuang committed
# -*- coding: utf-8 -*-

from __future__ import division

__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.
"""

Dong Zhuang's avatar
Dong Zhuang committed
import datetime
import pytz

import unittest
from django.test import TestCase, override_settings
Dong Zhuang's avatar
Dong Zhuang committed
from django.urls import reverse
from django.utils.timezone import now, timedelta

from course.models import ExamTicket, FlowSession
Dong Zhuang's avatar
Dong Zhuang committed
from course import constants, exam

from tests.constants import (
    DATE_TIME_PICKER_TIME_FORMAT)

from tests.base_test_mixins import (
    SingleCourseTestMixin, MockAddMessageMixing, SingleCoursePageTestMixin)
from tests.utils import mock, reload_urlconf
Dong Zhuang's avatar
Dong Zhuang committed
from tests import factories


class GenTicketCodeTest(unittest.TestCase):
    """test exam.gen_ticket_code"""

    def test_unique(self):
        code = set()
        for i in range(10):
            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=pytz.UTC)

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

    @classmethod
    def setUpTestData(cls):  # noqa
        super(ExamTestMixin, cls).setUpTestData()
        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(ExamTestMixin, self).setUp()
        self.c.force_login(self.instructor_participation.user)

    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.c.get(self.get_issue_exam_ticket_url())

    def post_issue_exam_ticket_view(self, data):
        return self.c.post(self.get_issue_exam_ticket_url(), data)

    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):
        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):
        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):
        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):
        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.c.get(self.get_batch_issue_exam_ticket_url())

    def post_batch_issue_exam_ticket_view(self, data):
        return self.c.post(self.get_batch_issue_exam_ticket_url(), data)

    def get_post_data(self, **kwargs):
        data = super(BatchIssueExamTicketsTest, self).get_post_data()
        del data["user"]
        data["format"] = "{{ tickets }}{{checkin_uri}}"
        data.update(kwargs)
        return data

    def test_not_authenticated(self):
        with self.temporarily_switch_to_user(None):
            resp = self.get_batch_issue_exam_ticket_view()
            self.assertEqual(resp.status_code, 403)
Loading
Loading full blame...