jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def get(image_file, domain, title, singer, album):
    import ast
    import base64
    import json
    import os
    from html import unescape

    import requests

    api = f"http://{domain}:7873/bGVhdmVfcmlnaHRfbm93"

    with open(image_file, "rb") as f:
        im_bytes = f.read()
        f.close()
    im_b64 = base64.b64encode(im_bytes).decode("utf8")

    headers = {"Content-type": "application/json", "Accept": "text/plain"}

    status = try_get_cached(domain, {"title": title, "singer": singer, "album": album})
    status = ast.literal_eval(str(status))

    if status is None:
        print("Cached version not found. Uploading image with song metadata.")
        payload = json.dumps(
            {"image": im_b64, "title": title, "singer": singer, "album": album}
        )
        response = requests.post(api, data=payload, headers=headers)

        data = unescape(response.text)
        print(data)

        data = ast.literal_eval(data)["entry"]
        print(data)

    else:
        data = status

    # data = [{"title": title, "singer": singer, "album": album}, file_name, file_ending]

    cmd = "del " + image_file
    os.system(cmd)

    return data
//  [python]
def assert_update_forum_role_membership(self, current_user, identifier, rolename, action):
    """
    Test update forum role membership.
    Get unique_student_identifier, rolename and action and update forum role.
    """
    url = reverse('update_forum_role_membership', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(
        url,
        {
            'unique_student_identifier': identifier,
            'rolename': rolename,
            'action': action,
        }
    )

    # Status code should be 200.
    self.assertEqual(response.status_code, 200)

    user_roles = current_user.roles.filter(course_id=self.course.id).values_list("name", flat=True)
    if action == 'allow':
        self.assertIn(rolename, user_roles)
    elif action == 'revoke':
        self.assertNotIn(rolename, user_roles)
//  [python]
def assert_update_forum_role_membership(self, current_user, identifier, rolename, action):
    """
    Test update forum role membership.
    Get unique_student_identifier, rolename and action and update forum role.
    """
    url = reverse('update_forum_role_membership', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(
        url,
        {
            'unique_student_identifier': identifier,
            'rolename': rolename,
            'action': action,
        }
    )

    # Status code should be 200.
    self.assertEqual(response.status_code, 200)

    user_roles = current_user.roles.filter(course_id=self.course.id).values_list("name", flat=True)
    if action == 'allow':
        self.assertIn(rolename, user_roles)
    elif action == 'revoke':
        self.assertNotIn(rolename, user_roles)
//  [python]
def get_email_content_response(self, num_emails, task_history_request, with_failures=False):
    """ Calls the list_email_content endpoint and returns the repsonse """
    self.setup_fake_email_info(num_emails, with_failures)
    task_history_request.return_value = self.tasks.values()
    url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})
    with patch('instructor.views.api.CourseEmail.objects.get') as mock_email_info:
        mock_email_info.side_effect = self.get_matching_mock_email
        response = self.client.post(url, {})
    self.assertEqual(response.status_code, 200)
    return response
//  [python]
def get_email_content_response(self, num_emails, task_history_request, with_failures=False):
    """ Calls the list_email_content endpoint and returns the repsonse """
    self.setup_fake_email_info(num_emails, with_failures)
    task_history_request.return_value = self.tasks.values()
    url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})
    with patch('instructor.views.api.CourseEmail.objects.get') as mock_email_info:
        mock_email_info.side_effect = self.get_matching_mock_email
        response = self.client.get(url, {})
    self.assertEqual(response.status_code, 200)
    return response
//  [python]
def register_with_redemption_code(self, user, code):
    """
    enroll user using a registration code
    """
    redeem_url = reverse('shoppingcart.views.register_code_redemption', args=[code], is_dashboard_endpoint=False)
    self.client.login(username=user.username, password='test')
    response = self.client.get(redeem_url)
    self.assertEquals(response.status_code, 200)
    # check button text
    self.assertTrue('Activate Course Enrollment' in response.content)

    response = self.client.post(redeem_url)
    self.assertEquals(response.status_code, 200)
//  [python]
def register_with_redemption_code(self, user, code):
    """
    enroll user using a registration code
    """
    redeem_url = reverse('register_code_redemption', args=[code])
    self.client.login(username=user.username, password='test')
    response = self.client.get(redeem_url)
    self.assertEquals(response.status_code, 200)
    # check button text
    self.assertTrue('Activate Course Enrollment' in response.content)

    response = self.client.post(redeem_url)
    self.assertEquals(response.status_code, 200)
