jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_list_email_content_error(self, task_history_request):
    """ Test handling of error retrieving email """
    invalid_task = FakeContentTask(0, 0, 0, 'test')
    invalid_task.make_invalid_input()
    task_history_request.return_value = [invalid_task]
    url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {})
    self.assertEqual(response.status_code, 200)

    self.assertTrue(task_history_request.called)
    returned_email_info = json.loads(response.content)['emails']
    self.assertEqual(len(returned_email_info), 1)
    returned_info = returned_email_info[0]
    for info in ['created', 'sent_to', 'email', 'number_sent', 'requester']:
        self.assertEqual(returned_info[info], None)
//  [python]
def test_list_email_content_error(self, task_history_request):
    """ Test handling of error retrieving email """
    invalid_task = FakeContentTask(0, 0, 0, 'test')
    invalid_task.make_invalid_input()
    task_history_request.return_value = [invalid_task]
    url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {})
    self.assertEqual(response.status_code, 200)

    self.assertTrue(task_history_request.called)
    returned_email_info = json.loads(response.content)['emails']
    self.assertEqual(len(returned_email_info), 1)
    returned_info = returned_email_info[0]
    for info in ['created', 'sent_to', 'email', 'number_sent', 'requester']:
        self.assertEqual(returned_info[info], None)
//  [python]
def test_modify_access_revoke_self(self):
    """
    Test that an instructor cannot remove instructor privelages from themself.
    """
    url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'unique_student_identifier': self.instructor.email,
        'rolename': 'instructor',
        'action': 'revoke',
    })
    self.assertEqual(response.status_code, 200)
    # check response content
    expected = {
        'unique_student_identifier': self.instructor.username,
        'rolename': 'instructor',
        'action': 'revoke',
        'removingSelfAsInstructor': True,
    }
    res_json = json.loads(response.content)
    self.assertEqual(res_json, expected)
//  [python]
def test_modify_access_revoke_self(self):
    """
    Test that an instructor cannot remove instructor privelages from themself.
    """
    url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'unique_student_identifier': self.instructor.email,
        'rolename': 'instructor',
        'action': 'revoke',
    })
    self.assertEqual(response.status_code, 200)
    # check response content
    expected = {
        'unique_student_identifier': self.instructor.username,
        'rolename': 'instructor',
        'action': 'revoke',
        'removingSelfAsInstructor': True,
    }
    res_json = json.loads(response.content)
    self.assertEqual(res_json, expected)
//  [python]
def test_modify_access_with_fake_user(self):
    url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'unique_student_identifier': 'GandalfTheGrey',
        'rolename': 'staff',
        'action': 'revoke',
    })
    self.assertEqual(response.status_code, 200)
    expected = {
        'unique_student_identifier': 'GandalfTheGrey',
        'userDoesNotExist': True,
    }
    res_json = json.loads(response.content)
    self.assertEqual(res_json, expected)
//  [python]
def test_modify_access_with_fake_user(self):
    url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'unique_student_identifier': 'GandalfTheGrey',
        'rolename': 'staff',
        'action': 'revoke',
    })
    self.assertEqual(response.status_code, 200)
    expected = {
        'unique_student_identifier': 'GandalfTheGrey',
        'userDoesNotExist': True,
    }
    res_json = json.loads(response.content)
    self.assertEqual(res_json, expected)
//  [python]
def test_modify_access_revoke_not_allowed(self):
    """ Test revoking access that a user does not have. """
    url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'unique_student_identifier': self.other_staff.email,
        'rolename': 'instructor',
        'action': 'revoke',
    })
    self.assertEqual(response.status_code, 200)
//  [python]
def test_modify_access_revoke_not_allowed(self):
    """ Test revoking access that a user does not have. """
    url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'unique_student_identifier': self.other_staff.email,
        'rolename': 'instructor',
        'action': 'revoke',
    })
    self.assertEqual(response.status_code, 200)
//  [python]
def test_rescore_entrance_exam_all_student(self):
    """ Test rescoring for all students. """
    url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
    response = self.client.post(url, {
        'all_students': True,
    })
    self.assertEqual(response.status_code, 200)
//  [python]
def test_rescore_entrance_exam_all_student(self):
    """ Test rescoring for all students. """
    url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
    response = self.client.get(url, {
        'all_students': True,
    })
    self.assertEqual(response.status_code, 200)
