From 81bab4d01a3db9f0561a77232304568a5d09e896 Mon Sep 17 00:00:00 2001 From: Awais Qureshi <awais.qureshi@arbisoft.com> Date: Thu, 18 Mar 2021 11:34:46 +0500 Subject: [PATCH] Pyupgrade in common/djangoapps/third-party-auth/tests. --- .../tests/test_saml_configuration.py | 4 +- .../saml_configuration/views.py | 2 +- .../tests/test_samlproviderconfig.py | 2 +- .../samlproviderconfig/views.py | 4 +- .../tests/test_samlproviderdata.py | 2 +- .../samlproviderdata/views.py | 2 +- .../third_party_auth/tests/factories.py | 4 +- .../third_party_auth/tests/samlutils.py | 4 +- .../third_party_auth/tests/specs/base.py | 25 +++++------ .../tests/specs/test_azuread.py | 2 +- .../tests/specs/test_generic.py | 2 +- .../tests/specs/test_google.py | 6 +-- .../tests/specs/test_linkedin.py | 2 +- .../third_party_auth/tests/specs/test_lti.py | 4 +- .../tests/specs/test_testshib.py | 25 +++++------ .../tests/specs/test_twitter.py | 4 +- .../third_party_auth/tests/test_admin.py | 4 +- .../third_party_auth/tests/test_decorators.py | 2 +- .../tests/test_identityserver3.py | 2 +- .../third_party_auth/tests/test_middleware.py | 2 +- .../third_party_auth/tests/test_pipeline.py | 6 +-- .../tests/test_pipeline_integration.py | 41 ++++++++++--------- .../third_party_auth/tests/test_provider.py | 7 ++-- .../third_party_auth/tests/test_saml.py | 6 +-- .../third_party_auth/tests/test_settings.py | 4 +- .../third_party_auth/tests/test_views.py | 6 +-- .../third_party_auth/tests/testutil.py | 30 +++++++------- .../third_party_auth/tests/utils.py | 10 ++--- 28 files changed, 109 insertions(+), 105 deletions(-) diff --git a/common/djangoapps/third_party_auth/saml_configuration/tests/test_saml_configuration.py b/common/djangoapps/third_party_auth/saml_configuration/tests/test_saml_configuration.py index 540d73ad869..4e991041440 100644 --- a/common/djangoapps/third_party_auth/saml_configuration/tests/test_saml_configuration.py +++ b/common/djangoapps/third_party_auth/saml_configuration/tests/test_saml_configuration.py @@ -51,7 +51,7 @@ class SAMLConfigurationTests(APITestCase): """ @classmethod def setUpTestData(cls): - super(SAMLConfigurationTests, cls).setUpTestData() + super().setUpTestData() cls.user = User.objects.create_user(username='testuser', password=TEST_PASSWORD) cls.site, _ = Site.objects.get_or_create(domain='example.com') for config in SAML_CONFIGURATIONS: @@ -74,7 +74,7 @@ class SAMLConfigurationTests(APITestCase): ) def setUp(self): - super(SAMLConfigurationTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.client.login(username=self.user.username, password=TEST_PASSWORD) def test_get_saml_configurations_successful(self): diff --git a/common/djangoapps/third_party_auth/saml_configuration/views.py b/common/djangoapps/third_party_auth/saml_configuration/views.py index 20cbbc5feda..093717b2962 100644 --- a/common/djangoapps/third_party_auth/saml_configuration/views.py +++ b/common/djangoapps/third_party_auth/saml_configuration/views.py @@ -10,7 +10,7 @@ from ..models import SAMLConfiguration from .serializers import SAMLConfigurationSerializer -class SAMLConfigurationMixin(object): +class SAMLConfigurationMixin: authentication_classes = (JwtAuthentication, SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) serializer_class = SAMLConfigurationSerializer diff --git a/common/djangoapps/third_party_auth/samlproviderconfig/tests/test_samlproviderconfig.py b/common/djangoapps/third_party_auth/samlproviderconfig/tests/test_samlproviderconfig.py index 29ccf53bb10..f41ae253ad9 100644 --- a/common/djangoapps/third_party_auth/samlproviderconfig/tests/test_samlproviderconfig.py +++ b/common/djangoapps/third_party_auth/samlproviderconfig/tests/test_samlproviderconfig.py @@ -48,7 +48,7 @@ class SAMLProviderConfigTests(APITestCase): """ @classmethod def setUpTestData(cls): - super(SAMLProviderConfigTests, cls).setUpTestData() + super().setUpTestData() cls.user = User.objects.create_user(username='testuser', password='testpwd') cls.site, _ = Site.objects.get_or_create(domain='example.com') cls.enterprise_customer = EnterpriseCustomer.objects.create( diff --git a/common/djangoapps/third_party_auth/samlproviderconfig/views.py b/common/djangoapps/third_party_auth/samlproviderconfig/views.py index 050d655f216..a8cdb40d7de 100644 --- a/common/djangoapps/third_party_auth/samlproviderconfig/views.py +++ b/common/djangoapps/third_party_auth/samlproviderconfig/views.py @@ -18,7 +18,7 @@ from .serializers import SAMLProviderConfigSerializer from ..utils import convert_saml_slug_provider_id -class SAMLProviderMixin(object): +class SAMLProviderMixin: authentication_classes = [JwtAuthentication, SessionAuthentication] permission_classes = [permissions.IsAuthenticated] serializer_class = SAMLProviderConfigSerializer @@ -95,7 +95,7 @@ class SAMLProviderConfigViewSet(PermissionRequiredMixin, SAMLProviderMixin, view try: enterprise_customer = EnterpriseCustomer.objects.get(pk=customer_uuid) except EnterpriseCustomer.DoesNotExist: - raise ValidationError('Enterprise customer not found at uuid: {}'.format(customer_uuid)) # lint-amnesty, pylint: disable=raise-missing-from + raise ValidationError(f'Enterprise customer not found at uuid: {customer_uuid}') # lint-amnesty, pylint: disable=raise-missing-from # Create the samlproviderconfig model first serializer = self.get_serializer(data=request.data) diff --git a/common/djangoapps/third_party_auth/samlproviderdata/tests/test_samlproviderdata.py b/common/djangoapps/third_party_auth/samlproviderdata/tests/test_samlproviderdata.py index 8208d8ae883..e9b593ff79b 100644 --- a/common/djangoapps/third_party_auth/samlproviderdata/tests/test_samlproviderdata.py +++ b/common/djangoapps/third_party_auth/samlproviderdata/tests/test_samlproviderdata.py @@ -48,7 +48,7 @@ class SAMLProviderDataTests(APITestCase): """ @classmethod def setUpTestData(cls): - super(SAMLProviderDataTests, cls).setUpTestData() + super().setUpTestData() cls.user = User.objects.create_user(username='testuser', password='testpwd') cls.site, _ = Site.objects.get_or_create(domain='example.com') cls.enterprise_customer = EnterpriseCustomer.objects.create( diff --git a/common/djangoapps/third_party_auth/samlproviderdata/views.py b/common/djangoapps/third_party_auth/samlproviderdata/views.py index e6360189828..43c24db8128 100644 --- a/common/djangoapps/third_party_auth/samlproviderdata/views.py +++ b/common/djangoapps/third_party_auth/samlproviderdata/views.py @@ -17,7 +17,7 @@ from ..models import SAMLProviderConfig, SAMLProviderData from .serializers import SAMLProviderDataSerializer -class SAMLProviderDataMixin(object): +class SAMLProviderDataMixin: authentication_classes = [JwtAuthentication, SessionAuthentication] permission_classes = [permissions.IsAuthenticated] serializer_class = SAMLProviderDataSerializer diff --git a/common/djangoapps/third_party_auth/tests/factories.py b/common/djangoapps/third_party_auth/tests/factories.py index df3ecd9848d..bc20502cb01 100644 --- a/common/djangoapps/third_party_auth/tests/factories.py +++ b/common/djangoapps/third_party_auth/tests/factories.py @@ -14,7 +14,7 @@ class SAMLConfigurationFactory(DjangoModelFactory): """ Factory or SAMLConfiguration model in third_party_auth app. """ - class Meta(object): + class Meta: model = SAMLConfiguration site = SubFactory(SiteFactory) @@ -25,7 +25,7 @@ class SAMLProviderConfigFactory(DjangoModelFactory): """ Factory or SAMLProviderConfig model in third_party_auth app. """ - class Meta(object): + class Meta: model = SAMLProviderConfig django_get_or_create = ('slug', 'metadata_source', "entity_id") diff --git a/common/djangoapps/third_party_auth/tests/samlutils.py b/common/djangoapps/third_party_auth/tests/samlutils.py index ff1617c264d..aa2428d297b 100644 --- a/common/djangoapps/third_party_auth/tests/samlutils.py +++ b/common/djangoapps/third_party_auth/tests/samlutils.py @@ -12,9 +12,9 @@ def _jwt_token_from_role_context_pairs(user, role_context_pairs): """ roles = [] for role, context in role_context_pairs: - role_data = '{role}'.format(role=role) + role_data = f'{role}' if context is not None: - role_data += ':{context}'.format(context=context) + role_data += f':{context}' roles.append(role_data) payload = generate_unversioned_payload(user) diff --git a/common/djangoapps/third_party_auth/tests/specs/base.py b/common/djangoapps/third_party_auth/tests/specs/base.py index 66ad493202a..aeadd6d37dd 100644 --- a/common/djangoapps/third_party_auth/tests/specs/base.py +++ b/common/djangoapps/third_party_auth/tests/specs/base.py @@ -6,9 +6,9 @@ Base integration test for provider implementations. import json import unittest from contextlib import contextmanager -import pytest +from unittest import mock -import mock +import pytest from django import test from django.conf import settings from django.contrib import auth @@ -40,7 +40,7 @@ def create_account(request): return RegistrationView().post(request) -class HelperMixin(object): +class HelperMixin: """ Contains helper methods for IntegrationTestMixin and IntegrationTest classes below. """ @@ -73,11 +73,11 @@ class HelperMixin(object): # Check that the correct provider was selected. self.assertContains( response, - u'"errorMessage": null' + '"errorMessage": null' ) self.assertContains( response, - u'"currentProvider": "{}"'.format(self.provider.name), + f'"currentProvider": "{self.provider.name}"', ) # Expect that each truthy value we've prepopulated the register form # with is actually present. @@ -122,7 +122,7 @@ class HelperMixin(object): assert 302 == response.status_code assert 'canceled' in location assert self.backend_name in location - assert location.startswith((expected_uri + '?')) + assert location.startswith(expected_uri + '?') def assert_json_failure_response_is_inactive_account(self, response): """Asserts failure on /login for inactive account looks right.""" @@ -186,8 +186,9 @@ class HelperMixin(object): assert 302 == response.status_code # NOTE: Ideally we should use assertRedirects(), however it errors out due to the hostname, testserver, # not being properly set. This may be an issue with the call made by PSA, but we are not certain. - assert response.get('Location').endswith((expected_redirect_url or - django_settings.SOCIAL_AUTH_LOGIN_REDIRECT_URL)) + assert response.get('Location').endswith( + expected_redirect_url or django_settings.SOCIAL_AUTH_LOGIN_REDIRECT_URL + ) def assert_redirect_to_login_looks_correct(self, response): """Asserts a response would redirect to /login.""" @@ -363,7 +364,7 @@ class IntegrationTestMixin(testutil.TestCase, test.TestCase, HelperMixin): USER_USERNAME = "override" def setUp(self): - super(IntegrationTestMixin, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.request_factory = test.RequestFactory() self.login_page_url = reverse('signin_user') @@ -533,7 +534,7 @@ class IntegrationTest(testutil.TestCase, test.TestCase, HelperMixin): """Abstract base class for provider integration tests.""" def setUp(self): - super(IntegrationTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.request_factory = test.RequestFactory() # Actual tests, executed once per child. @@ -796,11 +797,11 @@ class IntegrationTest(testutil.TestCase, test.TestCase, HelperMixin): def test_first_party_auth_trumps_third_party_auth_and_fails_when_credentials_bad(self): self.assert_first_party_auth_trumps_third_party_auth( - email='user@example.com', password=u'password', success=False) + email='user@example.com', password='password', success=False) def test_first_party_auth_trumps_third_party_auth_and_succeeds_when_credentials_good(self): self.assert_first_party_auth_trumps_third_party_auth( - email='user@example.com', password=u'password', success=True) + email='user@example.com', password='password', success=True) def test_pipeline_redirects_to_requested_url(self): requested_redirect_url = 'foo' # something different from '/dashboard' diff --git a/common/djangoapps/third_party_auth/tests/specs/test_azuread.py b/common/djangoapps/third_party_auth/tests/specs/test_azuread.py index e980b5da040..eeffc4afe76 100644 --- a/common/djangoapps/third_party_auth/tests/specs/test_azuread.py +++ b/common/djangoapps/third_party_auth/tests/specs/test_azuread.py @@ -8,7 +8,7 @@ class AzureADOauth2IntegrationTest(base.Oauth2IntegrationTest): # lint-amnesty, """Integration tests for Azure Active Directory / Microsoft Account provider.""" def setUp(self): - super(AzureADOauth2IntegrationTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.provider = self.configure_azure_ad_provider( enabled=True, visible=True, diff --git a/common/djangoapps/third_party_auth/tests/specs/test_generic.py b/common/djangoapps/third_party_auth/tests/specs/test_generic.py index f02ccd54d23..b9a41914e9e 100644 --- a/common/djangoapps/third_party_auth/tests/specs/test_generic.py +++ b/common/djangoapps/third_party_auth/tests/specs/test_generic.py @@ -20,7 +20,7 @@ class GenericIntegrationTest(IntegrationTestMixin, testutil.TestCase): USER_USERNAME = "Galactica1" def setUp(self): - super(GenericIntegrationTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.configure_dummy_provider(enabled=True, visible=True) def do_provider_login(self, provider_redirect_url): diff --git a/common/djangoapps/third_party_auth/tests/specs/test_google.py b/common/djangoapps/third_party_auth/tests/specs/test_google.py index c3cf331c92f..c74b78d1c19 100644 --- a/common/djangoapps/third_party_auth/tests/specs/test_google.py +++ b/common/djangoapps/third_party_auth/tests/specs/test_google.py @@ -5,10 +5,10 @@ import base64 import hashlib import hmac import json +from unittest.mock import patch from django.conf import settings from django.urls import reverse -from mock import patch from social_core.exceptions import AuthException from common.djangoapps.student.tests.factories import UserFactory @@ -20,7 +20,7 @@ class GoogleOauth2IntegrationTest(base.Oauth2IntegrationTest): # lint-amnesty, """Integration tests for provider.GoogleOauth2.""" def setUp(self): - super(GoogleOauth2IntegrationTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.provider = self.configure_google_provider( enabled=True, visible=True, @@ -50,7 +50,7 @@ class GoogleOauth2IntegrationTest(base.Oauth2IntegrationTest): # lint-amnesty, return self.get_response_data().get('email').split('@')[0] def assert_redirect_to_provider_looks_correct(self, response): - super(GoogleOauth2IntegrationTest, self).assert_redirect_to_provider_looks_correct(response) # lint-amnesty, pylint: disable=super-with-arguments + super().assert_redirect_to_provider_looks_correct(response) assert 'google.com' in response['Location'] def test_custom_form(self): diff --git a/common/djangoapps/third_party_auth/tests/specs/test_linkedin.py b/common/djangoapps/third_party_auth/tests/specs/test_linkedin.py index 9a48ac0f59c..fd9ce1da5ff 100644 --- a/common/djangoapps/third_party_auth/tests/specs/test_linkedin.py +++ b/common/djangoapps/third_party_auth/tests/specs/test_linkedin.py @@ -17,7 +17,7 @@ class LinkedInOauth2IntegrationTest(base.Oauth2IntegrationTest): # lint-amnesty """Integration tests for provider.LinkedInOauth2.""" def setUp(self): - super(LinkedInOauth2IntegrationTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.provider = self.configure_linkedin_provider( enabled=True, visible=True, diff --git a/common/djangoapps/third_party_auth/tests/specs/test_lti.py b/common/djangoapps/third_party_auth/tests/specs/test_lti.py index adfc070f7fb..0c505bf80ab 100644 --- a/common/djangoapps/third_party_auth/tests/specs/test_lti.py +++ b/common/djangoapps/third_party_auth/tests/specs/test_lti.py @@ -30,10 +30,10 @@ class IntegrationTestLTI(testutil.TestCase): """ def setUp(self): - super(IntegrationTestLTI, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.hostname = 'testserver' self.client.defaults['SERVER_NAME'] = self.hostname - self.url_prefix = 'http://{}'.format(self.hostname) + self.url_prefix = f'http://{self.hostname}' self.configure_lti_provider( name='Other Tool Consumer 1', enabled=True, lti_consumer_key='other1', diff --git a/common/djangoapps/third_party_auth/tests/specs/test_testshib.py b/common/djangoapps/third_party_auth/tests/specs/test_testshib.py index 30c8c7c3914..1589571e5a4 100644 --- a/common/djangoapps/third_party_auth/tests/specs/test_testshib.py +++ b/common/djangoapps/third_party_auth/tests/specs/test_testshib.py @@ -8,26 +8,27 @@ import json import logging import os from unittest import skip +from unittest.mock import MagicMock, patch import ddt import httpretty from django.conf import settings from django.contrib import auth +from enterprise.models import EnterpriseCustomerIdentityProvider, EnterpriseCustomerUser from freezegun import freeze_time -from mock import MagicMock, patch from social_core import actions from social_django import views as social_views from social_django.models import UserSocialAuth from testfixtures import LogCapture -from enterprise.models import EnterpriseCustomerIdentityProvider, EnterpriseCustomerUser -from openedx.core.djangoapps.user_authn.views.login import login_user -from openedx.core.djangoapps.user_api.accounts.settings_views import account_settings_context -from openedx.features.enterprise_support.tests.factories import EnterpriseCustomerFactory from common.djangoapps.third_party_auth import pipeline -from common.djangoapps.third_party_auth.saml import SapSuccessFactorsIdentityProvider, log as saml_log +from common.djangoapps.third_party_auth.saml import SapSuccessFactorsIdentityProvider +from common.djangoapps.third_party_auth.saml import log as saml_log from common.djangoapps.third_party_auth.tasks import fetch_saml_metadata from common.djangoapps.third_party_auth.tests import testutil, utils +from openedx.core.djangoapps.user_api.accounts.settings_views import account_settings_context +from openedx.core.djangoapps.user_authn.views.login import login_user +from openedx.features.enterprise_support.tests.factories import EnterpriseCustomerFactory from .base import IntegrationTestMixin @@ -37,7 +38,7 @@ TESTSHIB_METADATA_URL_WITH_CACHE_DURATION = 'https://mock.testshib.org/metadata/ TESTSHIB_SSO_URL = 'https://idp.testshib.org/idp/profile/SAML2/Redirect/SSO' -class SamlIntegrationTestUtilities(object): +class SamlIntegrationTestUtilities: """ Class contains methods particular to SAML integration testing so that they can be separated out from the actual test methods. @@ -52,7 +53,7 @@ class SamlIntegrationTestUtilities(object): USER_USERNAME = "myself" def setUp(self): - super(SamlIntegrationTestUtilities, self).setUp() # lint-amnesty, pylint: disable=no-member, super-with-arguments + super().setUp() # lint-amnesty, pylint: disable=no-member, super-with-arguments self.enable_saml( # lint-amnesty, pylint: disable=no-member private_key=self._get_private_key(), # lint-amnesty, pylint: disable=no-member public_key=self._get_public_key(), # lint-amnesty, pylint: disable=no-member @@ -156,7 +157,7 @@ class TestShibIntegrationTest(SamlIntegrationTestUtilities, IntegrationTestMixin 'id': 'id_value', 'firstName': 'firstName_value', 'idp_name': 'testshib', - 'attributes': {u'urn:oid:0.9.2342.19200300.100.1.1': [u'myself'], 'name_id': '1'}, + 'attributes': {'urn:oid:0.9.2342.19200300.100.1.1': ['myself'], 'name_id': '1'}, 'session_index': '1', } @@ -307,7 +308,7 @@ class TestShibIntegrationTest(SamlIntegrationTestUtilities, IntegrationTestMixin expected_next_url = "/dashboard" (msg, action_type, idp_name, request_data, next_url, xml), _kwargs = mock_log.call_args_list[0] - assert msg.startswith(u'SAML login %s') + assert msg.startswith('SAML login %s') assert action_type == 'request' assert idp_name == self.PROVIDER_IDP_SLUG self.assertDictContainsSubset( @@ -318,7 +319,7 @@ class TestShibIntegrationTest(SamlIntegrationTestUtilities, IntegrationTestMixin assert '<samlp:AuthnRequest' in xml (msg, action_type, idp_name, response_data, next_url, xml), _kwargs = mock_log.call_args_list[1] - assert msg.startswith(u'SAML login %s') + assert msg.startswith('SAML login %s') assert action_type == 'response' assert idp_name == self.PROVIDER_IDP_SLUG self.assertDictContainsSubset({"RelayState": idp_name}, response_data) @@ -387,7 +388,7 @@ class SuccessFactorsIntegrationTest(SamlIntegrationTestUtilities, IntegrationTes """ Mock out HTTP calls to various endpoints using httpretty. """ - super(SuccessFactorsIntegrationTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() # Mock the call to the SAP SuccessFactors assertion endpoint SAPSF_ASSERTION_URL = 'http://successfactors.com/oauth/idp' diff --git a/common/djangoapps/third_party_auth/tests/specs/test_twitter.py b/common/djangoapps/third_party_auth/tests/specs/test_twitter.py index c602c11a025..e592a624198 100644 --- a/common/djangoapps/third_party_auth/tests/specs/test_twitter.py +++ b/common/djangoapps/third_party_auth/tests/specs/test_twitter.py @@ -3,7 +3,7 @@ Separate integration test for Twitter which is an OAuth1 provider. """ -from mock import patch +from unittest.mock import patch from common.djangoapps.third_party_auth.tests.specs import base @@ -11,7 +11,7 @@ class TwitterIntegrationTest(base.Oauth2IntegrationTest): # lint-amnesty, pylin """Integration tests for Twitter backend.""" def setUp(self): - super(TwitterIntegrationTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.provider = self.configure_twitter_provider( enabled=True, visible=True, diff --git a/common/djangoapps/third_party_auth/tests/test_admin.py b/common/djangoapps/third_party_auth/tests/test_admin.py index 7099911e553..82a93e8db88 100644 --- a/common/djangoapps/third_party_auth/tests/test_admin.py +++ b/common/djangoapps/third_party_auth/tests/test_admin.py @@ -58,8 +58,8 @@ class Oauth2ProviderConfigAdminTest(testutil.TestCase): # Edit the provider via the admin edit link admin = OAuth2ProviderConfigAdmin(provider1, AdminSite()) - update_url = reverse('admin:{}_{}_add'.format(admin.model._meta.app_label, admin.model._meta.model_name)) - update_url += "?source={}".format(provider1.pk) + update_url = reverse(f'admin:{admin.model._meta.app_label}_{admin.model._meta.model_name}_add') + update_url += f"?source={provider1.pk}" # Remove the icon_image from the POST data, to simulate unchanged icon_image post_data = models.model_to_dict(provider1) diff --git a/common/djangoapps/third_party_auth/tests/test_decorators.py b/common/djangoapps/third_party_auth/tests/test_decorators.py index 0a2c732c4d2..b18f0ef0c68 100644 --- a/common/djangoapps/third_party_auth/tests/test_decorators.py +++ b/common/djangoapps/third_party_auth/tests/test_decorators.py @@ -23,7 +23,7 @@ class TestXFrameWhitelistDecorator(TestCase): """ Test the xframe_allow_whitelisted decorator. """ def setUp(self): - super(TestXFrameWhitelistDecorator, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.configure_lti_provider(name='Test', lti_hostname='localhost', lti_consumer_key='test_key', enabled=True) self.factory = RequestFactory() diff --git a/common/djangoapps/third_party_auth/tests/test_identityserver3.py b/common/djangoapps/third_party_auth/tests/test_identityserver3.py index 40796070d2c..c5854626aa9 100644 --- a/common/djangoapps/third_party_auth/tests/test_identityserver3.py +++ b/common/djangoapps/third_party_auth/tests/test_identityserver3.py @@ -16,7 +16,7 @@ class IdentityServer3Test(testutil.TestCase): """ def setUp(self): - super(IdentityServer3Test, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.id3_instance = IdentityServer3() self.response = { "sub": "020cadec-919a-4b06-845e-57915bf76826", diff --git a/common/djangoapps/third_party_auth/tests/test_middleware.py b/common/djangoapps/third_party_auth/tests/test_middleware.py index 0a4caa7ec58..ba026f62c4e 100644 --- a/common/djangoapps/third_party_auth/tests/test_middleware.py +++ b/common/djangoapps/third_party_auth/tests/test_middleware.py @@ -3,7 +3,7 @@ Tests for third party auth middleware """ -import mock +from unittest import mock from django.contrib.messages.middleware import MessageMiddleware from django.http import HttpResponse from django.test.client import RequestFactory diff --git a/common/djangoapps/third_party_auth/tests/test_pipeline.py b/common/djangoapps/third_party_auth/tests/test_pipeline.py index 9c3c265de95..b45ddfcd241 100644 --- a/common/djangoapps/third_party_auth/tests/test_pipeline.py +++ b/common/djangoapps/third_party_auth/tests/test_pipeline.py @@ -2,9 +2,9 @@ import json +from unittest import mock import ddt -import mock from common.djangoapps.third_party_auth import pipeline from common.djangoapps.third_party_auth.tests import testutil @@ -36,7 +36,7 @@ class ProviderUserStateTestCase(testutil.TestCase): self.enable_saml() idp_slug = "test" idp_config = {"logout_url": "http://example.com/logout"} - getattr(self, 'configure_{idp_type}_provider'.format(idp_type=idp_type))( + getattr(self, f'configure_{idp_type}_provider')( enabled=True, name="Test Provider", slug=idp_slug, @@ -62,7 +62,7 @@ class PipelineOverridesTest(SamlIntegrationTestUtilities, IntegrationTestMixin, """ def setUp(self): - super(PipelineOverridesTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.enable_saml() self.provider = self.configure_saml_provider( enabled=True, diff --git a/common/djangoapps/third_party_auth/tests/test_pipeline_integration.py b/common/djangoapps/third_party_auth/tests/test_pipeline_integration.py index 516fc501a40..13509797466 100644 --- a/common/djangoapps/third_party_auth/tests/test_pipeline_integration.py +++ b/common/djangoapps/third_party_auth/tests/test_pipeline_integration.py @@ -2,21 +2,22 @@ import datetime -import pytest +from unittest import mock import ddt -import mock +import pytest import pytz from django import test from django.contrib.auth import models from django.core import mail from social_django import models as social_models -from lms.djangoapps.verify_student.models import SSOVerification from common.djangoapps.student.tests.factories import UserFactory from common.djangoapps.third_party_auth import pipeline, provider from common.djangoapps.third_party_auth.tests import testutil from common.djangoapps.third_party_auth.tests.utils import skip_unless_thirdpartyauth +from lms.djangoapps.verify_student.models import SSOVerification + # Get Django User model by reference from python-social-auth. Not a type # constant, pylint. User = social_models.DjangoStorage.user.user_model() # pylint: disable=invalid-name @@ -27,7 +28,7 @@ class TestCase(testutil.TestCase, test.TestCase): """Base test case.""" def setUp(self): - super(TestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.enabled_provider = self.configure_google_provider(enabled=True) @@ -35,7 +36,7 @@ class GetAuthenticatedUserTestCase(TestCase): """Tests for get_authenticated_user.""" def setUp(self): - super(GetAuthenticatedUserTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = social_models.DjangoStorage.user.create_user(username='username', password='password') def get_by_username(self, username): @@ -75,7 +76,7 @@ class GetProviderUserStatesTestCase(TestCase): """Tests generation of ProviderUserStates.""" def setUp(self): - super(GetProviderUserStatesTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.configure_google_provider(enabled=False) self.user = social_models.DjangoStorage.user.create_user(username='username', password='password') @@ -214,7 +215,7 @@ class TestPipelineUtilityFunctions(TestCase): Test some of the isolated utility functions in the pipeline """ def setUp(self): - super(TestPipelineUtilityFunctions, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = social_models.DjangoStorage.user.create_user(username='username', password='password') self.social_auth = social_models.UserSocialAuth.objects.create( user=self.user, @@ -302,7 +303,7 @@ class EnsureUserInformationTestCase(TestCase): """Tests ensuring that we have the necessary user information to proceed with the pipeline.""" def setUp(self): - super(EnsureUserInformationTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = social_models.DjangoStorage.user.create_user( username='username', password='password', @@ -382,15 +383,15 @@ class UserDetailsForceSyncTestCase(TestCase): """Tests to ensure learner profile data is properly synced if the provider requires it.""" def setUp(self): - super(UserDetailsForceSyncTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory.create() self.old_email = self.user.email self.old_username = self.user.username self.old_fullname = self.user.profile.name self.details = { - 'email': u'new+{}'.format(self.user.email), - 'username': u'new_{}'.format(self.user.username), - 'fullname': u'Grown Up {}'.format(self.user.profile.name), + 'email': f'new+{self.user.email}', + 'username': f'new_{self.user.username}', + 'fullname': f'Grown Up {self.user.profile.name}', 'country': 'PK', 'non_existing_field': 'value', } @@ -418,8 +419,8 @@ class UserDetailsForceSyncTestCase(TestCase): # User now has updated information in the DB. user = User.objects.get() - assert user.email == 'new+{}'.format(self.old_email) - assert user.profile.name == u'Grown Up {}'.format(self.old_fullname) + assert user.email == f'new+{self.old_email}' + assert user.profile.name == f'Grown Up {self.old_fullname}' assert user.profile.country == 'PK' # Now verify that username field is not updated @@ -432,7 +433,7 @@ class UserDetailsForceSyncTestCase(TestCase): The user details were attempted to be synced but the incoming email already exists for another account. """ # Create a user with an email that conflicts with the incoming value. - UserFactory.create(email='new+{}'.format(self.old_email)) + UserFactory.create(email=f'new+{self.old_email}') # Begin the pipeline. pipeline.user_details_force_sync( @@ -445,7 +446,7 @@ class UserDetailsForceSyncTestCase(TestCase): # The email is not changed, but everything else is. user = User.objects.get(pk=self.user.pk) assert user.email == self.old_email - assert user.profile.name == u'Grown Up {}'.format(self.old_fullname) + assert user.profile.name == f'Grown Up {self.old_fullname}' assert user.profile.country == 'PK' # Now verify that username field is not updated @@ -461,7 +462,7 @@ class UserDetailsForceSyncTestCase(TestCase): An email should still be sent in this case. """ # Create a user with an email that conflicts with the incoming value. - UserFactory.create(username='new_{}'.format(self.old_username)) + UserFactory.create(username=f'new_{self.old_username}') # Begin the pipeline. pipeline.user_details_force_sync( @@ -473,9 +474,9 @@ class UserDetailsForceSyncTestCase(TestCase): # The username is not changed, but everything else is. user = User.objects.get(pk=self.user.pk) - assert user.email == 'new+{}'.format(self.old_email) + assert user.email == f'new+{self.old_email}' assert user.username == self.old_username - assert user.profile.name == u'Grown Up {}'.format(self.old_fullname) + assert user.profile.name == f'Grown Up {self.old_fullname}' assert user.profile.country == 'PK' # An email should still be sent because the email changed. @@ -486,7 +487,7 @@ class SetIDVerificationStatusTestCase(TestCase): """Tests to ensure SSO ID Verification for the user is set if the provider requires it.""" def setUp(self): - super(SetIDVerificationStatusTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory.create() self.provider_class_name = 'common.djangoapps.third_party_auth.models.SAMLProviderConfig' self.provider_slug = 'default' diff --git a/common/djangoapps/third_party_auth/tests/test_provider.py b/common/djangoapps/third_party_auth/tests/test_provider.py index 3c9d505c0ce..64e4e4e92fb 100644 --- a/common/djangoapps/third_party_auth/tests/test_provider.py +++ b/common/djangoapps/third_party_auth/tests/test_provider.py @@ -2,16 +2,17 @@ import re +from unittest.mock import Mock, patch from django.contrib.sites.models import Site -from django.db import connections, DEFAULT_DB_ALIAS +from django.db import DEFAULT_DB_ALIAS, connections from django.test.utils import CaptureQueriesContext -from mock import Mock, patch -from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration from common.djangoapps.third_party_auth import provider from common.djangoapps.third_party_auth.tests import testutil from common.djangoapps.third_party_auth.tests.utils import skip_unless_thirdpartyauth +from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration + SITE_DOMAIN_A = 'professionalx.example.com' SITE_DOMAIN_B = 'somethingelse.example.com' diff --git a/common/djangoapps/third_party_auth/tests/test_saml.py b/common/djangoapps/third_party_auth/tests/test_saml.py index f2532accb7b..9bb49aa52a1 100644 --- a/common/djangoapps/third_party_auth/tests/test_saml.py +++ b/common/djangoapps/third_party_auth/tests/test_saml.py @@ -3,7 +3,7 @@ Unit tests for third_party_auth SAML auth providers """ -import mock +from unittest import mock from common.djangoapps.third_party_auth.saml import EdXSAMLIdentityProvider, get_saml_idp_class from common.djangoapps.third_party_auth.tests.data.saml_identity_provider_mock_data import ( @@ -23,8 +23,8 @@ class TestEdXSAMLIdentityProvider(SAMLTestCase): error_mock = log_mock.error idp_class = get_saml_idp_class('fake_idp_class_option') error_mock.assert_called_once_with( - u'[THIRD_PARTY_AUTH] Invalid EdXSAMLIdentityProvider subclass--' - u'using EdXSAMLIdentityProvider base class. Provider: {provider}'.format(provider='fake_idp_class_option') + '[THIRD_PARTY_AUTH] Invalid EdXSAMLIdentityProvider subclass--' + 'using EdXSAMLIdentityProvider base class. Provider: {provider}'.format(provider='fake_idp_class_option') ) assert idp_class is EdXSAMLIdentityProvider diff --git a/common/djangoapps/third_party_auth/tests/test_settings.py b/common/djangoapps/third_party_auth/tests/test_settings.py index a56273759bc..accecca09ec 100644 --- a/common/djangoapps/third_party_auth/tests/test_settings.py +++ b/common/djangoapps/third_party_auth/tests/test_settings.py @@ -1,6 +1,6 @@ """Unit tests for settings.py.""" -from mock import patch +from unittest.mock import patch from common.djangoapps.third_party_auth import provider, settings from common.djangoapps.third_party_auth.tests import testutil from common.djangoapps.third_party_auth.tests.utils import skip_unless_thirdpartyauth @@ -29,7 +29,7 @@ class SettingsUnitTest(testutil.TestCase): # pylint: disable=no-member def setUp(self): - super(SettingsUnitTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.settings = testutil.FakeDjangoSettings(_SETTINGS_MAP) def test_apply_settings_adds_exception_middleware(self): diff --git a/common/djangoapps/third_party_auth/tests/test_views.py b/common/djangoapps/third_party_auth/tests/test_views.py index 44fe56a492c..31082022aac 100644 --- a/common/djangoapps/third_party_auth/tests/test_views.py +++ b/common/djangoapps/third_party_auth/tests/test_views.py @@ -47,9 +47,9 @@ class SAMLMetadataTest(SAMLTestCase): self.enable_saml() self.check_metadata_contacts( xml=self._fetch_metadata(), - tech_name=u"{} Support".format(settings.PLATFORM_NAME), + tech_name=f"{settings.PLATFORM_NAME} Support", tech_email="technical@example.com", - support_name=u"{} Support".format(settings.PLATFORM_NAME), + support_name=f"{settings.PLATFORM_NAME} Support", support_email="technical@example.com" ) @@ -165,7 +165,7 @@ class IdPRedirectViewTest(SAMLTestCase): Test IdPRedirectView. """ def setUp(self): - super(IdPRedirectViewTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.enable_saml() self.configure_saml_provider( diff --git a/common/djangoapps/third_party_auth/tests/testutil.py b/common/djangoapps/third_party_auth/tests/testutil.py index 756c01a19de..ec8b1e65069 100644 --- a/common/djangoapps/third_party_auth/tests/testutil.py +++ b/common/djangoapps/third_party_auth/tests/testutil.py @@ -7,17 +7,15 @@ Used by Django and non-Django tests; must not have Django deps. import os.path from contextlib import contextmanager +from unittest import mock import django.test -import mock import six from django.conf import settings from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.contrib.sites.models import Site from mako.template import Template from oauth2_provider.models import Application -from openedx.core.djangolib.testing.utils import CacheIsolationMixin -from openedx.core.storage import OverwriteStorage from common.djangoapps.third_party_auth.models import ( LTIProviderConfig, @@ -26,6 +24,8 @@ from common.djangoapps.third_party_auth.models import ( SAMLProviderConfig ) from common.djangoapps.third_party_auth.models import cache as config_cache +from openedx.core.djangolib.testing.utils import CacheIsolationMixin +from openedx.core.storage import OverwriteStorage AUTH_FEATURES_KEY = 'ENABLE_THIRD_PARTY_AUTH' AUTH_FEATURE_ENABLED = AUTH_FEATURES_KEY in settings.FEATURES @@ -43,16 +43,16 @@ def patch_mako_templates(): return mock.patch.multiple(Template, render_unicode=wrapped_render, render=wrapped_render) -class FakeDjangoSettings(object): +class FakeDjangoSettings: """A fake for Django settings.""" def __init__(self, mappings): """Initializes the fake from mappings dict.""" - for key, value in six.iteritems(mappings): + for key, value in mappings.items(): setattr(self, key, value) -class ThirdPartyAuthTestMixin(object): +class ThirdPartyAuthTestMixin: """ Helper methods useful for testing third party auth functionality """ def setUp(self, *args, **kwargs): @@ -64,11 +64,11 @@ class ThirdPartyAuthTestMixin(object): patch.start() self.addCleanup(patch.stop) - super(ThirdPartyAuthTestMixin, self).setUp(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments + super().setUp(*args, **kwargs) def tearDown(self): config_cache.clear() - super(ThirdPartyAuthTestMixin, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments + super().tearDown() def enable_saml(self, **kwargs): """ Enable SAML support (via SAMLConfiguration, not for any particular provider) """ @@ -184,12 +184,12 @@ class TestCase(ThirdPartyAuthTestMixin, CacheIsolationMixin, django.test.TestCas """Base class for auth test cases.""" def setUp(self): # pylint: disable=arguments-differ - super(TestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() # Explicitly set a server name that is compatible with all our providers: # (The SAML lib we use doesn't like the default 'testserver' as a domain) self.hostname = 'example.none' self.client.defaults['SERVER_NAME'] = self.hostname - self.url_prefix = 'http://{}'.format(self.hostname) + self.url_prefix = f'http://{self.hostname}' class SAMLTestCase(TestCase): @@ -199,12 +199,12 @@ class SAMLTestCase(TestCase): @classmethod def _get_public_key(cls, key_name='saml_key'): """ Get a public key for use in the test. """ - return cls.read_data_file('{}.pub'.format(key_name)) + return cls.read_data_file(f'{key_name}.pub') @classmethod def _get_private_key(cls, key_name='saml_key'): """ Get a private key for use in the test. """ - return cls.read_data_file('{}.key'.format(key_name)) + return cls.read_data_file(f'{key_name}.key') def enable_saml(self, **kwargs): """ Enable SAML support (via SAMLConfiguration, not for any particular provider) """ @@ -213,7 +213,7 @@ class SAMLTestCase(TestCase): if 'public_key' not in kwargs: kwargs['public_key'] = self._get_public_key() kwargs.setdefault('entity_id', "https://saml.example.none") - super(SAMLTestCase, self).enable_saml(**kwargs) # lint-amnesty, pylint: disable=super-with-arguments + super().enable_saml(**kwargs) @contextmanager @@ -282,8 +282,8 @@ def simulate_running_pipeline(pipeline_target, backend, email=None, fullname=Non if username is not None: pipeline_data["kwargs"]["username"] = username - pipeline_get = mock.patch("{pipeline}.get".format(pipeline=pipeline_target), spec=True) - pipeline_running = mock.patch("{pipeline}.running".format(pipeline=pipeline_target), spec=True) + pipeline_get = mock.patch(f"{pipeline_target}.get", spec=True) + pipeline_running = mock.patch(f"{pipeline_target}.running", spec=True) mock_get = pipeline_get.start() mock_running = pipeline_running.start() diff --git a/common/djangoapps/third_party_auth/tests/utils.py b/common/djangoapps/third_party_auth/tests/utils.py index ec3811e9f3c..29dc75e44fa 100644 --- a/common/djangoapps/third_party_auth/tests/utils.py +++ b/common/djangoapps/third_party_auth/tests/utils.py @@ -34,7 +34,7 @@ class ThirdPartyOAuthTestMixin(ThirdPartyAuthTestMixin): CREATE_USER = True def setUp(self): # lint-amnesty, pylint: disable=arguments-differ - super(ThirdPartyOAuthTestMixin, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() if self.CREATE_USER: self.user = UserFactory.create(password='secret') UserSocialAuth.objects.create(user=self.user, provider=self.BACKEND, uid=self.social_uid) @@ -45,7 +45,7 @@ class ThirdPartyOAuthTestMixin(ThirdPartyAuthTestMixin): self.configure_facebook_provider(enabled=True, visible=True) def tearDown(self): - super(ThirdPartyOAuthTestMixin, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments + super().tearDown() Partial.objects.all().delete() def _create_client(self): @@ -87,7 +87,7 @@ class ThirdPartyOAuthTestMixin(ThirdPartyAuthTestMixin): ) -class ThirdPartyOAuthTestMixinFacebook(object): +class ThirdPartyOAuthTestMixinFacebook: """Tests oauth with the Facebook backend""" BACKEND = "facebook" USER_URL = FacebookOAuth2.USER_DATA_URL.format(version=FACEBOOK_API_VERSION) @@ -95,7 +95,7 @@ class ThirdPartyOAuthTestMixinFacebook(object): UID_FIELD = "id" -class ThirdPartyOAuthTestMixinGoogle(object): +class ThirdPartyOAuthTestMixinGoogle: """Tests oauth with the Google backend""" BACKEND = "google-oauth2" USER_URL = "https://www.googleapis.com/oauth2/v3/userinfo" @@ -115,7 +115,7 @@ def read_and_pre_process_xml(file_name): Returns: (str): Pre Processed contents of the file. """ - with open(file_name, 'r') as xml_file: + with open(file_name) as xml_file: return xml_file.read().replace('\n', '') -- GitLab