//  [python]
def test_bulk_purchase_detailed_report(self):
    """
    test to generate detailed enrollment report.
    1 Purchase registration codes.
    2 Enroll users via registration code.
    3 Validate generated enrollment report.
    """
    paid_course_reg_item = PaidCourseRegistration.add_to_order(self.cart, self.course.id)
    # update the quantity of the cart item paid_course_reg_item
    resp = self.client.post(
        reverse('shoppingcart.views.update_user_cart', is_dashboard_endpoint=False),
        {'ItemId': paid_course_reg_item.id, 'qty': '4'}
    )
    self.assertEqual(resp.status_code, 200)
    # apply the coupon code to the item in the cart
    resp = self.client.post(
        reverse('shoppingcart.views.use_code', is_dashboard_endpoint=False),
        {'code': self.coupon_code}
    )
    self.assertEqual(resp.status_code, 200)
    self.cart.purchase()

    course_reg_codes = CourseRegistrationCode.objects.filter(order=self.cart)
    self.register_with_redemption_code(self.instructor, course_reg_codes[0].code)

    test_user = UserFactory()
    test_user_cart = Order.get_cart_for_user(test_user)
    PaidCourseRegistration.add_to_order(test_user_cart, self.course.id)
    test_user_cart.purchase()
    InvoiceTransaction.objects.create(
        invoice=self.sale_invoice_1,
        amount=-self.sale_invoice_1.total_amount,
        status='refunded',
        created_by=self.instructor,
        last_modified_by=self.instructor
    )
    course_registration_code = CourseRegistrationCode.objects.create(
        code='abcde',
        course_id=self.course.id.to_deprecated_string(),
        created_by=self.instructor,
        invoice=self.sale_invoice_1,
        invoice_item=self.invoice_item,
        mode_slug='honor'
    )

    test_user1 = UserFactory()
    self.register_with_redemption_code(test_user1, course_registration_code.code)

    CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
    self.client.login(username=self.instructor.username, password='test')

    url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {})
    self.assertIn('The detailed enrollment report is being created.', response.content)
//  [python]
def test_bulk_purchase_detailed_report(self):
    """
    test to generate detailed enrollment report.
    1 Purchase registration codes.
    2 Enroll users via registration code.
    3 Validate generated enrollment report.
    """
    paid_course_reg_item = PaidCourseRegistration.add_to_order(self.cart, self.course.id)
    # update the quantity of the cart item paid_course_reg_item
    resp = self.client.post(reverse('shoppingcart.views.update_user_cart'),
                            {'ItemId': paid_course_reg_item.id, 'qty': '4'})
    self.assertEqual(resp.status_code, 200)
    # apply the coupon code to the item in the cart
    resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': self.coupon_code})
    self.assertEqual(resp.status_code, 200)
    self.cart.purchase()

    course_reg_codes = CourseRegistrationCode.objects.filter(order=self.cart)
    self.register_with_redemption_code(self.instructor, course_reg_codes[0].code)

    test_user = UserFactory()
    test_user_cart = Order.get_cart_for_user(test_user)
    PaidCourseRegistration.add_to_order(test_user_cart, self.course.id)
    test_user_cart.purchase()
    InvoiceTransaction.objects.create(
        invoice=self.sale_invoice_1,
        amount=-self.sale_invoice_1.total_amount,
        status='refunded',
        created_by=self.instructor,
        last_modified_by=self.instructor
    )
    course_registration_code = CourseRegistrationCode.objects.create(
        code='abcde',
        course_id=self.course.id.to_deprecated_string(),
        created_by=self.instructor,
        invoice=self.sale_invoice_1,
        invoice_item=self.invoice_item,
        mode_slug='honor'
    )

    test_user1 = UserFactory()
    self.register_with_redemption_code(test_user1, course_registration_code.code)

    CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
    self.client.login(username=self.instructor.username, password='test')

    url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {})
    self.assertIn('The detailed enrollment report is being created.', response.content)
//  [python]
def test_calculate_report_csv_success(self, report_type, instructor_api_endpoint, task_api_endpoint, extra_instructor_api_kwargs):
    kwargs = {'course_id': unicode(self.course.id)}
    kwargs.update(extra_instructor_api_kwargs)
    url = reverse(instructor_api_endpoint, kwargs=kwargs)
    success_status = "The {report_type} report is being created.".format(report_type=report_type)
    if report_type == 'problem responses':
        with patch(task_api_endpoint):
            response = self.client.post(url, {'problem_location': ''})
        self.assertIn(success_status, response.content)
    else:
        CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
        with patch(task_api_endpoint):
            response = self.client.post(url, {})
        self.assertIn(success_status, response.content)
//  [python]
def test_calculate_report_csv_success(self, report_type, instructor_api_endpoint, task_api_endpoint, extra_instructor_api_kwargs):
    kwargs = {'course_id': unicode(self.course.id)}
    kwargs.update(extra_instructor_api_kwargs)
    url = reverse(instructor_api_endpoint, kwargs=kwargs)
    success_status = "The {report_type} report is being created.".format(report_type=report_type)
    if report_type == 'problem responses':
        with patch(task_api_endpoint):
            response = self.client.get(url, {'problem_location': ''})
        self.assertIn(success_status, response.content)
    else:
        CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
        with patch(task_api_endpoint):
            response = self.client.get(url, {})
        self.assertIn(success_status, response.content)