//  [python]
def test_modify_access_with_inactive_user(self):
    self.other_user.is_active = False
    self.other_user.save()  # pylint: disable=no-member
    url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'unique_student_identifier': self.other_user.username,
        'rolename': 'beta',
        'action': 'allow',
    })
    self.assertEqual(response.status_code, 200)
    expected = {
        'unique_student_identifier': self.other_user.username,
        'inactiveUser': True,
    }
    res_json = json.loads(response.content)
    self.assertEqual(res_json, expected)
//  [python]
def test_modify_access_with_inactive_user(self):
    self.other_user.is_active = False
    self.other_user.save()  # pylint: disable=no-member
    url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'unique_student_identifier': self.other_user.username,
        'rolename': 'beta',
        'action': 'allow',
    })
    self.assertEqual(response.status_code, 200)
    expected = {
        'unique_student_identifier': self.other_user.username,
        'inactiveUser': True,
    }
    res_json = json.loads(response.content)
    self.assertEqual(res_json, expected)
//  [python]
def test_rescore_entrance_exam_all_student_and_single(self):
    """ Test re-scoring with both all students and single student parameters. """
    url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
    response = self.client.post(url, {
        'unique_student_identifier': self.student.email,
        'all_students': True,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_rescore_entrance_exam_all_student_and_single(self):
    """ Test re-scoring with both all students and single student parameters. """
    url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
    response = self.client.get(url, {
        'unique_student_identifier': self.student.email,
        'all_students': True,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_rescore_entrance_exam_with_invalid_exam(self):
    """ Test course has entrance exam id set while re-scoring. """
    url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
    response = self.client.post(url, {
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_rescore_entrance_exam_with_invalid_exam(self):
    """ Test course has entrance exam id set while re-scoring. """
    url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
    response = self.client.get(url, {
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_rescore_problem_single(self, act):
    """ Test rescoring of a single student. """
    url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'problem_to_reset': self.problem_urlname,
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 200)
    self.assertTrue(act.called)
//  [python]
def test_rescore_problem_single(self, act):
    """ Test rescoring of a single student. """
    url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'problem_to_reset': self.problem_urlname,
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 200)
    self.assertTrue(act.called)
//  [python]
def test_rescore_entrance_exam_single_student(self, act):
    """ Test re-scoring of entrance exam for single student. """
    url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
    response = self.client.post(url, {
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 200)
    self.assertTrue(act.called)
//  [python]
def test_rescore_entrance_exam_single_student(self, act):
    """ Test re-scoring of entrance exam for single student. """
    url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
    response = self.client.get(url, {
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 200)
    self.assertTrue(act.called)
//  [python]
def test_rescore_problem_all(self, act):
    """ Test rescoring for all students. """
    url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'problem_to_reset': self.problem_urlname,
        'all_students': True,
    })
    self.assertEqual(response.status_code, 200)
    self.assertTrue(act.called)
//  [python]
def test_rescore_problem_all(self, act):
    """ Test rescoring for all students. """
    url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'problem_to_reset': self.problem_urlname,
        'all_students': True,
    })
    self.assertEqual(response.status_code, 200)
    self.assertTrue(act.called)
//  [python]
def test_reset_entrance_exam_all_student_attempts(self, act):
    """ Test reset all student attempts for entrance exam. """
    url = reverse('reset_student_attempts_for_entrance_exam',
                  kwargs={'course_id': unicode(self.course.id)})
    response = self.client.post(url, {
        'all_students': True,
    })
    self.assertEqual(response.status_code, 200)
    self.assertTrue(act.called)
//  [python]
def test_reset_entrance_exam_all_student_attempts(self, act):
    """ Test reset all student attempts for entrance exam. """
    url = reverse('reset_student_attempts_for_entrance_exam',
                  kwargs={'course_id': unicode(self.course.id)})
    response = self.client.get(url, {
        'all_students': True,
    })
    self.assertEqual(response.status_code, 200)
    self.assertTrue(act.called)
//  [python]
def test_reset_date(self):
    self.test_change_due_date()
    url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'student': self.user1.username,
        'url': self.week1.location.to_deprecated_string(),
    })
    self.assertEqual(response.status_code, 200, response.content)
    self.assertEqual(
        None,
        get_extended_due(self.course, self.week1, self.user1)
    )
//  [python]
def test_reset_date(self):
    self.test_change_due_date()
    url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'student': self.user1.username,
        'url': self.week1.location.to_deprecated_string(),
    })
    self.assertEqual(response.status_code, 200, response.content)
    self.assertEqual(
        None,
        get_extended_due(self.course, self.week1, self.user1)
    )
