refactor: ran pyupgrade on lms/djangoapps/certificates (#26740)

This commit is contained in:
Usama Sadiq
2021-03-12 14:47:30 +05:00
committed by GitHub
parent 82406e970a
commit bd9bb424cd
32 changed files with 196 additions and 254 deletions

View File

@@ -2,21 +2,19 @@
Tests for the cert_allowlist command
"""
import mock
from unittest import mock
import pytest
from django.core.management import CommandError, call_command
from edx_toggles.toggles.testutils import override_waffle_flag
from waffle.testutils import override_switch
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory
from lms.djangoapps.certificates.generation_handler import CERTIFICATES_USE_ALLOWLIST
from lms.djangoapps.certificates.tests.factories import CertificateWhitelistFactory
from lms.djangoapps.certificates.tests.test_generation_handler import (
AUTO_GENERATION_SWITCH_NAME,
ID_VERIFIED_METHOD
)
from lms.djangoapps.certificates.tests.test_generation_handler import AUTO_GENERATION_SWITCH_NAME, ID_VERIFIED_METHOD
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
@override_switch(AUTO_GENERATION_SWITCH_NAME, active=True)

View File

@@ -1,16 +1,13 @@
"""Tests for the resubmit_error_certificates management command. """
from unittest.mock import patch
import ddt
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test.utils import override_settings
from mock import patch
from opaque_keys.edx.locator import CourseLocator
from six import text_type
from six.moves import range
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, check_mongo_calls
from common.djangoapps.course_modes.models import CourseMode
from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory
@@ -20,6 +17,8 @@ from lms.djangoapps.badges.tests.factories import BadgeAssertionFactory, CourseC
from lms.djangoapps.certificates.models import CertificateStatuses, GeneratedCertificate
from lms.djangoapps.certificates.tests.factories import GeneratedCertificateFactory
from lms.djangoapps.grades.tests.utils import mock_passing_grade
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, check_mongo_calls
class CertificateManagementTest(ModuleStoreTestCase):
@@ -88,8 +87,8 @@ class ResubmitErrorCertificatesTest(CertificateManagementTest):
# Re-submit certificates for two of the courses
call_command(self.command, course_key_list=[
text_type(self.courses[0].id),
text_type(self.courses[1].id)
str(self.courses[0].id),
str(self.courses[1].id)
])
# Expect that the first two courses have been re-submitted,
@@ -136,7 +135,7 @@ class ResubmitErrorCertificatesTest(CertificateManagementTest):
call_command(self.command)
def test_invalid_course_key(self):
invalid_key = u"invalid/"
invalid_key = "invalid/"
with self.assertRaisesRegex(CommandError, invalid_key):
call_command(self.command, course_key_list=[invalid_key])
@@ -183,7 +182,7 @@ class RegenerateCertificatesTest(CertificateManagementTest):
self.course.issue_badges = issue_badges
self.store.update_item(self.course, None)
args = u'-u {} -c {}'.format(self.user.email, text_type(key))
args = '-u {} -c {}'.format(self.user.email, str(key))
call_command(self.command, *args.split(' '))
assert xqueue.return_value.regen_cert.call_args.args == (
@@ -211,7 +210,7 @@ class RegenerateCertificatesTest(CertificateManagementTest):
key = self.course.location.course_key
self._create_cert(key, self.user, CertificateStatuses.downloadable)
args = u'-u {} -c {} --insecure'.format(self.user.email, text_type(key))
args = '-u {} -c {} --insecure'.format(self.user.email, str(key))
call_command(self.command, *args.split(' '))
certificate = GeneratedCertificate.eligible_certificates.get(
@@ -248,7 +247,7 @@ class UngenerateCertificatesTest(CertificateManagementTest):
self._create_cert(key, self.user, CertificateStatuses.unavailable)
with mock_passing_grade():
args = u'-c {} --insecure'.format(text_type(key))
args = '-c {} --insecure'.format(str(key))
call_command(self.command, *args.split(' '))
assert mock_send_to_queue.called

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
import django.db.models.deletion
import django.utils.timezone
import jsonfield.fields
@@ -71,7 +68,7 @@ class Migration(migrations.Migration):
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('change_date', models.DateTimeField(auto_now_add=True, verbose_name='Change date')),
('enabled', models.BooleanField(default=False, verbose_name='Enabled')),
('configuration', models.TextField(help_text=u'Certificate HTML View Parameters (JSON)')),
('configuration', models.TextField(help_text='Certificate HTML View Parameters (JSON)')),
('changed_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, editable=False, to=settings.AUTH_USER_MODEL, null=True, verbose_name='Changed by')),
],
options={
@@ -132,7 +129,7 @@ class Migration(migrations.Migration):
('access_key', models.CharField(default=cert_models._make_uuid, help_text='An access key for the example certificate. This is used when we receive a response from the queue to validate that the sender is the same entity we asked to generate the certificate.', max_length=255, db_index=True)),
('full_name', models.CharField(default='John Do\xeb', help_text='The full name that will appear on the certificate.', max_length=255)),
('template', models.CharField(help_text='The template file to use when generating the certificate.', max_length=255)),
('status', models.CharField(default=u'started', help_text='The status of the example certificate.', max_length=255, choices=[(u'started', u'Started'), (u'success', u'Success'), (u'error', u'Error')])),
('status', models.CharField(default='started', help_text='The status of the example certificate.', max_length=255, choices=[('started', 'Started'), ('success', 'Success'), ('error', 'Error')])),
('error_reason', models.TextField(default=None, help_text='The reason an error occurred during certificate generation.', null=True)),
('download_url', models.CharField(default=None, max_length=255, null=True, help_text='The download URL for the generated certificate.')),
],
@@ -154,18 +151,18 @@ class Migration(migrations.Migration):
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('course_id', CourseKeyField(default=None, max_length=255, blank=True)),
('verify_uuid', models.CharField(default=u'', max_length=32, blank=True)),
('download_uuid', models.CharField(default=u'', max_length=32, blank=True)),
('download_url', models.CharField(default=u'', max_length=128, blank=True)),
('grade', models.CharField(default=u'', max_length=5, blank=True)),
('key', models.CharField(default=u'', max_length=32, blank=True)),
('verify_uuid', models.CharField(default='', max_length=32, blank=True)),
('download_uuid', models.CharField(default='', max_length=32, blank=True)),
('download_url', models.CharField(default='', max_length=128, blank=True)),
('grade', models.CharField(default='', max_length=5, blank=True)),
('key', models.CharField(default='', max_length=32, blank=True)),
('distinction', models.BooleanField(default=False)),
('status', models.CharField(default=u'unavailable', max_length=32)),
('mode', models.CharField(default=u'honor', max_length=32, choices=[(u'verified', u'verified'), (u'honor', u'honor'), (u'audit', u'audit'), (u'professional', u'professional'), (u'no-id-professional', u'no-id-professional')])),
('status', models.CharField(default='unavailable', max_length=32)),
('mode', models.CharField(default='honor', max_length=32, choices=[('verified', 'verified'), ('honor', 'honor'), ('audit', 'audit'), ('professional', 'professional'), ('no-id-professional', 'no-id-professional')])),
('name', models.CharField(max_length=255, blank=True)),
('created_date', models.DateTimeField(auto_now_add=True)),
('modified_date', models.DateTimeField(auto_now=True)),
('error_reason', models.CharField(default=u'', max_length=512, blank=True)),
('error_reason', models.CharField(default='', max_length=512, blank=True)),
('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)),
],
),
@@ -176,14 +173,14 @@ class Migration(migrations.Migration):
),
migrations.AlterUniqueTogether(
name='certificatetemplate',
unique_together=set([('organization_id', 'course_key', 'mode')]),
unique_together={('organization_id', 'course_key', 'mode')},
),
migrations.AlterUniqueTogether(
name='generatedcertificate',
unique_together=set([('user', 'course_id')]),
unique_together={('user', 'course_id')},
),
migrations.AlterUniqueTogether(
name='badgeassertion',
unique_together=set([('course_id', 'user', 'mode')]),
unique_together={('course_id', 'user', 'mode')},
),
]

View File

@@ -1,7 +1,3 @@
# -*- coding: utf-8 -*-
import json
from django.db import migrations, models

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.files import File
from django.db import migrations, models
@@ -19,9 +16,9 @@ def forwards(apps, schema_editor):
if not objects.exists():
for mode in ['honor', 'verified', 'professional']:
conf = objects.create(mode=mode)
file_name = '{0}{1}'.format(mode, '.png')
file_name = '{}{}'.format(mode, '.png')
conf.icon.save(
'badges/{}'.format(file_name),
f'badges/{file_name}',
File(open(settings.PROJECT_ROOT / 'static' / 'images' / 'default-badges' / file_name, 'rb'))
)

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
import django.utils.timezone
import model_utils.fields
from django.conf import settings

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import migrations, models
@@ -14,6 +11,6 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='generatedcertificate',
name='verify_uuid',
field=models.CharField(default=u'', max_length=32, db_index=True, blank=True),
field=models.CharField(default='', max_length=32, db_index=True, blank=True),
),
]

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import migrations, models

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
import django.utils.timezone
import model_utils.fields
from django.conf import settings

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import migrations, models
@@ -14,7 +11,7 @@ class Migration(migrations.Migration):
operations = [
migrations.AlterUniqueTogether(
name='badgeassertion',
unique_together=set([]),
unique_together=set(),
),
migrations.RemoveField(
model_name='badgeassertion',

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.apps import apps
from django.db import migrations, models
from django.db.models import F

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import migrations, models

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
import logging
from django.db import migrations, models
@@ -47,7 +44,7 @@ class Migration(migrations.Migration):
operations = [
migrations.AlterUniqueTogether(
name='certificatetemplate',
unique_together=set([('organization_id', 'course_key', 'mode', 'language')]),
unique_together={('organization_id', 'course_key', 'mode', 'language')},
),
migrations.RunPython(migrations.RunPython.noop, reverse_code=revert_alter_unique)
]

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import migrations, models

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import migrations

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-01-30 17:38

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-04-04 15:14
@@ -15,11 +14,11 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='certificatetemplate',
name='mode',
field=models.CharField(blank=True, choices=[(u'verified', u'verified'), (u'honor', u'honor'), (u'audit', u'audit'), (u'professional', u'professional'), (u'no-id-professional', u'no-id-professional'), (u'masters', u'masters')], default=u'honor', help_text='The course mode for this template.', max_length=125, null=True),
field=models.CharField(blank=True, choices=[('verified', 'verified'), ('honor', 'honor'), ('audit', 'audit'), ('professional', 'professional'), ('no-id-professional', 'no-id-professional'), ('masters', 'masters')], default='honor', help_text='The course mode for this template.', max_length=125, null=True),
),
migrations.AlterField(
model_name='generatedcertificate',
name='mode',
field=models.CharField(choices=[(u'verified', u'verified'), (u'honor', u'honor'), (u'audit', u'audit'), (u'professional', u'professional'), (u'no-id-professional', u'no-id-professional'), (u'masters', u'masters')], default=u'honor', max_length=32),
field=models.CharField(choices=[('verified', 'verified'), ('honor', 'honor'), ('audit', 'audit'), ('professional', 'professional'), ('no-id-professional', 'no-id-professional'), ('masters', 'masters')], default='honor', max_length=32),
),
]

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.26 on 2019-12-10 18:05

View File

@@ -21,7 +21,7 @@ class GeneratedCertificateFactory(DjangoModelFactory):
"""
GeneratedCertificate factory
"""
class Meta(object):
class Meta:
model = GeneratedCertificate
course_id = None
@@ -37,7 +37,7 @@ class CertificateWhitelistFactory(DjangoModelFactory):
CertificateWhitelist factory
"""
class Meta(object):
class Meta:
model = CertificateWhitelist
course_id = None
@@ -50,7 +50,7 @@ class CertificateInvalidationFactory(DjangoModelFactory):
CertificateInvalidation factory
"""
class Meta(object):
class Meta:
model = CertificateInvalidation
notes = 'Test Notes'
@@ -62,7 +62,7 @@ class CertificateHtmlViewConfigurationFactory(DjangoModelFactory):
CertificateHtmlViewConfiguration factory
"""
class Meta(object):
class Meta:
model = CertificateHtmlViewConfiguration
enabled = True
@@ -99,7 +99,7 @@ class LinkedInAddToProfileConfigurationFactory(DjangoModelFactory):
LinkedInAddToProfileConfiguration factory
"""
class Meta(object):
class Meta:
model = LinkedInAddToProfileConfiguration
enabled = True

View File

@@ -4,11 +4,11 @@
import uuid
from contextlib import contextmanager
from datetime import datetime, timedelta
from unittest.mock import patch
import pytest
import ddt
import pytz
import six
from config_models.models import cache
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
@@ -18,7 +18,6 @@ from django.urls import reverse
from django.utils import timezone
from edx_toggles.toggles.testutils import override_waffle_flag
from freezegun import freeze_time
from mock import patch
from opaque_keys.edx.keys import CourseKey
from opaque_keys.edx.locator import CourseLocator
from testfixtures import LogCapture
@@ -44,13 +43,13 @@ from lms.djangoapps.certificates.api import (
generate_user_certificates,
get_allowlist_entry,
get_allowlisted_users,
get_certificate_for_user,
get_certificates_for_user,
get_certificates_for_user_by_course_keys,
get_certificate_footer_context,
get_certificate_for_user,
get_certificate_header_context,
get_certificate_invalidation_entry,
get_certificate_url,
get_certificates_for_user,
get_certificates_for_user_by_course_keys,
is_certificate_invalidated,
is_on_allowlist,
remove_allowlist_entry,
@@ -79,7 +78,7 @@ FEATURES_WITH_CERTS_ENABLED = settings.FEATURES.copy()
FEATURES_WITH_CERTS_ENABLED['CERTIFICATES_HTML_VIEW'] = True
class WebCertificateTestMixin(object):
class WebCertificateTestMixin:
"""
Mixin with helpers for testing Web Certificates.
"""
@@ -358,7 +357,7 @@ class CertificateGetTests(SharedModuleStoreTestCase):
cls.freezer = freeze_time(cls.now)
cls.freezer.start()
super(CertificateGetTests, cls).setUpClass()
super().setUpClass()
cls.student = UserFactory()
cls.student_no_cert = UserFactory()
cls.uuid = uuid.uuid4().hex
@@ -409,7 +408,7 @@ class CertificateGetTests(SharedModuleStoreTestCase):
@classmethod
def tearDownClass(cls):
super(CertificateGetTests, cls).tearDownClass()
super().tearDownClass()
cls.freezer.stop()
def test_get_certificate_for_user(self):
@@ -560,7 +559,7 @@ class GenerateUserCertificatesTest(EventTestMixin, WebCertificateTestMixin, Modu
self.assert_event_emitted(
'edx.certificate.created',
user_id=self.student.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
certificate_url=get_certificate_url(self.student.id, self.course.id),
certificate_id=cert.verify_uuid,
enrollment_mode=cert.mode,
@@ -651,7 +650,7 @@ class CertificateGenerationEnabledTest(EventTestMixin, TestCase):
event_name = '.'.join(['edx', 'certificate', 'generation', cert_event_type])
self.assert_event_emitted(
event_name,
course_id=six.text_type(self.COURSE_KEY),
course_id=str(self.COURSE_KEY),
)
self._assert_enabled_for_course(self.COURSE_KEY, expect_enabled)
@@ -775,8 +774,7 @@ class CertificatesBrandingTest(ModuleStoreTestCase):
data = get_certificate_header_context(is_secure=True)
# Make sure there are not unexpected keys in dict returned by 'get_certificate_header_context'
six.assertCountEqual(
self,
self.assertCountEqual(
list(data.keys()),
['logo_src', 'logo_url']
)
@@ -795,8 +793,7 @@ class CertificatesBrandingTest(ModuleStoreTestCase):
data = get_certificate_footer_context()
# Make sure there are not unexpected keys in dict returned by 'get_certificate_footer_context'
six.assertCountEqual(
self,
self.assertCountEqual(
list(data.keys()),
['company_about_url', 'company_privacy_url', 'company_tos_url']
)

View File

@@ -4,21 +4,21 @@ Tests for certificate generation
import logging
from edx_toggles.toggles import LegacyWaffleSwitch
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory
from common.djangoapps.util.testing import EventTestMixin
from lms.djangoapps.certificates.generation import generate_allowlist_certificate
from lms.djangoapps.certificates.models import GeneratedCertificate, CertificateStatuses
from lms.djangoapps.certificates.models import CertificateStatuses, GeneratedCertificate
from openedx.core.djangoapps.certificates.config import waffle
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
log = logging.getLogger(__name__)
ID_VERIFIED_METHOD = 'lms.djangoapps.verify_student.services.IDVerificationService.user_is_verified'
AUTO_GENERATION_NAMESPACE = waffle.WAFFLE_NAMESPACE
AUTO_GENERATION_NAME = waffle.AUTO_CERTIFICATE_GENERATION
AUTO_GENERATION_SWITCH_NAME = '{}.{}'.format(AUTO_GENERATION_NAMESPACE, AUTO_GENERATION_NAME)
AUTO_GENERATION_SWITCH_NAME = f'{AUTO_GENERATION_NAMESPACE}.{AUTO_GENERATION_NAME}'
AUTO_GENERATION_SWITCH = LegacyWaffleSwitch(AUTO_GENERATION_NAMESPACE, AUTO_GENERATION_NAME)

View File

@@ -2,19 +2,17 @@
Tests for certificate generation handler
"""
import logging
from unittest import mock
import ddt
import mock
from edx_toggles.toggles import LegacyWaffleSwitch
from edx_toggles.toggles.testutils import override_waffle_flag
from edx_toggles.toggles.testutils import override_waffle_switch
from edx_toggles.toggles.testutils import override_waffle_flag, override_waffle_switch
from waffle.testutils import override_switch
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory
from lms.djangoapps.certificates.generation_handler import CERTIFICATES_USE_ALLOWLIST, CERTIFICATES_USE_UPDATED
from lms.djangoapps.certificates.generation_handler import (
CERTIFICATES_USE_ALLOWLIST,
CERTIFICATES_USE_UPDATED,
_can_generate_allowlist_certificate_for_status,
is_using_certificate_allowlist,
_is_using_v2_course_certificates,
@@ -26,20 +24,22 @@ from lms.djangoapps.certificates.generation_handler import (
generate_regular_certificate_task,
is_using_certificate_allowlist_and_is_on_allowlist
)
from lms.djangoapps.certificates.models import GeneratedCertificate, CertificateStatuses
from lms.djangoapps.certificates.models import CertificateStatuses, GeneratedCertificate
from lms.djangoapps.certificates.tests.factories import (
CertificateInvalidationFactory,
CertificateWhitelistFactory,
GeneratedCertificateFactory,
CertificateInvalidationFactory
GeneratedCertificateFactory
)
from openedx.core.djangoapps.certificates.config import waffle
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
log = logging.getLogger(__name__)
ID_VERIFIED_METHOD = 'lms.djangoapps.verify_student.services.IDVerificationService.user_is_verified'
AUTO_GENERATION_NAMESPACE = waffle.WAFFLE_NAMESPACE
AUTO_GENERATION_NAME = waffle.AUTO_CERTIFICATE_GENERATION
AUTO_GENERATION_SWITCH_NAME = '{}.{}'.format(AUTO_GENERATION_NAMESPACE, AUTO_GENERATION_NAME)
AUTO_GENERATION_SWITCH_NAME = f'{AUTO_GENERATION_NAMESPACE}.{AUTO_GENERATION_NAME}'
AUTO_GENERATION_SWITCH = LegacyWaffleSwitch(AUTO_GENERATION_NAMESPACE, AUTO_GENERATION_NAME)

View File

@@ -2,6 +2,8 @@
import json
from unittest.mock import patch
import pytest
import ddt
from django.conf import settings
@@ -9,11 +11,8 @@ from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.test.utils import override_settings
from mock import patch
from opaque_keys.edx.locator import CourseKey, CourseLocator
from path import Path as path
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from common.djangoapps.student.tests.factories import AdminFactory, UserFactory
from lms.djangoapps.certificates.models import (
@@ -29,6 +28,8 @@ from lms.djangoapps.certificates.models import (
from lms.djangoapps.certificates.tests.factories import CertificateInvalidationFactory, GeneratedCertificateFactory
from lms.djangoapps.instructor_task.tests.factories import InstructorTaskFactory
from openedx.core.djangoapps.content.course_overviews.tests.factories import CourseOverviewFactory
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
FEATURES_INVALID_FILE_PATH = settings.FEATURES.copy()
FEATURES_INVALID_FILE_PATH['CERTS_HTML_VIEW_CONFIG_PATH'] = 'invalid/path/to/config.json'
@@ -201,7 +202,7 @@ class EligibleCertificateManagerTest(SharedModuleStoreTestCase):
self.course1 = CourseOverviewFactory()
self.course2 = CourseOverviewFactory(
id=CourseKey.from_string('{}a'.format(self.course1.id))
id=CourseKey.from_string(f'{self.course1.id}a')
)
self.eligible_cert = GeneratedCertificateFactory.create(

View File

@@ -1,19 +1,17 @@
# -*- coding: utf-8 -*-
"""Tests for the XQueue certificates interface. """
import json
from contextlib import contextmanager
from datetime import datetime, timedelta
from unittest.mock import Mock, patch
import ddt
import freezegun
import pytz
import six
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from mock import Mock, patch
from opaque_keys.edx.locator import CourseLocator
from testfixtures import LogCapture
@@ -349,14 +347,14 @@ class XQueueCertInterfaceAddCertificateTest(ModuleStoreTestCase):
LOGGER.name,
'WARNING',
(
u"PDF certificate generation discontinued, canceling "
u"PDF certificate generation for student {student_id} "
u"in course '{course_id}' "
u"with status '{status}' "
u"and download_url '{download_url}'."
"PDF certificate generation discontinued, canceling "
"PDF certificate generation for student {student_id} "
"in course '{course_id}' "
"with status '{status}' "
"and download_url '{download_url}'."
).format(
student_id=self.user_2.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
status=CertificateStatuses.downloadable,
download_url=download_url
)
@@ -418,15 +416,15 @@ class XQueueCertInterfaceExampleCertificateTest(TestCase):
"""Check that the task was added to the queue. """
expected_header = {
'lms_key': cert.access_key,
'lms_callback_url': 'https://edx.org/update_example_certificate?key={key}'.format(key=cert.uuid),
'lms_callback_url': f'https://edx.org/update_example_certificate?key={cert.uuid}',
'queue_name': 'certificates'
}
expected_body = {
'action': 'create',
'username': cert.uuid,
'name': u'John Doë',
'course_id': six.text_type(self.COURSE_KEY),
'name': 'John Doë',
'course_id': str(self.COURSE_KEY),
'template_pdf': 'test.pdf',
'example_certificate': True
}

View File

@@ -3,15 +3,14 @@ Unit Tests for the Certificate service
"""
from edx_toggles.toggles.testutils import override_waffle_flag
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from common.djangoapps.student.tests.factories import UserFactory
from lms.djangoapps.certificates.generation_handler import CERTIFICATES_USE_ALLOWLIST
from lms.djangoapps.certificates.models import CertificateStatuses, GeneratedCertificate
from lms.djangoapps.certificates.services import CertificateService
from lms.djangoapps.certificates.tests.factories import CertificateWhitelistFactory
from lms.djangoapps.certificates.tests.factories import GeneratedCertificateFactory
from lms.djangoapps.certificates.tests.factories import CertificateWhitelistFactory, GeneratedCertificateFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
class CertificateServiceTests(ModuleStoreTestCase):

View File

@@ -4,14 +4,11 @@ and disabling for instructor-paced courses.
"""
from unittest import mock
import ddt
import mock
import six
from edx_toggles.toggles import LegacyWaffleSwitch
from edx_toggles.toggles.testutils import override_waffle_flag
from edx_toggles.toggles.testutils import override_waffle_switch
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from edx_toggles.toggles.testutils import override_waffle_flag, override_waffle_switch
from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory
from lms.djangoapps.certificates.api import cert_generation_enabled
@@ -23,12 +20,13 @@ from lms.djangoapps.certificates.models import (
)
from lms.djangoapps.certificates.signals import _fire_ungenerated_certificate_task
from lms.djangoapps.certificates.tasks import CERTIFICATE_DELAY_SECONDS
from lms.djangoapps.certificates.tests.factories import CertificateWhitelistFactory
from lms.djangoapps.certificates.tests.factories import GeneratedCertificateFactory
from lms.djangoapps.certificates.tests.factories import CertificateWhitelistFactory, GeneratedCertificateFactory
from lms.djangoapps.grades.course_grade_factory import CourseGradeFactory
from lms.djangoapps.grades.tests.utils import mock_passing_grade
from lms.djangoapps.verify_student.models import IDVerificationAttempt, SoftwareSecurePhotoVerification
from openedx.core.djangoapps.certificates.config import waffle
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
AUTO_CERTIFICATE_GENERATION_SWITCH = LegacyWaffleSwitch(waffle.waffle(), waffle.AUTO_CERTIFICATE_GENERATION)
@@ -106,8 +104,8 @@ class WhitelistGeneratedCertificatesTest(ModuleStoreTestCase):
mock_generate_certificate_apply_async.assert_called_with(
countdown=CERTIFICATE_DELAY_SECONDS,
kwargs={
'student': six.text_type(self.user.id),
'course_key': six.text_type(self.course.id),
'student': str(self.user.id),
'course_key': str(self.course.id),
}
)
@@ -134,8 +132,8 @@ class WhitelistGeneratedCertificatesTest(ModuleStoreTestCase):
mock_generate_certificate_apply_async.assert_called_with(
countdown=CERTIFICATE_DELAY_SECONDS,
kwargs={
'student': six.text_type(self.user.id),
'course_key': six.text_type(self.ip_course.id),
'student': str(self.user.id),
'course_key': str(self.ip_course.id),
}
)
@@ -182,8 +180,8 @@ class WhitelistGeneratedCertificatesTest(ModuleStoreTestCase):
mock_generate_certificate_apply_async.assert_called_with(
countdown=CERTIFICATE_DELAY_SECONDS,
kwargs={
'student': six.text_type(self.user.id),
'course_key': six.text_type(self.ip_course.id),
'student': str(self.user.id),
'course_key': str(self.ip_course.id),
}
)
mock_generate_allowlist_task.assert_not_called()
@@ -235,8 +233,8 @@ class PassingGradeCertsTest(ModuleStoreTestCase):
mock_generate_certificate_apply_async.assert_called_with(
countdown=CERTIFICATE_DELAY_SECONDS,
kwargs={
'student': six.text_type(self.user.id),
'course_key': six.text_type(self.course.id),
'student': str(self.user.id),
'course_key': str(self.course.id),
}
)
@@ -256,8 +254,8 @@ class PassingGradeCertsTest(ModuleStoreTestCase):
mock_generate_certificate_apply_async.assert_called_with(
countdown=CERTIFICATE_DELAY_SECONDS,
kwargs={
'student': six.text_type(self.user.id),
'course_key': six.text_type(self.ip_course.id),
'student': str(self.user.id),
'course_key': str(self.ip_course.id),
}
)
@@ -446,8 +444,8 @@ class LearnerTrackChangeCertsTest(ModuleStoreTestCase):
mock_generate_certificate_apply_async.assert_called_with(
countdown=CERTIFICATE_DELAY_SECONDS,
kwargs={
'student': six.text_type(self.user_one.id),
'course_key': six.text_type(self.course_one.id),
'student': str(self.user_one.id),
'course_key': str(self.course_one.id),
'expected_verification_status': IDVerificationAttempt.STATUS.approved,
}
)
@@ -467,8 +465,8 @@ class LearnerTrackChangeCertsTest(ModuleStoreTestCase):
mock_generate_certificate_apply_async.assert_called_with(
countdown=CERTIFICATE_DELAY_SECONDS,
kwargs={
'student': six.text_type(self.user_two.id),
'course_key': six.text_type(self.course_two.id),
'student': str(self.user_two.id),
'course_key': str(self.course_two.id),
'expected_verification_status': IDVerificationAttempt.STATUS.approved,
}
)

View File

@@ -4,17 +4,14 @@ Tests for certificate app views used by the support team.
import json
from unittest.mock import patch
from uuid import uuid4
import ddt
import six
from django.conf import settings
from django.test.utils import override_settings
from django.urls import reverse
from mock import patch
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from common.djangoapps.student.models import CourseEnrollment
from common.djangoapps.student.roles import GlobalStaff, SupportStaffRole
@@ -24,6 +21,8 @@ from lms.djangoapps.certificates.models import CertificateInvalidation, Certific
from lms.djangoapps.certificates.tests.factories import CertificateInvalidationFactory, GeneratedCertificateFactory
from lms.djangoapps.grades.tests.utils import mock_passing_grade
from openedx.core.djangoapps.content.course_overviews.tests.factories import CourseOverviewFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
FEATURES_WITH_CERTS_ENABLED = settings.FEATURES.copy()
FEATURES_WITH_CERTS_ENABLED['CERTIFICATES_HTML_VIEW'] = True
@@ -166,9 +165,9 @@ class CertificateSearchTests(CertificateSupportTestCase):
("", False),
(CertificateSupportTestCase.STUDENT_USERNAME, False, 'invalid_key'),
(CertificateSupportTestCase.STUDENT_USERNAME, False,
six.text_type(CertificateSupportTestCase.COURSE_NOT_EXIST_KEY)),
str(CertificateSupportTestCase.COURSE_NOT_EXIST_KEY)),
(CertificateSupportTestCase.STUDENT_USERNAME, True,
six.text_type(CertificateSupportTestCase.EXISTED_COURSE_KEY_1)),
str(CertificateSupportTestCase.EXISTED_COURSE_KEY_1)),
)
@ddt.unpack
def test_search(self, user_filter, expect_result, course_filter=None):
@@ -204,10 +203,10 @@ class CertificateSearchTests(CertificateSupportTestCase):
retrieved_cert = results[0]
assert retrieved_cert['username'] == self.STUDENT_USERNAME
assert retrieved_cert['course_key'] == six.text_type(self.CERT_COURSE_KEY)
assert retrieved_cert['course_key'] == str(self.CERT_COURSE_KEY)
assert retrieved_cert['created'] == self.cert.created_date.isoformat()
assert retrieved_cert['modified'] == self.cert.modified_date.isoformat()
assert retrieved_cert['grade'] == six.text_type(self.CERT_GRADE)
assert retrieved_cert['grade'] == str(self.CERT_GRADE)
assert retrieved_cert['status'] == self.CERT_STATUS
assert retrieved_cert['type'] == self.CERT_MODE
assert retrieved_cert['download_url'] == self.CERT_DOWNLOAD_URL
@@ -329,7 +328,7 @@ class CertificateRegenerateTests(CertificateSupportTestCase):
def test_regenerate_no_such_user(self):
response = self._regenerate(
course_key=six.text_type(self.CERT_COURSE_KEY),
course_key=str(self.CERT_COURSE_KEY),
username="invalid_username",
)
assert response.status_code == 400
@@ -494,7 +493,7 @@ class CertificateGenerateTests(CertificateSupportTestCase):
def test_generate_no_such_user(self):
response = self._generate(
course_key=six.text_type(self.EXISTED_COURSE_KEY_2),
course_key=str(self.EXISTED_COURSE_KEY_2),
username="invalid_username",
)
assert response.status_code == 400

View File

@@ -3,9 +3,10 @@ Test module for user certificate generation.
"""
from unittest.mock import call, patch
import ddt
from django.test import TestCase
from mock import call, patch
from opaque_keys.edx.keys import CourseKey
from common.djangoapps.student.tests.factories import UserFactory

View File

@@ -6,16 +6,12 @@ import json
from uuid import uuid4
import ddt
import six
from django.conf import settings
from django.core.cache import cache
from django.test.client import Client
from django.test.utils import override_settings
from django.urls import reverse
from opaque_keys.edx.locator import CourseLocator
from six.moves import range
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from common.djangoapps.student.tests.factories import UserFactory
from lms.djangoapps.certificates.models import (
@@ -27,6 +23,8 @@ from lms.djangoapps.certificates.tests.factories import GeneratedCertificateFact
from lms.djangoapps.certificates.utils import get_certificate_url
from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration
from openedx.core.djangolib.testing.utils import CacheIsolationTestCase
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
FEATURES_WITH_CERTS_ENABLED = settings.FEATURES.copy()
FEATURES_WITH_CERTS_ENABLED['CERTIFICATES_HTML_VIEW'] = True
@@ -257,7 +255,7 @@ class CertificatesViewsSiteTests(ModuleStoreTestCase):
'name': 'Signatory_Name ' + str(i),
'title': 'Signatory_Title ' + str(i),
'organization': 'Signatory_Organization ' + str(i),
'signature_image_path': '/static/certificates/images/demo-sig{}.png'.format(i),
'signature_image_path': f'/static/certificates/images/demo-sig{i}.png',
'id': i,
} for i in range(signatory_count)
@@ -285,7 +283,7 @@ class CertificatesViewsSiteTests(ModuleStoreTestCase):
def test_html_view_for_site(self):
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
self._add_course_certificates(count=1, signatory_count=2)
@@ -304,7 +302,7 @@ class CertificatesViewsSiteTests(ModuleStoreTestCase):
def test_html_view_site_configuration_missing(self):
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
self._add_course_certificates(count=1, signatory_count=2)

View File

@@ -1,24 +1,20 @@
# -*- coding: utf-8 -*-
"""Tests for certificates views. """
import datetime
import json
from unittest.mock import patch
from urllib.parse import urlencode
from uuid import uuid4
import ddt
import six
from django.conf import settings
from django.test.client import Client, RequestFactory
from django.test.utils import override_settings
from django.urls import reverse
from edx_toggles.toggles import LegacyWaffleSwitch
from edx_toggles.toggles.testutils import override_waffle_switch
from mock import patch
from organizations import api as organizations_api
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from common.djangoapps.course_modes.models import CourseMode
from common.djangoapps.student.roles import CourseStaffRole
@@ -55,6 +51,8 @@ from openedx.core.djangoapps.site_configuration.tests.test_util import (
from openedx.core.djangolib.js_utils import js_escaped_string
from openedx.core.djangolib.testing.utils import CacheIsolationTestCase
from openedx.core.lib.tests.assertions.events import assert_event_matches
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
AUTO_CERTIFICATE_GENERATION_SWITCH = LegacyWaffleSwitch(waffle.waffle(), waffle.AUTO_CERTIFICATE_GENERATION)
FEATURES_WITH_CERTS_ENABLED = settings.FEATURES.copy()
@@ -129,7 +127,7 @@ class CommonCertificatesTestCase(ModuleStoreTestCase):
'name': 'Signatory_Name ' + str(i),
'title': 'Signatory_Title ' + str(i),
'organization': 'Signatory_Organization ' + str(i),
'signature_image_path': u'/static/certificates/images/demo-sig{}.png'.format(i),
'signature_image_path': f'/static/certificates/images/demo-sig{i}.png',
'id': i
} for i in range(signatory_count)
@@ -141,7 +139,7 @@ class CommonCertificatesTestCase(ModuleStoreTestCase):
'name': 'Name ' + str(i),
'description': 'Description ' + str(i),
'course_title': 'course_title_' + str(i),
'org_logo_path': u'/t4x/orgX/testX/asset/org-logo-{}.png'.format(i),
'org_logo_path': f'/t4x/orgX/testX/asset/org-logo-{i}.png',
'signatories': signatories,
'version': 1,
'is_active': is_active
@@ -157,7 +155,7 @@ class CommonCertificatesTestCase(ModuleStoreTestCase):
"""
Creates a custom certificate template entry in DB.
"""
template_html = u"""
template_html = """
<%namespace name='static' file='static_content.html'/>
<html>
<body>
@@ -185,12 +183,12 @@ class CommonCertificatesTestCase(ModuleStoreTestCase):
"""
Creates a custom certificate template entry in DB.
"""
template_html = u"""
template_html = """
<%namespace name='static' file='static_content.html'/>
<html>
<body>
lang: ${LANGUAGE_CODE}
course name: """ + template_name + u"""
course name: """ + template_name + """
mode: ${course_mode}
${accomplishment_copy_course_description}
${twitter_url}
@@ -213,7 +211,7 @@ class CommonCertificatesTestCase(ModuleStoreTestCase):
"""
Creates a custom certificate template entry in DB that includes hours of effort.
"""
template_html = u"""
template_html = """
<%namespace name='static' file='static_content.html'/>
<html>
<body>
@@ -411,11 +409,11 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
'logo': '/logo_test1.png/'
}
test_org = organizations_api.add_organization(organization_data=test_organization_data)
organizations_api.add_organization_course(organization_data=test_org, course_key=six.text_type(self.course.id))
organizations_api.add_organization_course(organization_data=test_org, course_key=str(self.course.id))
self._add_course_certificates(count=1, signatory_count=1, is_active=True)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
response = self.client.get(test_url)
@@ -424,7 +422,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
'a course of study offered by test_organization, an online learning initiative of test organization',
)
self.assertNotContains(response, 'a course of study offered by testorg')
self.assertContains(response, u'<title>test_organization {} Certificate |'.format(self.course.number, ))
self.assertContains(response, f'<title>test_organization {self.course.number} Certificate |')
self.assertContains(response, 'logo_test1.png')
@ddt.data(True, False)
@@ -481,7 +479,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
'logo': '/logo_test1.png'
}
test_org = organizations_api.add_organization(organization_data=test_organization_data)
organizations_api.add_organization_course(organization_data=test_org, course_key=six.text_type(self.course.id))
organizations_api.add_organization_course(organization_data=test_org, course_key=str(self.course.id))
self._add_course_certificates(count=1, signatory_count=1, is_active=True)
badge_class = get_completion_badge(course_id=self.course_id, user=self.user)
BadgeAssertionFactory.create(
@@ -496,7 +494,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
response = self.client.get(test_url, HTTP_HOST='test.localhost')
@@ -509,14 +507,14 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
# Test an item from course info
self.assertContains(response, 'course_title_0')
# Test an item from user info
self.assertContains(response, u"{fullname}, you earned a certificate!".format(fullname=self.user.profile.name))
self.assertContains(response, f"{self.user.profile.name}, you earned a certificate!")
# Test an item from social info
self.assertContains(response, "Post on Facebook")
self.assertContains(response, "Share on Twitter")
# Test an item from certificate/org info
self.assertContains(
response,
u"a course of study offered by {partner_short_name}, "
"a course of study offered by {partner_short_name}, "
"an online learning initiative of "
"{partner_long_name}.".format(
partner_short_name=short_org_name,
@@ -535,7 +533,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._add_course_certificates(count=1, signatory_count=2)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
response = self.client.get(test_url)
@@ -562,7 +560,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._add_course_certificates(count=1, signatory_count=2)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
@@ -596,7 +594,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._add_course_certificates(count=1, signatory_count=2)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
response = self.client.get(test_url)
@@ -614,7 +612,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._add_course_certificates(count=1, signatory_count=2)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
@@ -635,7 +633,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._add_course_certificates(count=1, signatory_count=2)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
@@ -671,7 +669,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
response = self.client.get(test_url)
@@ -684,7 +682,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._add_course_certificates(count=1, signatory_count=2)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
@@ -714,7 +712,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self.store.update_item(self.course, self.user.id)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
@@ -733,7 +731,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._add_course_certificates(count=1, signatory_count=2)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
@@ -763,7 +761,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
response = self.client.get(test_url)
@@ -775,7 +773,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._add_course_certificates(count=1, signatory_count=0)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
response = self.client.get(test_url)
@@ -804,7 +802,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
response = self.client.get(test_url)
@@ -815,7 +813,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
def test_render_html_view_disabled_feature_flag_returns_static_url(self):
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
assert str(self.cert.download_url) in test_url
@@ -834,7 +832,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._add_course_certificates(count=1, signatory_count=0)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
self.cert.delete()
@@ -843,13 +841,13 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
response = self.client.get(test_url)
assert response.status_code == 404
@override_settings(FEATURES=FEATURES_WITH_CERTS_ENABLED, PLATFORM_NAME=u'Űńíćődé Űńívéŕśítӳ')
@override_settings(FEATURES=FEATURES_WITH_CERTS_ENABLED, PLATFORM_NAME='Űńíćődé Űńívéŕśítӳ')
def test_render_html_view_with_unicode_platform_name(self):
self._add_course_certificates(count=1, signatory_count=0)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
response = self.client.get(test_url)
@@ -903,7 +901,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
# user has already has certificate generated for 'honor' mode
@@ -931,7 +929,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._add_course_certificates(count=1, signatory_count=1, is_active=True)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
@@ -941,7 +939,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
expected_date = self.course.certificate_available_date
with override_waffle_switch(AUTO_CERTIFICATE_GENERATION_SWITCH, active=True):
response = self.client.get(test_url)
date = u'{month} {day}, {year}'.format(
date = '{month} {day}, {year}'.format(
month=strftime_localized(expected_date, "%B"),
day=expected_date.day,
year=expected_date.year
@@ -956,7 +954,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
response = self.client.get(test_url)
@@ -967,7 +965,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self.cert.status = CertificateStatuses.unavailable
self.cert.save()
request_certificate_url = reverse('request_certificate')
response = self.client.post(request_certificate_url, {'course_id': six.text_type(self.course.id)})
response = self.client.post(request_certificate_url, {'course_id': str(self.course.id)})
assert response.status_code == 200
response_json = json.loads(response.content.decode('utf-8'))
assert CertificateStatuses.notpassing == response_json['add_status']
@@ -981,7 +979,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
with patch('capa.xqueue_interface.XQueueInterface.send_to_queue') as mock_queue:
mock_queue.return_value = (0, "Successfully queued")
with mock_passing_grade():
response = self.client.post(request_certificate_url, {'course_id': six.text_type(self.course.id)})
response = self.client.post(request_certificate_url, {'course_id': str(self.course.id)})
assert response.status_code == 200
response_json = json.loads(response.content.decode('utf-8'))
assert CertificateStatuses.generating == response_json['add_status']
@@ -998,15 +996,15 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
mock_get_course_run_details.return_value = self.mock_course_run_details
self._add_course_certificates(count=1, signatory_count=2)
self._create_custom_named_template(
'test_template_1_course', org_id=1, mode='honor', course_key=six.text_type(self.course.id),
'test_template_1_course', org_id=1, mode='honor', course_key=str(self.course.id),
)
self._create_custom_named_template(
'test_template_2_course', org_id=1, mode='verified', course_key=six.text_type(self.course.id),
'test_template_2_course', org_id=1, mode='verified', course_key=str(self.course.id),
)
self._create_custom_named_template('test_template_3_course', org_id=2, mode='honor')
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
@@ -1041,13 +1039,13 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
'test_template_2_course',
org_id=1,
mode='honor',
course_key=six.text_type(othercourse.id)
course_key=str(othercourse.id)
)
self._create_custom_named_template('test_template_3_course', org_id=1, mode='verified') # wrong mode
self._create_custom_named_template('test_template_4_course', org_id=2, mode='honor') # wrong org
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
@@ -1071,7 +1069,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._create_custom_named_template('test_template_3_course', org_id=2, mode=None) # wrong org
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
@@ -1096,7 +1094,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._create_custom_named_template('test_template_3_course', org_id=2, mode=mode) # wrong org
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
@@ -1104,7 +1102,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
mock_get_org_id.return_value = None
response = self.client.get(test_url)
assert response.status_code == 200
self.assertContains(response, u'mode: {}'.format(mode))
self.assertContains(response, f'mode: {mode}')
self.assertContains(response, 'course name: test_template_1_course')
# Templates With Language tests
@@ -1142,12 +1140,12 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
# Create an org_mode_and_coursekey template language=null
self._create_custom_named_template(
'test_null_lang_template', org_id=1, mode='honor', course_key=six.text_type(self.course.id), language=None,
'test_null_lang_template', org_id=1, mode='honor', course_key=str(self.course.id), language=None,
)
# Verify return template lang = null
response = self.client.get(test_url)
@@ -1159,7 +1157,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
'test_wrong_lang_template',
org_id=1,
mode='honor',
course_key=six.text_type(self.course.id),
course_key=str(self.course.id),
language=wrong_language,
)
# Verify returns null lang template
@@ -1172,7 +1170,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
'test_all_languages_template',
org_id=1,
mode='honor',
course_key=six.text_type(self.course.id),
course_key=str(self.course.id),
language='',
)
# Verify returns null lang template
@@ -1185,7 +1183,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
'test_right_lang_template',
org_id=1,
mode='honor',
course_key=six.text_type(self.course.id),
course_key=str(self.course.id),
language=right_language,
)
# verify return right_language template
@@ -1222,7 +1220,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
# Create a org and mode template language=null
@@ -1280,7 +1278,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._add_course_certificates(count=1, signatory_count=2)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
# Create a org template language=null
@@ -1339,7 +1337,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
# Create a mode template language=null
@@ -1401,7 +1399,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
# Create a mode template language=null
@@ -1458,7 +1456,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._create_custom_template_with_hours_of_effort(org_id=1, language=None)
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
response = self.client.get(test_url)
@@ -1484,21 +1482,21 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
}):
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
with patch.dict("django.conf.settings.SOCIAL_SHARING_SETTINGS", {
"CERTIFICATE_TWITTER": True,
"CERTIFICATE_TWITTER_TEXT": u"nền tảng học tập"
"CERTIFICATE_TWITTER_TEXT": "nền tảng học tập"
}):
with patch('django.http.HttpRequest.build_absolute_uri') as mock_abs_uri:
mock_abs_uri.return_value = '='.join(['http://localhost/?param', u'é'])
mock_abs_uri.return_value = '='.join(['http://localhost/?param', 'é'])
with patch('lms.djangoapps.certificates.api.get_course_organization_id') as mock_get_org_id:
mock_get_org_id.return_value = None
response = self.client.get(test_url)
assert response.status_code == 200
if custom_certs_enabled:
self.assertContains(response, u'mode: {}'.format(mode))
self.assertContains(response, f'mode: {mode}')
else:
self.assertContains(response, "Tweet this Accomplishment")
self.assertContains(response, 'https://twitter.com/intent/tweet')
@@ -1514,7 +1512,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
self._create_custom_template(mode='honor')
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
@@ -1536,7 +1534,7 @@ class CertificatesViewsTests(CommonCertificatesTestCase, CacheIsolationTestCase)
mock_get_org_id.return_value = None
response = self.client.get(test_url)
self.assertContains(
response, u'<img class="custom-logo" src="{}certificate_template_assets/32/test_logo.png" />'.format(
response, '<img class="custom-logo" src="{}certificate_template_assets/32/test_logo.png" />'.format(
settings.MEDIA_URL
)
)
@@ -1554,7 +1552,7 @@ class CertificateEventTests(CommonCertificatesTestCase, EventTrackingTestCase):
self.recreate_tracker()
test_url = get_certificate_url(
user_id=self.user.id,
course_id=six.text_type(self.course.id),
course_id=str(self.course.id),
uuid=self.cert.verify_uuid
)
response = self.client.get(test_url)
@@ -1570,10 +1568,10 @@ class CertificateEventTests(CommonCertificatesTestCase, EventTrackingTestCase):
assert_event_matches(
{
'user_id': self.user.id,
'certificate_id': six.text_type(self.cert.verify_uuid),
'certificate_id': str(self.cert.verify_uuid),
'enrollment_mode': self.cert.mode,
'certificate_url': test_url,
'course_id': six.text_type(self.course.id),
'course_id': str(self.course.id),
'social_network': CertificateSocialNetworks.linkedin
},
actual_event['data']
@@ -1588,7 +1586,7 @@ class CertificateEventTests(CommonCertificatesTestCase, EventTrackingTestCase):
course_id=self.course_id,
uuid=self.cert.verify_uuid
)
test_url = '{}?evidence_visit=1'.format(cert_url)
test_url = f'{cert_url}?evidence_visit=1'
self.recreate_tracker()
badge_class = get_completion_badge(self.course_id, self.user)
assertion = BadgeAssertionFactory.create(
@@ -1615,10 +1613,10 @@ class CertificateEventTests(CommonCertificatesTestCase, EventTrackingTestCase):
'data': {
'course_id': 'testorg/run1/refundable_course',
'assertion_id': assertion.id,
'badge_generator': u'DummyBackend',
'badge_name': u'refundable course',
'issuing_component': u'',
'badge_slug': u'testorgrun1refundable_course_honor_432f164',
'badge_generator': 'DummyBackend',
'badge_name': 'refundable course',
'issuing_component': '',
'badge_slug': 'testorgrun1refundable_course_honor_432f164',
'assertion_json_url': 'http://www.example.com/assertion.json',
'assertion_image_url': 'http://www.example.com/image.png',
'user_id': self.user.id,

View File

@@ -4,15 +4,12 @@ Tests for the certificates models.
from datetime import datetime, timedelta
from unittest.mock import patch
import six
from ddt import data, ddt, unpack
from django.conf import settings
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import patch
from pytz import UTC
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from common.djangoapps.student.models import CourseEnrollment
from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory
@@ -25,6 +22,8 @@ from lms.djangoapps.certificates.models import (
certificate_status_for_student
)
from lms.djangoapps.certificates.tests.factories import GeneratedCertificateFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
@ddt
@@ -198,9 +197,9 @@ class CertificatesModelTest(ModuleStoreTestCase, MilestonesTestCaseMixin):
course = CourseFactory.create(org='edx', number='998', display_name='Test Course')
pre_requisite_course = CourseFactory.create(org='edx', number='999', display_name='Pre requisite Course')
# set pre-requisite course
set_prerequisite_courses(course.id, [six.text_type(pre_requisite_course.id)])
set_prerequisite_courses(course.id, [str(pre_requisite_course.id)])
# get milestones collected by user before completing the pre-requisite course
completed_milestones = milestones_achieved_by_user(student, six.text_type(pre_requisite_course.id))
completed_milestones = milestones_achieved_by_user(student, str(pre_requisite_course.id))
assert len(completed_milestones) == 0
GeneratedCertificateFactory.create(
@@ -210,9 +209,9 @@ class CertificatesModelTest(ModuleStoreTestCase, MilestonesTestCaseMixin):
mode='verified'
)
# get milestones collected by user after user has completed the pre-requisite course
completed_milestones = milestones_achieved_by_user(student, six.text_type(pre_requisite_course.id))
completed_milestones = milestones_achieved_by_user(student, str(pre_requisite_course.id))
assert len(completed_milestones) == 1
assert completed_milestones[0]['namespace'] == six.text_type(pre_requisite_course.id)
assert completed_milestones[0]['namespace'] == str(pre_requisite_course.id)
@patch.dict(settings.FEATURES, {'ENABLE_OPENBADGES': True})
@patch('lms.djangoapps.badges.backends.badgr.BadgrBackend', spec=True)