//  [python]
def test_certificates_features_against_status(self):
    """
    Test certificates with status 'downloadable' should be in the response.
    """
    url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})
    # firstly generating downloadable certificates with 'honor' mode
    certificate_count = 3
    for __ in xrange(certificate_count):
        self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.generating)

    response = self.client.post(url)
    res_json = json.loads(response.content)
    self.assertIn('certificates', res_json)
    self.assertEqual(len(res_json['certificates']), 0)

    # Certificates with status 'downloadable' should be in response.
    self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)
    response = self.client.post(url)
    res_json = json.loads(response.content)
    self.assertIn('certificates', res_json)
    self.assertEqual(len(res_json['certificates']), 1)
//  [python]
def test_certificates_features_against_status(self):
    """
    Test certificates with status 'downloadable' should be in the response.
    """
    url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})
    # firstly generating downloadable certificates with 'honor' mode
    certificate_count = 3
    for __ in xrange(certificate_count):
        self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.generating)

    response = self.client.get(url)
    res_json = json.loads(response.content)
    self.assertIn('certificates', res_json)
    self.assertEqual(len(res_json['certificates']), 0)

    # Certificates with status 'downloadable' should be in response.
    self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)
    response = self.client.get(url)
    res_json = json.loads(response.content)
    self.assertIn('certificates', res_json)
    self.assertEqual(len(res_json['certificates']), 1)
//  [python]
def test_certificates_features_csv(self):
    """
    Test for certificate csv features.
    """
    url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})
    # firstly generating downloadable certificates with 'honor' mode
    certificate_count = 3
    for __ in xrange(certificate_count):
        self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)

    current_date = datetime.date.today().strftime("%B %d, %Y")
    response = self.client.get(url, {'csv': 'true'})
    self.assertEqual(response['Content-Type'], 'text/csv')
    self.assertEqual(response['Content-Disposition'], 'attachment; filename={0}'.format('issued_certificates.csv'))
    self.assertEqual(
        response.content.strip(),
        '"CourseID","Certificate Type","Total Certificates Issued","Date Report Run"\r\n"'
        + str(self.course.id) + '","honor","3","' + current_date + '"'
    )
//  [python]
def test_certificates_features_csv(self):
    """
    Test for certificate csv features.
    """
    url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})
    url += '?csv=true'
    # firstly generating downloadable certificates with 'honor' mode
    certificate_count = 3
    for __ in xrange(certificate_count):
        self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)

    current_date = datetime.date.today().strftime("%B %d, %Y")
    response = self.client.get(url)
    self.assertEqual(response['Content-Type'], 'text/csv')
    self.assertEqual(response['Content-Disposition'], 'attachment; filename={0}'.format('issued_certificates.csv'))
    self.assertEqual(
        response.content.strip(),
        '"CourseID","Certificate Type","Total Certificates Issued","Date Report Run"\r\n"'
        + str(self.course.id) + '","honor","3","' + current_date + '"'
    )
//  [python]
def test_certificates_features_group_by_mode(self):
    """
    Test for certificate csv features against mode. Certificates should be group by 'mode' in reponse.
    """
    url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})
    # firstly generating downloadable certificates with 'honor' mode
    certificate_count = 3
    for __ in xrange(certificate_count):
        self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)

    response = self.client.post(url)
    res_json = json.loads(response.content)
    self.assertIn('certificates', res_json)
    self.assertEqual(len(res_json['certificates']), 1)

    # retrieve the first certificate from the list, there should be 3 certificates for 'honor' mode.
    certificate = res_json['certificates'][0]
    self.assertEqual(certificate.get('total_issued_certificate'), 3)
    self.assertEqual(certificate.get('mode'), 'honor')
    self.assertEqual(certificate.get('course_id'), str(self.course.id))

    # Now generating downloadable certificates with 'verified' mode
    for __ in xrange(certificate_count):
        self.generate_certificate(
            course_id=self.course.id,
            mode='verified',
            status=CertificateStatuses.downloadable
        )

    response = self.client.post(url)
    res_json = json.loads(response.content)
    self.assertIn('certificates', res_json)

    # total certificate count should be 2 for 'verified' mode.
    self.assertEqual(len(res_json['certificates']), 2)

    # retrieve the second certificate from the list
    certificate = res_json['certificates'][1]
    self.assertEqual(certificate.get('total_issued_certificate'), 3)
    self.assertEqual(certificate.get('mode'), 'verified')