//  [python]
def test_rescore_problem_single_from_uname(self, act):
    """ Test rescoring of a single student. """
    url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'problem_to_reset': self.problem_urlname,
        'unique_student_identifier': self.student.username,
    })
    self.assertEqual(response.status_code, 200)
    self.assertTrue(act.called)
//  [python]
def test_rescore_problem_single_from_uname(self, act):
    """ Test rescoring of a single student. """
    url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'problem_to_reset': self.problem_urlname,
        'unique_student_identifier': self.student.username,
    })
    self.assertEqual(response.status_code, 200)
    self.assertTrue(act.called)
//  [python]
def test_reset_student_attempts_all(self, act):
    """ Test reset all student attempts. """
    url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'problem_to_reset': self.problem_urlname,
        'all_students': True,
    })
    self.assertEqual(response.status_code, 200)
    self.assertTrue(act.called)
//  [python]
def test_reset_student_attempts_all(self, act):
    """ Test reset all student attempts. """
    url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'problem_to_reset': self.problem_urlname,
        'all_students': True,
    })
    self.assertEqual(response.status_code, 200)
    self.assertTrue(act.called)
//  [python]
def test_reset_entrance_exam_student_attempts_deletall(self):
    """ Make sure no one can delete all students state on entrance exam. """
    url = reverse('reset_student_attempts_for_entrance_exam',
                  kwargs={'course_id': unicode(self.course.id)})
    response = self.client.post(url, {
        'all_students': True,
        'delete_module': True,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_reset_entrance_exam_student_attempts_deletall(self):
    """ Make sure no one can delete all students state on entrance exam. """
    url = reverse('reset_student_attempts_for_entrance_exam',
                  kwargs={'course_id': unicode(self.course.id)})
    response = self.client.get(url, {
        'all_students': True,
        'delete_module': True,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_reset_student_attempts_deletall(self):
    """ Make sure no one can delete all students state on a problem. """
    url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'problem_to_reset': self.problem_urlname,
        'all_students': True,
        'delete_module': True,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_reset_student_attempts_deletall(self):
    """ Make sure no one can delete all students state on a problem. """
    url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'problem_to_reset': self.problem_urlname,
        'all_students': True,
        'delete_module': True,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_reset_extension_to_deleted_date(self):
    """
    Test that we can delete a due date extension after deleting the normal
    due date, without causing an error.
    """

    url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'student': self.user1.username,
        'url': self.week1.location.to_deprecated_string(),
        'due_datetime': '12/30/2013 00:00'
    })
    self.assertEqual(response.status_code, 200, response.content)
    self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=utc),
                     get_extended_due(self.course, self.week1, self.user1))

    self.week1.due = None
    self.week1 = self.store.update_item(self.week1, self.user1.id)
    # Now, week1's normal due date is deleted but the extension still exists.
    url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'student': self.user1.username,
        'url': self.week1.location.to_deprecated_string(),
    })
    self.assertEqual(response.status_code, 200, response.content)
    self.assertEqual(
        None,
        get_extended_due(self.course, self.week1, self.user1)
    )
//  [python]
def test_reset_extension_to_deleted_date(self):
    """
    Test that we can delete a due date extension after deleting the normal
    due date, without causing an error.
    """

    url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'student': self.user1.username,
        'url': self.week1.location.to_deprecated_string(),
        'due_datetime': '12/30/2013 00:00'
    })
    self.assertEqual(response.status_code, 200, response.content)
    self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=utc),
                     get_extended_due(self.course, self.week1, self.user1))

    self.week1.due = None
    self.week1 = self.store.update_item(self.week1, self.user1.id)
    # Now, week1's normal due date is deleted but the extension still exists.
    url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'student': self.user1.username,
        'url': self.week1.location.to_deprecated_string(),
    })
    self.assertEqual(response.status_code, 200, response.content)
    self.assertEqual(
        None,
        get_extended_due(self.course, self.week1, self.user1)
    )
//  [python]
def test_reset_student_attempts_delete(self):
    """ Test delete single student state. """
    url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'problem_to_reset': self.problem_urlname,
        'unique_student_identifier': self.student.email,
        'delete_module': True,
    })
    self.assertEqual(response.status_code, 200)
    # make sure the module has been deleted
    self.assertEqual(
        StudentModule.objects.filter(
            student=self.module_to_reset.student,
            course_id=self.module_to_reset.course_id,
            # module_id=self.module_to_reset.module_id,
        ).count(),
        0
    )
