Skip to content
test_code.py 66.4 KiB
Newer Older
Dong Zhuang's avatar
Dong Zhuang committed
from __future__ import division

__copyright__ = "Copyright (C) 2018 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
import zipfile
Dong Zhuang's avatar
Dong Zhuang committed
import unittest
from unittest import skipIf
from django.test import TestCase, override_settings, RequestFactory
Dong Zhuang's avatar
Dong Zhuang committed
from docker.errors import APIError as DockerAPIError
from socket import error as socket_error, timeout as sock_timeout
import errno

from course.models import FlowSession
Dong Zhuang's avatar
Dong Zhuang committed
from course.page.code import (
    RUNPY_PORT, request_python_run_with_retries, InvalidPingResponse,
    is_nuisance_failure, PythonCodeQuestionWithHumanTextFeedback)
from course.utils import FlowPageContext, CoursePageContext

from course.constants import MAX_EXTRA_CREDIT_FACTOR

from tests.test_pages import QUIZ_FLOW_ID
from tests.test_pages.test_generic import MESSAGE_ANSWER_SAVED_TEXT
Dong Zhuang's avatar
Dong Zhuang committed
from tests.base_test_mixins import (
    SubprocessRunpyContainerMixin, SingleCoursePageTestMixin,
    FallBackStorageMessageTestMixin)
Dong Zhuang's avatar
Dong Zhuang committed
from tests.test_sandbox import (
    SingleCoursePageSandboxTestBaseMixin, PAGE_ERRORS
)
from tests.utils import LocmemBackendTestsMixin, mock, mail

from . import markdowns

NO_CORRECTNESS_INFO_MSG = "No information on correctness of answer."

NOT_ALLOW_MULTIPLE_SUBMISSION_WARNING = (
    "code question does not explicitly "
    "allow multiple submission. Either add "
    "access_rules/add_permssions/change_answer "
    "or add 'single_submission: True' to confirm that you intend "
    "for only a single submission to be allowed. "
    "While you're at it, consider adding "
    "access_rules/add_permssions/see_correctness."
)

MAX_AUTO_FEEDBACK_POINTS_VALICATION_ERROR_MSG_PATTERN = (  # noqa
    "'max_auto_feedback_points' is invalid: expecting "
    "a value within [0, %(max_extra_credit_factor)s], "
    "got %(invalid_value)s."
)

GRADE_CODE_FAILING_MSG = (
    "The grading code failed. Sorry about that."
)

RUNPY_WITH_RETRIES_PATH = "course.page.code.request_python_run_with_retries"

AUTO_FEEDBACK_POINTS_OUT_OF_RANGE_ERROR_MSG_PATTERN = (
    "'correctness' is invalid: expecting "
    "a value within [0, %s] or None, "
    "got %s."
)
class SingleCourseQuizPageCodeQuestionTest(
            SingleCoursePageTestMixin, FallBackStorageMessageTestMixin,
            SubprocessRunpyContainerMixin, TestCase):
    flow_id = QUIZ_FLOW_ID

    @classmethod
    def setUpTestData(cls):  # noqa
        super(SingleCourseQuizPageCodeQuestionTest, cls).setUpTestData()
        cls.c.force_login(cls.student_participation.user)
        cls.start_flow(cls.flow_id)

    def setUp(self):  # noqa
        super(SingleCourseQuizPageCodeQuestionTest, self).setUp()
        # This is needed to ensure student is logged in
        self.c.force_login(self.student_participation.user)

    def test_code_page_correct(self):
        page_id = "addition"
        resp = self.post_answer_by_page_id(
            page_id, {"answer": ['c = b + a\r']})
        self.assertEqual(resp.status_code, 200)
        self.assertResponseMessagesContains(resp, MESSAGE_ANSWER_SAVED_TEXT)
        self.assertEqual(self.end_flow().status_code, 200)
        self.assertSessionScoreEqual(1)

    def test_code_page_wrong(self):
        page_id = "addition"
        resp = self.post_answer_by_page_id(
            page_id, {"answer": ['c = a - b\r']})
        self.assertEqual(resp.status_code, 200)
        self.assertResponseMessagesContains(resp, MESSAGE_ANSWER_SAVED_TEXT)
        self.assertEqual(self.end_flow().status_code, 200)
        self.assertSessionScoreEqual(0)

    def test_code_page_identical_to_reference(self):
        page_id = "addition"
        resp = self.post_answer_by_page_id(
            page_id, {"answer": ['c = a + b\r']})
        self.assertEqual(resp.status_code, 200)
        self.assertResponseMessagesContains(resp, MESSAGE_ANSWER_SAVED_TEXT)
        self.assertResponseContextAnswerFeedbackContainsFeedback(
                resp,
                ("It looks like you submitted code "
                 "that is identical to the reference "
                 "solution. This is not allowed."))
        self.assertEqual(self.end_flow().status_code, 200)
        self.assertSessionScoreEqual(1)

    def test_download_code_submissions_no_answer(self):
        group_page_id = "quiz_tail/addition"
        self.end_flow()

        # no answer
        with self.temporarily_switch_to_user(self.instructor_participation.user):
            resp = self.post_download_all_submissions_by_group_page_id(
                group_page_id=group_page_id, flow_id=self.flow_id)
            self.assertEqual(resp.status_code, 200)
            prefix, zip_file = resp["Content-Disposition"].split('=')
            self.assertEqual(prefix, "attachment; filename")
            self.assertEqual(resp.get('Content-Type'), "application/zip")

            buf = six.BytesIO(resp.content)
            with zipfile.ZipFile(buf, 'r') as zf:
                self.assertIsNone(zf.testzip())
                self.assertEqual(
                    len([f for f in zf.filelist if f.filename.endswith('.py')]), 0)
                for f in zf.filelist:
                    self.assertGreater(f.file_size, 0)

    def test_download_code_submissions_has_answer(self):
        group_page_id = "quiz_tail/addition"

        # create an answer
        page_id = "addition"
        self.post_answer_by_page_id(
            page_id, {"answer": ['c = a - b\r']})
        self.end_flow()
        with self.temporarily_switch_to_user(self.instructor_participation.user):
            resp = self.post_download_all_submissions_by_group_page_id(
                group_page_id=group_page_id, flow_id=self.flow_id)
            self.assertEqual(resp.status_code, 200)
            prefix, zip_file = resp["Content-Disposition"].split('=')
            self.assertEqual(prefix, "attachment; filename")
            self.assertEqual(resp.get('Content-Type'), "application/zip")

            buf = six.BytesIO(resp.content)
            with zipfile.ZipFile(buf, 'r') as zf:
                self.assertIsNone(zf.testzip())
                # todo: make more assertions in terms of file content
                self.assertEqual(
                    len([f for f in zf.filelist if f.filename.endswith('.py')]), 1)
                for f in zf.filelist:
                    self.assertGreater(f.file_size, 0)

    def test_code_page_analytics_no_answer(self):
        # analytics with no answer
        page_id = "addition"
        self.end_flow()
        with self.temporarily_switch_to_user(self.instructor_participation.user):
            resp = self.get_flow_page_analytics(
                flow_id=self.flow_id, group_id="quiz_tail",
                page_id=page_id)
            self.assertEqual(resp.status_code, 200)

    def test_code_page_analytics_has_answer(self):
        # create an answer
        page_id = "addition"
        self.post_answer_by_page_id(
            page_id, {"answer": ['c = a - b\r']})
        self.end_flow()

        # todo: make more assertions in terms of content
        with self.temporarily_switch_to_user(self.instructor_participation.user):
            resp = self.get_flow_page_analytics(
Loading
Loading full blame...