//  [python]
def test_certificates_features_group_by_mode(self):
    """
    Test for certificate csv features against mode. Certificates should be group by 'mode' in reponse.
    """
    url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})
    # firstly generating downloadable certificates with 'honor' mode
    certificate_count = 3
    for __ in xrange(certificate_count):
        self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)

    response = self.client.get(url)
    res_json = json.loads(response.content)
    self.assertIn('certificates', res_json)
    self.assertEqual(len(res_json['certificates']), 1)

    # retrieve the first certificate from the list, there should be 3 certificates for 'honor' mode.
    certificate = res_json['certificates'][0]
    self.assertEqual(certificate.get('total_issued_certificate'), 3)
    self.assertEqual(certificate.get('mode'), 'honor')
    self.assertEqual(certificate.get('course_id'), str(self.course.id))

    # Now generating downloadable certificates with 'verified' mode
    for __ in xrange(certificate_count):
        self.generate_certificate(
            course_id=self.course.id,
            mode='verified',
            status=CertificateStatuses.downloadable
        )

    response = self.client.get(url)
    res_json = json.loads(response.content)
    self.assertIn('certificates', res_json)

    # total certificate count should be 2 for 'verified' mode.
    self.assertEqual(len(res_json['certificates']), 2)

    # retrieve the second certificate from the list
    certificate = res_json['certificates'][1]
    self.assertEqual(certificate.get('total_issued_certificate'), 3)
    self.assertEqual(certificate.get('mode'), 'verified')
//  [python]
def test_change_nonexistent_due_date(self):
    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.week3.location.to_deprecated_string(),
        'due_datetime': '12/30/2013 00:00'
    })
    self.assertEqual(response.status_code, 400, response.content)
    self.assertEqual(
        None,
        get_extended_due(self.course, self.week3, self.user1)
    )
//  [python]
def test_change_nonexistent_due_date(self):
    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.week3.location.to_deprecated_string(),
        'due_datetime': '12/30/2013 00:00'
    })
    self.assertEqual(response.status_code, 400, response.content)
    self.assertEqual(
        None,
        get_extended_due(self.course, self.week3, self.user1)
    )
//  [python]
def test_change_to_invalid_due_date(self):
    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': '01/01/2009 00:00'
    })
    self.assertEqual(response.status_code, 400, response.content)
    self.assertEqual(
        None,
        get_extended_due(self.course, self.week1, self.user1)
    )
//  [python]
def test_change_to_invalid_due_date(self):
    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': '01/01/2009 00:00'
    })
    self.assertEqual(response.status_code, 400, response.content)
    self.assertEqual(
        None,
        get_extended_due(self.course, self.week1, self.user1)
    )
//  [python]
def test_coupon_redeem_count_in_ecommerce_section(self):
    """
    Test that checks the redeem count in the instructor_dashboard coupon section
    """
    # add the coupon code for the course
    coupon = Coupon(
        code='test_code', description='test_description', course_id=self.course.id,
        percentage_discount='10', created_by=self.instructor, is_active=True
    )
    coupon.save()

    # Coupon Redeem Count only visible for Financial Admins.
    CourseFinanceAdminRole(self.course.id).add_users(self.instructor)

    PaidCourseRegistration.add_to_order(self.cart, self.course.id)
    # apply the coupon code to the item in the cart
    resp = self.client.post(
        reverse('shoppingcart.views.use_code', is_dashboard_endpoint=False),
        {'code': coupon.code}
    )
    self.assertEqual(resp.status_code, 200)

    # URL for instructor dashboard
    instructor_dashboard = reverse(
        'instructor_dashboard',
        kwargs={'course_id': self.course.id.to_deprecated_string()},
        is_dashboard_endpoint=False
    )
    # visit the instructor dashboard page and
    # check that the coupon redeem count should be 0
    resp = self.client.get(instructor_dashboard)
    self.assertEqual(resp.status_code, 200)
    self.assertIn('Number Redeemed', resp.content)
    self.assertIn('<td>0</td>', resp.content)

    # now make the payment of your cart items
    self.cart.purchase()
    # visit the instructor dashboard page and
    # check that the coupon redeem count should be 1
    resp = self.client.get(instructor_dashboard)
    self.assertEqual(resp.status_code, 200)

    self.assertIn('Number Redeemed', resp.content)
    self.assertIn('<td>1</td>', resp.content)