//  [python]
def test_reset_student_attempts_delete(self):
    """ Test delete single student state. """
    url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'problem_to_reset': self.problem_urlname,
        'unique_student_identifier': self.student.email,
        'delete_module': True,
    })
    self.assertEqual(response.status_code, 200)
    # make sure the module has been deleted
    self.assertEqual(
        StudentModule.objects.filter(
            student=self.module_to_reset.student,
            course_id=self.module_to_reset.course_id,
            # module_id=self.module_to_reset.module_id,
        ).count(),
        0
    )
//  [python]
def test_reset_student_attempts_invalid_entrance_exam(self):
    """ Test reset for invalid entrance exam. """
    url = reverse('reset_student_attempts_for_entrance_exam',
                  kwargs={'course_id': unicode(self.course_with_invalid_ee.id)})
    response = self.client.post(url, {
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_reset_student_attempts_invalid_entrance_exam(self):
    """ Test reset for invalid entrance exam. """
    url = reverse('reset_student_attempts_for_entrance_exam',
                  kwargs={'course_id': unicode(self.course_with_invalid_ee.id)})
    response = self.client.get(url, {
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_reset_nonexistent_extension(self):
    url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'student': self.user1.username,
        'url': self.week1.location.to_deprecated_string(),
    })
    self.assertEqual(response.status_code, 400, response.content)
//  [python]
def test_reset_nonexistent_extension(self):
    url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'student': self.user1.username,
        'url': self.week1.location.to_deprecated_string(),
    })
    self.assertEqual(response.status_code, 400, response.content)
//  [python]
def test_reset_entrance_exam_student_attempts_single(self):
    """ Test reset single student attempts for entrance exam. """
    url = reverse('reset_student_attempts_for_entrance_exam',
                  kwargs={'course_id': unicode(self.course.id)})
    response = self.client.post(url, {
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 200)
    # make sure problem attempts have been reset.
    changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules)
    for changed_module in changed_modules:
        self.assertEqual(
            json.loads(changed_module.state)['attempts'],
            0
        )
//  [python]
def test_reset_entrance_exam_student_attempts_single(self):
    """ Test reset single student attempts for entrance exam. """
    url = reverse('reset_student_attempts_for_entrance_exam',
                  kwargs={'course_id': unicode(self.course.id)})
    response = self.client.get(url, {
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 200)
    # make sure problem attempts have been reset.
    changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules)
    for changed_module in changed_modules:
        self.assertEqual(
            json.loads(changed_module.state)['attempts'],
            0
        )
//  [python]
def test_reset_student_attempts_missingmodule(self):
    """ Test reset for non-existant problem. """
    url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'problem_to_reset': 'robot-not-a-real-module',
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_reset_student_attempts_missingmodule(self):
    """ Test reset for non-existant problem. """
    url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'problem_to_reset': 'robot-not-a-real-module',
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_reset_student_attempts_nonsense(self):
    """ Test failure with both unique_student_identifier and all_students. """
    url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'problem_to_reset': self.problem_urlname,
        'unique_student_identifier': self.student.email,
        'all_students': True,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_reset_student_attempts_nonsense(self):
    """ Test failure with both unique_student_identifier and all_students. """
    url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'problem_to_reset': self.problem_urlname,
        'unique_student_identifier': self.student.email,
        'all_students': True,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_show_unit_extensions(self):
    self.test_change_due_date()
    url = reverse('show_unit_extensions',
                  kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {'url': self.week1.location.to_deprecated_string()})
    self.assertEqual(response.status_code, 200, response.content)
    self.assertEqual(json.loads(response.content), {
        u'data': [{u'Extended Due Date': u'2013-12-30 00:00',
                   u'Full Name': self.user1.profile.name,
                   u'Username': self.user1.username}],
        u'header': [u'Username', u'Full Name', u'Extended Due Date'],
        u'title': u'Users with due date extensions for %s' %
                  self.week1.display_name})
//  [python]
def test_show_unit_extensions(self):
    self.test_change_due_date()
    url = reverse('show_unit_extensions',
                  kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {'url': self.week1.location.to_deprecated_string()})
    self.assertEqual(response.status_code, 200, response.content)
    self.assertEqual(json.loads(response.content), {
        u'data': [{u'Extended Due Date': u'2013-12-30 00:00',
                   u'Full Name': self.user1.profile.name,
                   u'Username': self.user1.username}],
        u'header': [u'Username', u'Full Name', u'Extended Due Date'],
        u'title': u'Users with due date extensions for %s' %
                  self.week1.display_name})
//  [python]
def test_reset_student_attempts_single(self):
    """ Test reset single student attempts. """
    url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {
        'problem_to_reset': self.problem_urlname,
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 200)
    # make sure problem attempts have been reset.
    changed_module = StudentModule.objects.get(pk=self.module_to_reset.pk)
    self.assertEqual(
        json.loads(changed_module.state)['attempts'],
        0
    )