//  [python]
def test_coupon_redeem_count_in_ecommerce_section(self):
    """
    Test that checks the redeem count in the instructor_dashboard coupon section
    """
    # add the coupon code for the course
    coupon = Coupon(
        code='test_code', description='test_description', course_id=self.course.id,
        percentage_discount='10', created_by=self.instructor, is_active=True
    )
    coupon.save()

    # Coupon Redeem Count only visible for Financial Admins.
    CourseFinanceAdminRole(self.course.id).add_users(self.instructor)

    PaidCourseRegistration.add_to_order(self.cart, self.course.id)
    # apply the coupon code to the item in the cart
    resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': coupon.code})
    self.assertEqual(resp.status_code, 200)

    # URL for instructor dashboard
    instructor_dashboard = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()})
    # visit the instructor dashboard page and
    # check that the coupon redeem count should be 0
    resp = self.client.get(instructor_dashboard)
    self.assertEqual(resp.status_code, 200)
    self.assertIn('Number Redeemed', resp.content)
    self.assertIn('<td>0</td>', resp.content)

    # now make the payment of your cart items
    self.cart.purchase()
    # visit the instructor dashboard page and
    # check that the coupon redeem count should be 1
    resp = self.client.get(instructor_dashboard)
    self.assertEqual(resp.status_code, 200)

    self.assertIn('Number Redeemed', resp.content)
    self.assertIn('<td>1</td>', resp.content)
//  [python]
def test_change_due_date(self):
    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))
//  [python]
def test_change_due_date(self):
    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))
//  [python]
def test_create_registration_code_without_invoice_and_order(self):
    """
    test generate detailed enrollment report,
    used a registration codes which has been created via invoice or bulk
    purchase scenario.
    """
    course_registration_code = CourseRegistrationCode.objects.create(
        code='abcde',
        course_id=self.course.id.to_deprecated_string(),
        created_by=self.instructor,
        mode_slug='honor'
    )
    test_user1 = UserFactory()
    self.register_with_redemption_code(test_user1, course_registration_code.code)

    CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
    self.client.login(username=self.instructor.username, password='test')

    url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {})
    self.assertIn('The detailed enrollment report is being created.', response.content)
//  [python]
def test_create_registration_code_without_invoice_and_order(self):
    """
    test generate detailed enrollment report,
    used a registration codes which has been created via invoice or bulk
    purchase scenario.
    """
    course_registration_code = CourseRegistrationCode.objects.create(
        code='abcde',
        course_id=self.course.id.to_deprecated_string(),
        created_by=self.instructor,
        mode_slug='honor'
    )
    test_user1 = UserFactory()
    self.register_with_redemption_code(test_user1, course_registration_code.code)

    CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
    self.client.login(username=self.instructor.username, password='test')

    url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {})
    self.assertIn('The detailed enrollment report is being created.', response.content)
//  [python]
def test_course_has_entrance_exam_in_student_attempts_reset(self):
    """ Test course has entrance exam id set while resetting attempts"""
    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': False,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_course_has_entrance_exam_in_student_attempts_reset(self):
    """ Test course has entrance exam id set while resetting attempts"""
    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': False,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_enrollment_report_features_csv(self):
    """
    test to generate enrollment report.
    enroll users, admin staff using registration codes.
    """
    InvoiceTransaction.objects.create(
        invoice=self.sale_invoice_1,
        amount=self.sale_invoice_1.total_amount,
        status='completed',
        created_by=self.instructor,
        last_modified_by=self.instructor
    )
    course_registration_code = CourseRegistrationCode.objects.create(
        code='abcde',
        course_id=self.course.id.to_deprecated_string(),
        created_by=self.instructor,
        invoice=self.sale_invoice_1,
        invoice_item=self.invoice_item,
        mode_slug='honor'
    )

    admin_user = AdminFactory()
    admin_cart = Order.get_cart_for_user(admin_user)
    PaidCourseRegistration.add_to_order(admin_cart, self.course.id)
    admin_cart.purchase()

    # create a new user/student and enroll
    # in the course using a registration code
    # and then validates the generated detailed enrollment report
    test_user = UserFactory()
    self.register_with_redemption_code(test_user, course_registration_code.code)

    CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
    UserProfileFactory.create(user=self.students[0], meta='{"company": "asdasda"}')

    self.client.login(username=self.instructor.username, password='test')
    url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {})
    self.assertIn('The detailed enrollment report is being created.', response.content)
//  [python]
def test_enrollment_report_features_csv(self):
    """
    test to generate enrollment report.
    enroll users, admin staff using registration codes.
    """
    InvoiceTransaction.objects.create(
        invoice=self.sale_invoice_1,
        amount=self.sale_invoice_1.total_amount,
        status='completed',
        created_by=self.instructor,
        last_modified_by=self.instructor
    )
    course_registration_code = CourseRegistrationCode.objects.create(
        code='abcde',
        course_id=self.course.id.to_deprecated_string(),
        created_by=self.instructor,
        invoice=self.sale_invoice_1,
        invoice_item=self.invoice_item,
        mode_slug='honor'
    )

    admin_user = AdminFactory()
    admin_cart = Order.get_cart_for_user(admin_user)
    PaidCourseRegistration.add_to_order(admin_cart, self.course.id)
    admin_cart.purchase()

    # create a new user/student and enroll
    # in the course using a registration code
    # and then validates the generated detailed enrollment report
    test_user = UserFactory()
    self.register_with_redemption_code(test_user, course_registration_code.code)

    CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
    UserProfileFactory.create(user=self.students[0], meta='{"company": "asdasda"}')

    self.client.login(username=self.instructor.username, password='test')
    url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {})
    self.assertIn('The detailed enrollment report is being created.', response.content)
//  [python]
def test_entrance_exam_reset_student_attempts_nonsense(self):
    """ Test failure with both unique_student_identifier and all_students. """
    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,
        'all_students': True,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_entrance_exam_reset_student_attempts_nonsense(self):
    """ Test failure with both unique_student_identifier and all_students. """
    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,
        'all_students': True,
    })
    self.assertEqual(response.status_code, 400)
//  [python]
def test_get_ora2_responses_already_running(self):
    url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)})

    with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task:
        mock_submit_ora2_task.side_effect = AlreadyRunningError()
        response = self.client.post(url, {})
    already_running_status = "An ORA data report generation task is already in progress."
    self.assertIn(already_running_status, response.content)
//  [python]
def test_get_ora2_responses_already_running(self):
    url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)})

    with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task:
        mock_submit_ora2_task.side_effect = AlreadyRunningError()
        response = self.client.get(url, {})
    already_running_status = "An ORA data report generation task is already in progress."
    self.assertIn(already_running_status, response.content)
//  [python]
def test_entrance_exam_sttudent_delete_state(self):
    """ Test delete single student entrance exam state. """
    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,
        'delete_module': True,
    })
    self.assertEqual(response.status_code, 200)
    # make sure the module has been deleted
    changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules)
    self.assertEqual(changed_modules.count(), 0)
//  [python]
def test_entrance_exam_sttudent_delete_state(self):
    """ Test delete single student entrance exam state. """
    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,
        'delete_module': True,
    })
    self.assertEqual(response.status_code, 200)
    # make sure the module has been deleted
    changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules)
    self.assertEqual(changed_modules.count(), 0)
//  [python]
def test_entrance_exam_delete_state_with_staff(self):
    """ Test entrance exam delete state failure with staff access. """
    self.client.logout()
    staff_user = StaffFactory(course_key=self.course.id)
    self.client.login(username=staff_user.username, password='test')
    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,
        'delete_module': True,
    })
    self.assertEqual(response.status_code, 403)
//  [python]
def test_entrance_exam_delete_state_with_staff(self):
    """ Test entrance exam delete state failure with staff access. """
    self.client.logout()
    staff_user = StaffFactory(course_key=self.course.id)
    self.client.login(username=staff_user.username, password='test')
    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,
        'delete_module': True,
    })
    self.assertEqual(response.status_code, 403)
//  [python]
def test_get_historical_coupon_codes(self):
    """
    Test to download a response of all the active coupon codes
    """
    get_coupon_code_url = reverse(
        'get_coupon_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}
    )
    for i in range(10):
        coupon = Coupon(
            code='test_code{0}'.format(i), description='test_description', course_id=self.course.id,
            percentage_discount='{0}'.format(i), created_by=self.instructor, is_active=True
        )
        coupon.save()

    #now create coupons with the expiration dates
    for i in range(5):
        coupon = Coupon(
            code='coupon{0}'.format(i), description='test_description', course_id=self.course.id,
            percentage_discount='{0}'.format(i), created_by=self.instructor, is_active=True,
            expiration_date=datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=2)
        )
        coupon.save()

    response = self.client.post(get_coupon_code_url)
    self.assertEqual(response.status_code, 200, response.content)
    # filter all the coupons
    for coupon in Coupon.objects.all():
        self.assertIn(
            '"{coupon_code}","{course_id}","{discount}","{description}","{expiration_date}","{is_active}",'
            '"{code_redeemed_count}","{total_discounted_seats}","{total_discounted_amount}"'.format(
                coupon_code=coupon.code,
                course_id=coupon.course_id,
                discount=coupon.percentage_discount,
                description=coupon.description,
                expiration_date=coupon.display_expiry_date,
                is_active=coupon.is_active,
                code_redeemed_count="0",
                total_discounted_seats="0",
                total_discounted_amount="0",
            ), response.content
        )

    self.assertEqual(response['Content-Type'], 'text/csv')
    body = response.content.replace('\r', '')
    self.assertTrue(body.startswith(EXPECTED_COUPON_CSV_HEADER))