//  [python]
def test_reset_student_attempts_single(self):
    """ Test reset single student attempts. """
    url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {
        'problem_to_reset': self.problem_urlname,
        'unique_student_identifier': self.student.email,
    })
    self.assertEqual(response.status_code, 200)
    # make sure problem attempts have been reset.
    changed_module = StudentModule.objects.get(pk=self.module_to_reset.pk)
    self.assertEqual(
        json.loads(changed_module.state)['attempts'],
        0
    )
//  [python]
def add_objects(db_book_object, db_object, db_session, db_type, add_elements):
    changed = False
    if db_type == 'languages':
        db_filter = db_object.lang_code
    elif db_type == 'custom':
        db_filter = db_object.value
    else:
        db_filter = db_object.name
    for add_element in add_elements:
        # check if an element with that name exists
        db_element = db_session.query(db_object).filter(db_filter == add_element).first()
        # if no element is found add it
        if db_type == 'author':
            new_element = db_object(add_element, helper.get_sorted_author(add_element.replace('|', ',')), "")
        elif db_type == 'series':
            new_element = db_object(add_element, add_element)
        elif db_type == 'custom':
            new_element = db_object(value=add_element)
        elif db_type == 'publisher':
            new_element = db_object(add_element, None)
        else:  # db_type should be tag or language
            new_element = db_object(add_element)
        if db_element is None:
            changed = True
            db_session.add(new_element)
            db_book_object.append(new_element)
        else:
            db_element = create_objects_for_addition(db_element, add_element, db_type)
            # add element to book
            changed = True
            db_book_object.append(db_element)
    return changed
//  [python]
def add_objects(db_book_object, db_object, db_session, db_type, add_elements):
    changed = False
    if db_type == 'languages':
        db_filter = db_object.lang_code
    elif db_type == 'custom':
        db_filter = db_object.value
    else:
        db_filter = db_object.name
    for add_element in add_elements:
        # check if a element with that name exists
        db_element = db_session.query(db_object).filter(db_filter == add_element).first()
        # if no element is found add it
        if db_type == 'author':
            new_element = db_object(add_element, helper.get_sorted_author(add_element.replace('|', ',')), "")
        elif db_type == 'series':
            new_element = db_object(add_element, add_element)
        elif db_type == 'custom':
            new_element = db_object(value=add_element)
        elif db_type == 'publisher':
            new_element = db_object(add_element, None)
        else:  # db_type should be tag or language
            new_element = db_object(add_element)
        if db_element is None:
            changed = True
            db_session.add(new_element)
            db_book_object.append(new_element)
        else:
            db_element = create_objects_for_addition(db_element, add_element, db_type)
            changed = True
            # add element to book
            changed = True
            db_book_object.append(db_element)
    return changed
//  [python]
def test_show_student_extensions(self):
    self.test_change_due_date()
    url = reverse('show_student_extensions',
                  kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {'student': self.user1.username})
    self.assertEqual(response.status_code, 200, response.content)
    self.assertEqual(json.loads(response.content), {
        u'data': [{u'Extended Due Date': u'2013-12-30 00:00',
                   u'Unit': self.week1.display_name}],
        u'header': [u'Unit', u'Extended Due Date'],
        u'title': u'Due date extensions for %s (%s)' % (
            self.user1.profile.name, self.user1.username)})
//  [python]
def test_show_student_extensions(self):
    self.test_change_due_date()
    url = reverse('show_student_extensions',
                  kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {'student': self.user1.username})
    self.assertEqual(response.status_code, 200, response.content)
    self.assertEqual(json.loads(response.content), {
        u'data': [{u'Extended Due Date': u'2013-12-30 00:00',
                   u'Unit': self.week1.display_name}],
        u'header': [u'Unit', u'Extended Due Date'],
        u'title': u'Due date extensions for %s (%s)' % (
            self.user1.profile.name, self.user1.username)})