//  [python]
def test_get_historical_coupon_codes(self):
    """
    Test to download a response of all the active coupon codes
    """
    get_coupon_code_url = reverse(
        'get_coupon_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}
    )
    for i in range(10):
        coupon = Coupon(
            code='test_code{0}'.format(i), description='test_description', course_id=self.course.id,
            percentage_discount='{0}'.format(i), created_by=self.instructor, is_active=True
        )
        coupon.save()

    #now create coupons with the expiration dates
    for i in range(5):
        coupon = Coupon(
            code='coupon{0}'.format(i), description='test_description', course_id=self.course.id,
            percentage_discount='{0}'.format(i), created_by=self.instructor, is_active=True,
            expiration_date=datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=2)
        )
        coupon.save()

    response = self.client.get(get_coupon_code_url)
    self.assertEqual(response.status_code, 200, response.content)
    # filter all the coupons
    for coupon in Coupon.objects.all():
        self.assertIn(
            '"{coupon_code}","{course_id}","{discount}","{description}","{expiration_date}","{is_active}",'
            '"{code_redeemed_count}","{total_discounted_seats}","{total_discounted_amount}"'.format(
                coupon_code=coupon.code,
                course_id=coupon.course_id,
                discount=coupon.percentage_discount,
                description=coupon.description,
                expiration_date=coupon.display_expiry_date,
                is_active=coupon.is_active,
                code_redeemed_count="0",
                total_discounted_seats="0",
                total_discounted_amount="0",
            ), response.content
        )

    self.assertEqual(response['Content-Type'], 'text/csv')
    body = response.content.replace('\r', '')
    self.assertTrue(body.startswith(EXPECTED_COUPON_CSV_HEADER))
//  [python]
def call_add_users_to_cohorts(self, csv_data, suffix='.csv'):
    """
    Call `add_users_to_cohorts` with a file generated from `csv_data`.
    """
    # this temporary file will be removed in `self.tearDown()`
    __, file_name = tempfile.mkstemp(suffix=suffix, dir=self.tempdir)
    with open(file_name, 'w') as file_pointer:
        file_pointer.write(csv_data.encode('utf-8'))
    with open(file_name, 'r') as file_pointer:
        url = reverse('add_users_to_cohorts', kwargs={'course_id': unicode(self.course.id)})
        return self.client.post(url, {'uploaded-file': file_pointer})
//  [python]
def call_add_users_to_cohorts(self, csv_data, suffix='.csv', method='POST'):
    """
    Call `add_users_to_cohorts` with a file generated from `csv_data`.
    """
    # this temporary file will be removed in `self.tearDown()`
    __, file_name = tempfile.mkstemp(suffix=suffix, dir=self.tempdir)
    with open(file_name, 'w') as file_pointer:
        file_pointer.write(csv_data.encode('utf-8'))
    with open(file_name, 'r') as file_pointer:
        url = reverse('add_users_to_cohorts', kwargs={'course_id': unicode(self.course.id)})
        if method == 'POST':
            return self.client.post(url, {'uploaded-file': file_pointer})
        elif method == 'GET':
            return self.client.get(url, {'uploaded-file': file_pointer})
//  [python]
def test_get_ora2_responses_success(self):
    url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)})

    with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task:
        mock_submit_ora2_task.return_value = True
        response = self.client.post(url, {})
    success_status = "The ORA data report is being generated."
    self.assertIn(success_status, response.content)
//  [python]
def test_get_ora2_responses_success(self):
    url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)})

    with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task:
        mock_submit_ora2_task.return_value = True
        response = self.client.get(url, {})
    success_status = "The ORA data report is being generated."
    self.assertIn(success_status, response.content)