//  [python]
def create_book_on_upload(modify_date, meta):
    title = meta.title
    authr = meta.author
    sort_authors, input_authors, db_author, renamed_authors = prepare_authors_on_upload(title, authr)

    title_dir = helper.get_valid_filename(title, chars=96)
    author_dir = helper.get_valid_filename(db_author.name, chars=96)

    # combine path and normalize path from Windows systems
    path = os.path.join(author_dir, title_dir).replace('\\', '/')

    # Calibre adds books with utc as timezone
    db_book = db.Books(title, "", sort_authors, datetime.utcnow(), datetime(101, 1, 1),
                       '1', datetime.utcnow(), path, meta.cover, db_author, [], "")

    modify_date |= modify_database_object(input_authors, db_book.authors, db.Authors, calibre_db.session,
                                          'author')

    # Add series_index to book
    modify_date |= edit_book_series_index(meta.series_id, db_book)

    # add languages
    invalid = []
    modify_date |= edit_book_languages(meta.languages, db_book, upload_mode=True, invalid=invalid)
    if invalid:
        for lang in invalid:
            flash(_(u"'%(langname)s' is not a valid language", langname=lang), category="warning")

    # handle tags
    modify_date |= edit_book_tags(meta.tags, db_book)

    # handle publisher
    modify_date |= edit_book_publisher(meta.publisher, db_book)

    # handle series
    modify_date |= edit_book_series(meta.series, db_book)

    # Add file to book
    file_size = os.path.getsize(meta.file_path)
    db_data = db.Data(db_book, meta.extension.upper()[1:], file_size, title_dir)
    db_book.data.append(db_data)
    calibre_db.session.add(db_book)

    # flush content, get db_book.id available
    calibre_db.session.flush()
    return db_book, input_authors, title_dir, renamed_authors
//  [python]
def create_book_on_upload(modif_date, meta):
    title = meta.title
    authr = meta.author
    sort_authors, input_authors, db_author, renamed_authors = prepare_authors_on_upload(title, authr)

    title_dir = helper.get_valid_filename(title, chars=96)
    author_dir = helper.get_valid_filename(db_author.name, chars=96)

    # combine path and normalize path from windows systems
    path = os.path.join(author_dir, title_dir).replace('\\', '/')

    # Calibre adds books with utc as timezone
    db_book = db.Books(title, "", sort_authors, datetime.utcnow(), datetime(101, 1, 1),
                       '1', datetime.utcnow(), path, meta.cover, db_author, [], "")

    modif_date |= modify_database_object(input_authors, db_book.authors, db.Authors, calibre_db.session,
                                         'author')

    # Add series_index to book
    modif_date |= edit_book_series_index(meta.series_id, db_book)

    # add languages
    invalid=[]
    modif_date |= edit_book_languages(meta.languages, db_book, upload=True, invalid=invalid)
    if invalid:
        for l in invalid:
            flash(_(u"'%(langname)s' is not a valid language", langname=l), category="warning")

    # handle tags
    modif_date |= edit_book_tags(meta.tags, db_book)

    # handle publisher
    modif_date |= edit_book_publisher(meta.publisher, db_book)

    # handle series
    modif_date |= edit_book_series(meta.series, db_book)

    # Add file to book
    file_size = os.path.getsize(meta.file_path)
    db_data = db.Data(db_book, meta.extension.upper()[1:], file_size, title_dir)
    db_book.data.append(db_data)
    calibre_db.session.add(db_book)

    # flush content, get db_book.id available
    calibre_db.session.flush()
    return db_book, input_authors, title_dir, renamed_authors
//  [python]
def convert_bookformat(book_id):
    # check to see if we have form fields to work with -  if not send user back
    book_format_from = request.form.get('book_format_from', None)
    book_format_to = request.form.get('book_format_to', None)

    if (book_format_from is None) or (book_format_to is None):
        flash(_(u"Source or destination format for conversion missing"), category="error")
        return redirect(url_for('edit-book.edit_book', book_id=book_id))

    log.info('converting: book id: %s from: %s to: %s', book_id, book_format_from, book_format_to)
    rtn = helper.convert_book_format(book_id, config.config_calibre_dir, book_format_from.upper(),
                                     book_format_to.upper(), current_user.name)

    if rtn is None:
        flash(_(u"Book successfully queued for converting to %(book_format)s",
                book_format=book_format_to),
              category="success")
    else:
        flash(_(u"There was an error converting this book: %(res)s", res=rtn), category="error")
    return redirect(url_for('edit-book.edit_book', book_id=book_id))
//  [python]
def convert_bookformat(book_id):
    # check to see if we have form fields to work with -  if not send user back
    book_format_from = request.form.get('book_format_from', None)
    book_format_to = request.form.get('book_format_to', None)

    if (book_format_from is None) or (book_format_to is None):
        flash(_(u"Source or destination format for conversion missing"), category="error")
        return redirect(url_for('editbook.edit_book', book_id=book_id))

    log.info('converting: book id: %s from: %s to: %s', book_id, book_format_from, book_format_to)
    rtn = helper.convert_book_format(book_id, config.config_calibre_dir, book_format_from.upper(),
                                     book_format_to.upper(), current_user.name)

    if rtn is None:
        flash(_(u"Book successfully queued for converting to %(book_format)s",
                    book_format=book_format_to),
                    category="success")
    else:
        flash(_(u"There was an error converting this book: %(res)s", res=rtn), category="error")
    return redirect(url_for('editbook.edit_book', book_id=book_id))
//  [python]
def delete_whole_book(book_id, book):
    # delete book from Shelfs, Downloads, Read list
    ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).delete()
    ub.session.query(ub.ReadBook).filter(ub.ReadBook.book_id == book_id).delete()
    ub.delete_download(book_id)
    ub.session_commit()

    # check if only this book links to:
    # author, language, series, tags, custom columns
    modify_database_object([u''], book.authors, db.Authors, calibre_db.session, 'author')
    modify_database_object([u''], book.tags, db.Tags, calibre_db.session, 'tags')
    modify_database_object([u''], book.series, db.Series, calibre_db.session, 'series')
    modify_database_object([u''], book.languages, db.Languages, calibre_db.session, 'languages')
    modify_database_object([u''], book.publishers, db.Publishers, calibre_db.session, 'publishers')

    cc = calibre_db.session.query(db.CustomColumns). \
        filter(db.CustomColumns.datatype.notin_(db.cc_exceptions)).all()
    for c in cc:
        cc_string = "custom_column_" + str(c.id)
        if not c.is_multiple:
            if len(getattr(book, cc_string)) > 0:
                if c.datatype == 'bool' or c.datatype == 'integer' or c.datatype == 'float':
                    del_cc = getattr(book, cc_string)[0]
                    getattr(book, cc_string).remove(del_cc)
                    log.debug('remove ' + str(c.id))
                    calibre_db.session.delete(del_cc)
                    calibre_db.session.commit()
                elif c.datatype == 'rating':
                    del_cc = getattr(book, cc_string)[0]
                    getattr(book, cc_string).remove(del_cc)
                    if len(del_cc.books) == 0:
                        log.debug('remove ' + str(c.id))
                        calibre_db.session.delete(del_cc)
                        calibre_db.session.commit()
                else:
                    del_cc = getattr(book, cc_string)[0]
                    getattr(book, cc_string).remove(del_cc)
                    log.debug('remove ' + str(c.id))
                    calibre_db.session.delete(del_cc)
                    calibre_db.session.commit()
        else:
            modify_database_object([u''], getattr(book, cc_string), db.cc_classes[c.id],
                                   calibre_db.session, 'custom')
    calibre_db.session.query(db.Books).filter(db.Books.id == book_id).delete()
//  [python]
def delete_whole_book(book_id, book):
    # delete book from Shelfs, Downloads, Read list
    ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).delete()
    ub.session.query(ub.ReadBook).filter(ub.ReadBook.book_id == book_id).delete()
    ub.delete_download(book_id)
    ub.session_commit()

    # check if only this book links to:
    # author, language, series, tags, custom columns
    modify_database_object([u''], book.authors, db.Authors, calibre_db.session, 'author')
    modify_database_object([u''], book.tags, db.Tags, calibre_db.session, 'tags')
    modify_database_object([u''], book.series, db.Series, calibre_db.session, 'series')
    modify_database_object([u''], book.languages, db.Languages, calibre_db.session, 'languages')
    modify_database_object([u''], book.publishers, db.Publishers, calibre_db.session, 'publishers')

    cc = calibre_db.session.query(db.Custom_Columns). \
        filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()
    for c in cc:
        cc_string = "custom_column_" + str(c.id)
        if not c.is_multiple:
            if len(getattr(book, cc_string)) > 0:
                if c.datatype == 'bool' or c.datatype == 'integer' or c.datatype == 'float':
                    del_cc = getattr(book, cc_string)[0]
                    getattr(book, cc_string).remove(del_cc)
                    log.debug('remove ' + str(c.id))
                    calibre_db.session.delete(del_cc)
                    calibre_db.session.commit()
                elif c.datatype == 'rating':
                    del_cc = getattr(book, cc_string)[0]
                    getattr(book, cc_string).remove(del_cc)
                    if len(del_cc.books) == 0:
                        log.debug('remove ' + str(c.id))
                        calibre_db.session.delete(del_cc)
                        calibre_db.session.commit()
                else:
                    del_cc = getattr(book, cc_string)[0]
                    getattr(book, cc_string).remove(del_cc)
                    log.debug('remove ' + str(c.id))
                    calibre_db.session.delete(del_cc)
                    calibre_db.session.commit()
        else:
            modify_database_object([u''], getattr(book, cc_string), db.cc_classes[c.id],
                                   calibre_db.session, 'custom')
    calibre_db.session.query(db.Books).filter(db.Books.id == book_id).delete()