//  [python]
def test_get_anon_ids(self):
    """
    Test the CSV output for the anonymized user ids.
    """
    url = reverse('get_anon_ids', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.post(url, {})
    self.assertEqual(response['Content-Type'], 'text/csv')
    body = response.content.replace('\r', '')
    self.assertTrue(body.startswith(
        '"User ID","Anonymized User ID","Course Specific Anonymized User ID"'
        '\n"{user_id}","41","42"\n'.format(user_id=self.students[0].id)
    ))
    self.assertTrue(
        body.endswith('"{user_id}","41","42"\n'.format(user_id=self.students[-1].id))
    )
//  [python]
def test_get_anon_ids(self):
    """
    Test the CSV output for the anonymized user ids.
    """
    url = reverse('get_anon_ids', kwargs={'course_id': self.course.id.to_deprecated_string()})
    response = self.client.get(url, {})
    self.assertEqual(response['Content-Type'], 'text/csv')
    body = response.content.replace('\r', '')
    self.assertTrue(body.startswith(
        '"User ID","Anonymized User ID","Course Specific Anonymized User ID"'
        '\n"{user_id}","41","42"\n'.format(user_id=self.students[0].id)
    ))
    self.assertTrue(
        body.endswith('"{user_id}","41","42"\n'.format(user_id=self.students[-1].id))
    )
//  [python]
def test_get_problem_responses_already_running(self):
    """
    Test whether get_problem_responses returns an appropriate status
    message if CSV generation is already in progress.
    """
    url = reverse(
        'get_problem_responses',
        kwargs={'course_id': unicode(self.course.id)}
    )

    with patch('instructor_task.api.submit_calculate_problem_responses_csv') as submit_task_function:
        error = AlreadyRunningError()
        submit_task_function.side_effect = error
        response = self.client.post(url, {})
        res_json = json.loads(response.content)
        self.assertIn('status', res_json)
        self.assertIn('already in progress', res_json['status'])
//  [python]
def test_get_problem_responses_already_running(self):
    """
    Test whether get_problem_responses returns an appropriate status
    message if CSV generation is already in progress.
    """
    url = reverse(
        'get_problem_responses',
        kwargs={'course_id': unicode(self.course.id)}
    )

    with patch('instructor_task.api.submit_calculate_problem_responses_csv') as submit_task_function:
        error = AlreadyRunningError()
        submit_task_function.side_effect = error
        response = self.client.get(url, {})
        res_json = json.loads(response.content)
        self.assertIn('status', res_json)
        self.assertIn('already in progress', res_json['status'])
//  [python]
def test_get_sale_records_features_csv(self):
    """
    Test that the response from get_sale_records is in csv format.
    """
    for i in range(2):
        course_registration_code = CourseRegistrationCode(
            code='sale_invoice{}'.format(i),
            course_id=self.course.id.to_deprecated_string(),
            created_by=self.instructor,
            invoice=self.sale_invoice_1,
            invoice_item=self.invoice_item,
            mode_slug='honor'
        )
        course_registration_code.save()

    url = reverse(
        'get_sale_records',
        kwargs={'course_id': self.course.id.to_deprecated_string()}
    )
    response = self.client.post(url + '/csv', {})
    self.assertEqual(response['Content-Type'], 'text/csv')
//  [python]
def test_get_sale_records_features_csv(self):
    """
    Test that the response from get_sale_records is in csv format.
    """
    for i in range(2):
        course_registration_code = CourseRegistrationCode(
            code='sale_invoice{}'.format(i),
            course_id=self.course.id.to_deprecated_string(),
            created_by=self.instructor,
            invoice=self.sale_invoice_1,
            invoice_item=self.invoice_item,
            mode_slug='honor'
        )
        course_registration_code.save()

    url = reverse(
        'get_sale_records',
        kwargs={'course_id': self.course.id.to_deprecated_string()}
    )
    response = self.client.get(url + '/csv', {})
    self.assertEqual(response['Content-Type'], 'text/csv')
//  [python]
def test_get_problem_responses_successful(self):
    """
    Test whether get_problem_responses returns an appropriate status
    message if CSV generation was started successfully.
    """
    url = reverse(
        'get_problem_responses',
        kwargs={'course_id': unicode(self.course.id)}
    )
    problem_location = ''

    response = self.client.post(url, {'problem_location': problem_location})
    res_json = json.loads(response.content)
    self.assertIn('status', res_json)
    status = res_json['status']
    self.assertIn('is being created', status)
    self.assertNotIn('already in progress', status)
//  [python]
def test_get_problem_responses_successful(self):
    """
    Test whether get_problem_responses returns an appropriate status
    message if CSV generation was started successfully.
    """
    url = reverse(
        'get_problem_responses',
        kwargs={'course_id': unicode(self.course.id)}
    )
    problem_location = ''

    response = self.client.get(url, {'problem_location': problem_location})
    res_json = json.loads(response.content)
    self.assertIn('status', res_json)
    status = res_json['status']
    self.assertIn('is being created', status)
    self.assertNotIn('already in progress', status)
//  [python]
def test_get_problem_responses_invalid_location(self):
    """
    Test whether get_problem_responses returns an appropriate status
    message when users submit an invalid problem location.
    """
    url = reverse(
        'get_problem_responses',
        kwargs={'course_id': unicode(self.course.id)}
    )
    problem_location = ''

    response = self.client.post(url, {'problem_location': problem_location})
    res_json = json.loads(response.content)
    self.assertEqual(res_json, 'Could not find problem with this location.')
//  [python]
def test_get_problem_responses_invalid_location(self):
    """
    Test whether get_problem_responses returns an appropriate status
    message when users submit an invalid problem location.
    """
    url = reverse(
        'get_problem_responses',
        kwargs={'course_id': unicode(self.course.id)}
    )
    problem_location = ''

    response = self.client.get(url, {'problem_location': problem_location})
    res_json = json.loads(response.content)
    self.assertEqual(res_json, 'Could not find problem with this location.')