//  [python]
def delete_book_from_table(book_id, book_format, json_response):
    warning = {}
    if current_user.role_delete_books():
        book = calibre_db.get_book(book_id)
        if book:
            try:
                result, error = helper.delete_book(book, config.config_calibre_dir, book_format=book_format.upper())
                if not result:
                    if json_response:
                        return json.dumps([{"location": url_for("edit-book.edit_book", book_id=book_id),
                                            "type": "danger",
                                            "format": "",
                                            "message": error}])
                    else:
                        flash(error, category="error")
                        return redirect(url_for('edit-book.edit_book', book_id=book_id))
                if error:
                    if json_response:
                        warning = {"location": url_for("edit-book.edit_book", book_id=book_id),
                                   "type": "warning",
                                   "format": "",
                                   "message": error}
                    else:
                        flash(error, category="warning")
                if not book_format:
                    delete_whole_book(book_id, book)
                else:
                    calibre_db.session.query(db.Data).filter(db.Data.book == book.id).\
                        filter(db.Data.format == book_format).delete()
                    if book_format.upper() in ['KEPUB', 'EPUB', 'EPUB3']:
                        kobo_sync_status.remove_synced_book(book.id, True)
                calibre_db.session.commit()
            except Exception as ex:
                log.error_or_exception(ex)
                calibre_db.session.rollback()
                if json_response:
                    return json.dumps([{"location": url_for("edit-book.edit_book", book_id=book_id),
                                        "type": "danger",
                                        "format": "",
                                        "message": ex}])
                else:
                    flash(str(ex), category="error")
                    return redirect(url_for('edit-book.edit_book', book_id=book_id))

        else:
            # book not found
            log.error('Book with id "%s" could not be deleted: not found', book_id)
        return render_delete_book_result(book_format, json_response, warning, book_id)
    message = _("You are missing permissions to delete books")
    if json_response:
        return json.dumps({"location": url_for("edit-book.edit_book", book_id=book_id),
                           "type": "danger",
                           "format": "",
                           "message": message})
    else:
        flash(message, category="error")
        return redirect(url_for('edit-book.edit_book', book_id=book_id))
//  [python]
def delete_book_from_table(book_id, book_format, jsonResponse):
    warning = {}
    if current_user.role_delete_books():
        book = calibre_db.get_book(book_id)
        if book:
            try:
                result, error = helper.delete_book(book, config.config_calibre_dir, book_format=book_format.upper())
                if not result:
                    if jsonResponse:
                        return json.dumps([{"location": url_for("editbook.edit_book", book_id=book_id),
                                           "type": "danger",
                                           "format": "",
                                           "message": error}])
                    else:
                        flash(error, category="error")
                        return redirect(url_for('editbook.edit_book', book_id=book_id))
                if error:
                    if jsonResponse:
                        warning = {"location": url_for("editbook.edit_book", book_id=book_id),
                                                "type": "warning",
                                                "format": "",
                                                "message": error}
                    else:
                        flash(error, category="warning")
                if not book_format:
                    delete_whole_book(book_id, book)
                else:
                    calibre_db.session.query(db.Data).filter(db.Data.book == book.id).\
                        filter(db.Data.format == book_format).delete()
                    if book_format.upper() in ['KEPUB', 'EPUB', 'EPUB3']:
                        kobo_sync_status.remove_synced_book(book.id, True)
                calibre_db.session.commit()
            except Exception as ex:
                log.error_or_exception(ex)
                calibre_db.session.rollback()
                if jsonResponse:
                    return json.dumps([{"location": url_for("editbook.edit_book", book_id=book_id),
                                        "type": "danger",
                                        "format": "",
                                        "message": ex}])
                else:
                    flash(str(ex), category="error")
                    return redirect(url_for('editbook.edit_book', book_id=book_id))

        else:
            # book not found
            log.error('Book with id "%s" could not be deleted: not found', book_id)
        return render_delete_book_result(book_format, jsonResponse, warning, book_id)
    message = _("You are missing permissions to delete books")
    if jsonResponse:
        return json.dumps({"location": url_for("editbook.edit_book", book_id=book_id),
                           "type": "danger",
                           "format": "",
                           "message": message})
    else:
        flash(message, category="error")
        return redirect(url_for('editbook.edit_book', book_id=book_id))