From b06e13fabad9acecc9fdee6eec70870ce9cf1611 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20=C4=8Ciha=C5=99?= Date: Mon, 26 May 2025 16:06:25 +0200 Subject: [PATCH] chore: apply more ruff fixes --- .pre-commit-config.yaml | 2 +- manage.py | 0 pyproject.toml | 23 +++++++++++-- social_django/__init__.py | 2 +- social_django/admin.py | 8 +++-- social_django/context_processors.py | 10 +++--- social_django/fields.py | 5 +-- social_django/middleware.py | 10 ++++-- social_django/migrations/0001_initial.py | 9 ++---- .../migrations/0004_auto_20160423_0400.py | 4 +-- .../migrations/0013_migrate_extra_data.py | 19 ++++++----- social_django/models.py | 8 ++--- social_django/storage.py | 26 +++++++-------- social_django/strategy.py | 32 ++++++++++++------- social_django/urls.py | 2 +- social_django/utils.py | 5 +-- social_django/views.py | 18 ++++------- tests/settings.py | 4 +-- tests/test_admin.py | 18 +++++++---- tests/test_models.py | 31 +++++++++--------- tests/test_strategy.py | 2 +- tests/test_views.py | 17 ++++++---- 22 files changed, 144 insertions(+), 111 deletions(-) mode change 100644 => 100755 manage.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e7f50425..d7449a5e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -19,7 +19,7 @@ repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.11.11 hooks: - - id: ruff + - id: ruff-check args: [--fix, --exit-non-zero-on-fix] - id: ruff-format - repo: meta diff --git a/manage.py b/manage.py old mode 100644 new mode 100755 diff --git a/pyproject.toml b/pyproject.toml index e7d6f2d2..cf9b78c5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -104,15 +104,32 @@ exclude = [ "site" ] line-length = 120 -output-format = "github" [tool.ruff.lint] -ignore = [] -select = ["E", "F", "I", "PLC", "PLE", "UP"] +ignore = [ + "ANN", # TODO: Missing type annotations + "ARG001", # TODO: Unused function argument (mostly for API compatibility) + "ARG002", # TODO: Unused method argument (mostly for API compatibility) + "B026", # TODO: Star-arg unpacking after a keyword argument is strongly discouraged + "COM812", # CONFIG: incompatible with formatter + "D", # TODO: Missing documentation + "D203", # CONFIG: incompatible with D211 + "D212", # CONFIG: incompatible with D213 + "DJ008", # TODO: Model does not define `__str__` method + "FBT002", # TODO: Boolean default positional argument in function definition + "FBT003", # TODO: Boolean positional value in function call + "PT", # CONFIG: Not using pytest + "RUF012" # TODO: ClassVar type annotations +] +select = ["ALL"] [tool.ruff.lint.mccabe] max-complexity = 10 +[tool.ruff.lint.per-file-ignores] +"social_django/migrations/*.py" = ["RUF012"] +"tests/settings.py" = ["PTH"] + [tool.setuptools] packages = ["social_django"] diff --git a/social_django/__init__.py b/social_django/__init__.py index b14ac789..196cd7f2 100644 --- a/social_django/__init__.py +++ b/social_django/__init__.py @@ -23,4 +23,4 @@ def fake_init(self, strategy=None, *args, **kwargs): if not getattr(BaseAuth, "__init_patched", False): BaseAuth.__init__ = baseauth_init_workaround(BaseAuth.__init__) # type: ignore[method-assign] - BaseAuth.__init_patched = True # type: ignore[attr-defined] + BaseAuth.__init_patched = True # type: ignore[attr-defined] # noqa: SLF001 diff --git a/social_django/admin.py b/social_django/admin.py index 6ebc2460..f58bd43e 100644 --- a/social_django/admin.py +++ b/social_django/admin.py @@ -22,10 +22,12 @@ class UserSocialAuthOption(admin.ModelAdmin): def get_search_fields(self, request=None): search_fields = getattr(settings, setting_name("ADMIN_USER_SEARCH_FIELDS"), None) if search_fields is None: - _User = UserSocialAuth.user_model() - username = getattr(_User, "USERNAME_FIELD", None) or hasattr(_User, "username") and "username" or None + _User = UserSocialAuth.user_model() # noqa: N806 + username = getattr(_User, "USERNAME_FIELD", None) or (hasattr(_User, "username") and "username") or None fieldnames = ("first_name", "last_name", "email", username) - all_names = self._get_all_field_names(_User._meta) + all_names = self._get_all_field_names( + _User._meta # noqa: SLF001 + ) search_fields = [name for name in fieldnames if name and name in all_names] return ["user__" + name for name in search_fields] + getattr(settings, setting_name("ADMIN_SEARCH_FIELDS"), []) diff --git a/social_django/context_processors.py b/social_django/context_processors.py index 522b692b..eb8a3fb7 100644 --- a/social_django/context_processors.py +++ b/social_django/context_processors.py @@ -24,16 +24,18 @@ def __setitem__(self, name, value): def backends(request): - """Load Social Auth current user data to context under the key 'backends'. - Will return the output of social_core.backends.utils.user_backends_data.""" + """ + Load Social Auth current user data to context under the key 'backends'. + Will return the output of social_core.backends.utils.user_backends_data. + """ return {"backends": LazyDict(lambda: user_backends_data(request.user, settings.AUTHENTICATION_BACKENDS, Storage))} def login_redirect(request): """Load current redirect to context.""" try: - value = ( - request.method == "POST" and request.POST.get(REDIRECT_FIELD_NAME) or request.GET.get(REDIRECT_FIELD_NAME) + value = (request.method == "POST" and request.POST.get(REDIRECT_FIELD_NAME)) or request.GET.get( + REDIRECT_FIELD_NAME ) except MultiPartParserError: # request POST may be malformed diff --git a/social_django/fields.py b/social_django/fields.py index a87024af..303c42c9 100644 --- a/social_django/fields.py +++ b/social_django/fields.py @@ -8,10 +8,7 @@ POSTGRES_JSONFIELD = getattr(settings, setting_name("POSTGRES_JSONFIELD"), False) -if POSTGRES_JSONFIELD: - JSONFIELD_ENABLED = True -else: - JSONFIELD_ENABLED = getattr(settings, setting_name("JSONFIELD_ENABLED"), False) +JSONFIELD_ENABLED = True if POSTGRES_JSONFIELD else getattr(settings, setting_name("JSONFIELD_ENABLED"), False) if JSONFIELD_ENABLED: JSONFIELD_CUSTOM = getattr(settings, setting_name("JSONFIELD_CUSTOM"), None) diff --git a/social_django/middleware.py b/social_django/middleware.py index 32aeaed6..95ed2cf6 100644 --- a/social_django/middleware.py +++ b/social_django/middleware.py @@ -10,7 +10,8 @@ class SocialAuthExceptionMiddleware: - """Middleware that handles Social Auth AuthExceptions by providing the user + """ + Middleware that handles Social Auth AuthExceptions by providing the user with a message, logging an error, and redirecting to some next location. By default, the exception message itself is sent to the user and they are @@ -30,7 +31,7 @@ def __call__(self, request): def process_exception(self, request, exception): strategy = getattr(request, "social_strategy", None) if strategy is None or self.raise_exception(request, exception): - return + return None if isinstance(exception, SocialAuthBaseException): backend = getattr(request, "backend", None) @@ -45,17 +46,20 @@ def process_exception(self, request, exception): messages.error(request, message, extra_tags=f"social-auth {backend_name}") except MessageFailure: if url: - url += ("?" in url and "&" or "?") + f"message={quote(message)}&backend={backend_name}" + url += (("?" in url and "&") or "?") + f"message={quote(message)}&backend={backend_name}" else: social_logger.error(message) if url: return redirect(url) + return None + return None def raise_exception(self, request, exception): strategy = getattr(request, "social_strategy", None) if strategy is not None: return strategy.setting("RAISE_EXCEPTIONS", settings.DEBUG) + return None def get_message(self, request, exception): return str(exception) diff --git a/social_django/migrations/0001_initial.py b/social_django/migrations/0001_initial.py index 07924a80..0c45506e 100644 --- a/social_django/migrations/0001_initial.py +++ b/social_django/migrations/0001_initial.py @@ -2,13 +2,8 @@ from django.db import migrations, models from social_core.utils import setting_name -from ..fields import JSONField -from ..storage import ( - DjangoAssociationMixin, - DjangoCodeMixin, - DjangoNonceMixin, - DjangoUserMixin, -) +from social_django.fields import JSONField +from social_django.storage import DjangoAssociationMixin, DjangoCodeMixin, DjangoNonceMixin, DjangoUserMixin USER_MODEL = ( getattr(settings, setting_name("USER_MODEL"), None) or getattr(settings, "AUTH_USER_MODEL", None) or "auth.User" diff --git a/social_django/migrations/0004_auto_20160423_0400.py b/social_django/migrations/0004_auto_20160423_0400.py index 5d6375e2..512d5def 100644 --- a/social_django/migrations/0004_auto_20160423_0400.py +++ b/social_django/migrations/0004_auto_20160423_0400.py @@ -1,6 +1,6 @@ from django.db import migrations -from ..fields import JSONField +from social_django.fields import JSONField class Migration(migrations.Migration): @@ -18,5 +18,5 @@ class Migration(migrations.Migration): model_name="usersocialauth", name="extra_data", field=JSONField(default=dict), - ) + ), ] diff --git a/social_django/migrations/0013_migrate_extra_data.py b/social_django/migrations/0013_migrate_extra_data.py index 49ea2d2d..2216574d 100644 --- a/social_django/migrations/0013_migrate_extra_data.py +++ b/social_django/migrations/0013_migrate_extra_data.py @@ -1,9 +1,12 @@ # Generated by Django 4.0 on 2023-06-10 07:10 +import contextlib import json from django.db import migrations, models +MAX_BATCH_SIZE = 1000 + def migrate_json_field(apps, schema_editor): UserSocialAuth = apps.get_model("social_django", "UserSocialAuth") @@ -13,14 +16,12 @@ def migrate_json_field(apps, schema_editor): for auth in UserSocialAuth.objects.using(db_alias).exclude(extra_data='""').iterator(): old_value = auth.extra_data if isinstance(old_value, str): - try: + with contextlib.suppress(json.JSONDecodeError): old_value = json.loads(old_value) - except json.JSONDecodeError as error: - print(f"Failed to migrate extra_data {old_value}: {error}") auth.extra_data_new = old_value to_be_updated.append(auth) - if len(to_be_updated) >= 1000: + if len(to_be_updated) >= MAX_BATCH_SIZE: UserSocialAuth.objects.bulk_update(to_be_updated, ["extra_data_new"]) to_be_updated.clear() @@ -31,10 +32,8 @@ def migrate_json_field(apps, schema_editor): for auth in Partial.objects.using(db_alias).all(): old_value = auth.data if isinstance(old_value, str): - try: + with contextlib.suppress(json.JSONDecodeError): old_value = json.loads(old_value) - except json.JSONDecodeError as error: - print(f"Failed to migrate data {old_value}: {error}") auth.data_new = old_value auth.save(update_fields=["data_new"]) @@ -46,7 +45,7 @@ def migrate_json_field_backwards(apps, schema_editor): to_be_updated = [] is_text_field = isinstance( - UserSocialAuth._meta.get_field("extra_data"), + UserSocialAuth._meta.get_field("extra_data"), # noqa: SLF001 models.TextField, ) for auth in UserSocialAuth.objects.using(db_alias).iterator(): @@ -56,7 +55,7 @@ def migrate_json_field_backwards(apps, schema_editor): auth.extra_data = new_value to_be_updated.append(auth) - if len(to_be_updated) >= 1000: + if len(to_be_updated) >= MAX_BATCH_SIZE: UserSocialAuth.objects.bulk_update(to_be_updated, ["extra_data"]) to_be_updated.clear() @@ -65,7 +64,7 @@ def migrate_json_field_backwards(apps, schema_editor): to_be_updated.clear() is_text_field = issubclass( - type(Partial._meta.get_field("data")), + type(Partial._meta.get_field("data")), # noqa: SLF001 models.TextField, ) for auth in Partial.objects.using(db_alias).all(): diff --git a/social_django/models.py b/social_django/models.py index 70f9d995..ccf90335 100644 --- a/social_django/models.py +++ b/social_django/models.py @@ -36,13 +36,13 @@ class AbstractUserSocialAuth(models.Model, DjangoUserMixin): modified = models.DateTimeField(auto_now=True) objects = UserSocialAuthManager() - def __str__(self): - return str(self.user) - class Meta: constraints = [models.CheckConstraint(condition=~models.Q(uid=""), name="user_social_auth_uid_required")] abstract = True + def __str__(self): + return str(self.user) + @classmethod def get_social_auth(cls, provider: str, uid: str | int): if not isinstance(uid, str): @@ -57,7 +57,7 @@ def get_social_auth(cls, provider: str, uid: str | int): @classmethod def username_max_length(cls): username_field = cls.username_field() - field = cls.user_model()._meta.get_field(username_field) + field = cls.user_model()._meta.get_field(username_field) # noqa: SLF001 return field.max_length @classmethod diff --git a/social_django/storage.py b/social_django/storage.py index aa57f0aa..295b55c5 100644 --- a/social_django/storage.py +++ b/social_django/storage.py @@ -34,10 +34,7 @@ def allowed_to_disconnect(cls, user, backend_name, association_id=None): qs = cls.objects.exclude(provider=backend_name) qs = qs.filter(user=user) - if hasattr(user, "has_usable_password"): - valid_password = user.has_usable_password() - else: - valid_password = True + valid_password = user.has_usable_password() if hasattr(user, "has_usable_password") else True return valid_password or qs.exists() @classmethod @@ -56,7 +53,7 @@ def user_exists(cls, *args, **kwargs): """ if "username" in kwargs: kwargs[cls.username_field()] = kwargs.pop("username") - return cls.user_model()._default_manager.filter(*args, **kwargs).exists() + return cls.user_model()._default_manager.filter(*args, **kwargs).exists() # noqa: SLF001 @classmethod def get_username(cls, user): @@ -65,6 +62,7 @@ def get_username(cls, user): @classmethod def create_user(cls, *args, **kwargs): username_field = cls.username_field() + manager = cls.user_model()._default_manager # noqa: SLF001 if "username" in kwargs: if username_field not in kwargs: kwargs[username_field] = kwargs.pop("username") @@ -72,7 +70,7 @@ def create_user(cls, *args, **kwargs): # If username_field is 'email' and there is no field named "username" # then latest should be removed from kwargs. try: - cls.user_model()._meta.get_field("username") + cls.user_model()._meta.get_field("username") # noqa: SLF001 except FieldDoesNotExist: kwargs.pop("username") try: @@ -83,17 +81,17 @@ def create_user(cls, *args, **kwargs): # stays undamaged by wrapping the create in an atomic. using = router.db_for_write(cls.user_model()) with transaction.atomic(using=using): - user = cls.user_model()._default_manager.create_user(*args, **kwargs) + user = manager.create_user(*args, **kwargs) else: - user = cls.user_model()._default_manager.create_user(*args, **kwargs) + user = manager.create_user(*args, **kwargs) except IntegrityError as exc: # If email comes in as None it won't get found in the get if kwargs.get("email", True) is None: kwargs["email"] = "" try: - user = cls.user_model()._default_manager.get(*args, **kwargs) + user = manager.get(*args, **kwargs) except cls.user_model().DoesNotExist: - raise exc + raise exc from None return user @classmethod @@ -101,7 +99,7 @@ def get_user(cls, pk=None, **kwargs): if pk: kwargs = {"pk": pk} try: - return cls.user_model()._default_manager.get(**kwargs) + return cls.user_model()._default_manager.get(**kwargs) # noqa: SLF001 except cls.user_model().DoesNotExist: return None @@ -109,7 +107,9 @@ def get_user(cls, pk=None, **kwargs): def get_users_by_email(cls, email): user_model = cls.user_model() email_field = getattr(user_model, "EMAIL_FIELD", "email") - return user_model._default_manager.filter(**{email_field + "__iexact": email}) + return user_model._default_manager.filter( # noqa: SLF001 + **{email_field + "__iexact": email} + ) @classmethod def get_social_auth(cls, provider, uid): @@ -121,7 +121,7 @@ def get_social_auth(cls, provider, uid): return None @classmethod - def get_social_auth_for_user(cls, user, provider=None, id=None): + def get_social_auth_for_user(cls, user, provider=None, id=None): # noqa: A002 qs = cls.objects.filter(user=user) if provider: diff --git a/social_django/strategy.py b/social_django/strategy.py index 996d5270..8f9cbb30 100644 --- a/social_django/strategy.py +++ b/social_django/strategy.py @@ -1,12 +1,11 @@ from __future__ import annotations from importlib import import_module -from typing import Any +from typing import TYPE_CHECKING, Any from django.conf import settings from django.contrib.auth import authenticate, get_user from django.contrib.contenttypes.models import ContentType -from django.contrib.sessions.backends.base import SessionBase from django.db.models import Model from django.http import HttpRequest, HttpResponse from django.shortcuts import redirect, resolve_url @@ -17,10 +16,15 @@ from django.utils.translation import get_language from social_core.strategy import BaseStrategy, BaseTemplateStrategy +if TYPE_CHECKING: + from django.contrib.sessions.backends.base import SessionBase + def render_template_string(request, html, context=None): - """Take a template in the form of a string and render it for the - given context""" + """ + Take a template in the form of a string and render it for the + given context + """ template = engines["django"].from_string(html) return template.render(context=context, request=request) @@ -71,13 +75,14 @@ def request_data(self, merge=True): def request_host(self): if self.request: return self.request.get_host() + return None def request_is_secure(self): """Is the request using HTTPS?""" return self.request.is_secure() def request_path(self): - """path of the current request""" + """Path of the current request""" return self.request.path def request_port(self): @@ -100,7 +105,8 @@ def html(self, content): def render_html(self, tpl=None, html=None, context=None): if not tpl and not html: - raise ValueError("Missing template or html parameters") + msg = "Missing template or html parameters" + raise ValueError(msg) context = context or {} try: template = loader.get_template(tpl) @@ -136,15 +142,16 @@ def session_setdefault(self, name, value): def build_absolute_uri(self, path=None): if self.request: return self.request.build_absolute_uri(path) - else: - return path + return path def random_string(self, length=12, chars=BaseStrategy.ALLOWED_CHARS): return get_random_string(length, chars) def to_session_value(self, val): - """Converts values that are instance of Model to a dictionary - with enough information to retrieve the instance back later.""" + """ + Converts values that are instance of Model to a dictionary + with enough information to retrieve the instance back later. + """ if isinstance(val, Model): val = {"pk": val.pk, "ctype": ContentType.objects.get_for_model(val).pk} return val @@ -153,8 +160,9 @@ def from_session_value(self, val): """Converts back the instance saved by self._ctype function.""" if isinstance(val, dict) and "pk" in val and "ctype" in val: ctype = ContentType.objects.get_for_id(val["ctype"]) - ModelClass = ctype.model_class() - val = ModelClass._default_manager.get(pk=val["pk"]) + ModelClass = ctype.model_class() # noqa: N806 + val = ModelClass._default_manager.get(pk=val["pk"]) # noqa: SLF001 + return val def get_language(self): diff --git a/social_django/urls.py b/social_django/urls.py index 3e9d36c7..259eea96 100644 --- a/social_django/urls.py +++ b/social_django/urls.py @@ -6,7 +6,7 @@ from . import views -extra = getattr(settings, setting_name("TRAILING_SLASH"), True) and "/" or "" +extra = (getattr(settings, setting_name("TRAILING_SLASH"), True) and "/") or "" app_name = "social" diff --git a/social_django/utils.py b/social_django/utils.py index 3dbdbcc8..2f7da3e7 100644 --- a/social_django/utils.py +++ b/social_django/utils.py @@ -38,8 +38,9 @@ def wrapper(request, backend, *args, **kwargs): try: request.backend = load_backend(request.social_strategy, backend, redirect_uri=uri) - except MissingBackend: - raise Http404("Backend not found") + except MissingBackend as error: + msg = "Backend not found" + raise Http404(msg) from error return func(request, backend, *args, **kwargs) return wrapper diff --git a/social_django/views.py b/social_django/views.py index 92e47f95..4e1d08c5 100644 --- a/social_django/views.py +++ b/social_django/views.py @@ -59,10 +59,7 @@ def get_session_timeout(social_user, enable_session_expiration=False, max_sessio # We've enabled session expiration. Check to see if we got # a specific expiration time from the provider for this user; # if not, use the platform default expiration. - if expiration: - received_expiration_time = expiration.total_seconds() - else: - received_expiration_time = DEFAULT_SESSION_TIMEOUT + received_expiration_time = expiration.total_seconds() if expiration else DEFAULT_SESSION_TIMEOUT # Check to see if the backend set a value as a maximum length # that a session may be; if they did, then we should use the minimum @@ -83,14 +80,13 @@ def get_session_timeout(social_user, enable_session_expiration=False, max_sessio # We received an expiration time from the backend, and we also # have a set maximum session length. Use the smaller of the two. session_expiry = min(received_expiration_time, max_session_length) + # If there's an explicitly-set maximum session length, use that + # even if we don't want to retrieve session expiry times from + # the backend. If there isn't, then use the platform default. + elif max_session_length is None: + session_expiry = DEFAULT_SESSION_TIMEOUT else: - # If there's an explicitly-set maximum session length, use that - # even if we don't want to retrieve session expiry times from - # the backend. If there isn't, then use the platform default. - if max_session_length is None: - session_expiry = DEFAULT_SESSION_TIMEOUT - else: - session_expiry = max_session_length + session_expiry = max_session_length return session_expiry diff --git a/tests/settings.py b/tests/settings.py index 858ada04..979ba9cb 100644 --- a/tests/settings.py +++ b/tests/settings.py @@ -9,7 +9,7 @@ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", - } + }, } ROOT_URLCONF = "tests.urls" @@ -55,6 +55,6 @@ }, ] -SECRET_KEY = "6p%gef2(6kvjsgl*7!51a7z8c3=u4uc&6ulpua0g1^&sthiifp" +SECRET_KEY = "6p%gef2(6kvjsgl*7!51a7z8c3=u4uc&6ulpua0g1^&sthiifp" # noqa: S105 STATIC_URL = "/static/" diff --git a/tests/test_admin.py b/tests/test_admin.py index a8d3012e..5ede75a7 100644 --- a/tests/test_admin.py +++ b/tests/test_admin.py @@ -8,23 +8,29 @@ class SocialAdminTest(TestCase): @classmethod def setUpTestData(cls): - User = get_user_model() - User._default_manager.create_superuser( + User = get_user_model() # noqa: N806 + User._default_manager.create_superuser( # noqa: SLF001 username="admin", email="admin@test.com", first_name="Admin", - password="super-duper-test", + password="super-duper-test", # noqa: S106 ) def test_admin_app_name(self): """The App name in the admin index page""" - self.client.login(username="admin", password="super-duper-test") + self.client.login( + username="admin", + password="super-duper-test", # noqa: S106 + ) response = self.client.get(reverse("admin:index")) self.assertContains(response, "Python Social Auth") def test_social_auth_changelist(self): """The App name in the admin index page""" - self.client.login(username="admin", password="super-duper-test") - meta = UserSocialAuth._meta + self.client.login( + username="admin", + password="super-duper-test", # noqa: S106 + ) + meta = UserSocialAuth._meta # noqa: SLF001 url_name = f"admin:{meta.app_label}_{meta.model_name}_changelist" self.client.get(reverse(url_name)) diff --git a/tests/test_models.py b/tests/test_models.py index 4112b97f..5b9d13d2 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -20,22 +20,22 @@ class TestSocialAuthUser(TestCase): def test_user_relationship_none(self): """Accessing User.social_user outside of the pipeline doesn't work""" - User = get_user_model() - user = User._default_manager.create_user(username="randomtester") + User = get_user_model() # noqa: N806 + user = User._default_manager.create_user(username="randomtester") # noqa: SLF001 with self.assertRaises(AttributeError): - user.social_user + user.social_user # noqa: B018 def test_user_existing_relationship(self): """Accessing User.social_user outside of the pipeline doesn't work""" - User = get_user_model() - user = User._default_manager.create_user(username="randomtester") + User = get_user_model() # noqa: N806 + user = User._default_manager.create_user(username="randomtester") # noqa: SLF001 UserSocialAuth.objects.create(user=user, provider="my-provider", uid="1234") with self.assertRaises(AttributeError): - user.social_user + user.social_user # noqa: B018 def test_get_social_auth(self): - User = get_user_model() - user = User._default_manager.create_user(username="randomtester") + User = get_user_model() # noqa: N806 + user = User._default_manager.create_user(username="randomtester") # noqa: SLF001 user_social = UserSocialAuth.objects.create(user=user, provider="my-provider", uid="1234") other = UserSocialAuth.get_social_auth("my-provider", "1234") self.assertEqual(other, user_social) @@ -65,13 +65,13 @@ def test_cleanup(self): class TestUserSocialAuth(TestCase): def setUp(self): self.user_model = get_user_model() - self.user = self.user_model._default_manager.create_user(username="randomtester", email="user@example.com") + self.user = self.user_model._default_manager.create_user(username="randomtester", email="user@example.com") # noqa: SLF001 self.usa = UserSocialAuth.objects.create(user=self.user, provider="my-provider", uid="1234") def test_changed(self): self.user.email = eml = "test@example.com" UserSocialAuth.changed(user=self.user) - db_eml = self.user_model._default_manager.get(username=self.user.username).email + db_eml = self.user_model._default_manager.get(username=self.user.username).email # noqa: SLF001 self.assertEqual(db_eml, eml) def test_set_extra_data(self): @@ -116,7 +116,7 @@ def test_create_user_custom_username(self, *args): @mock.patch("social_django.storage.transaction", spec=[]) def test_create_user_without_transaction_atomic(self, *args): UserSocialAuth.create_user(username="test") - self.assertTrue(self.user_model._default_manager.filter(username="test").exists()) + self.assertTrue(self.user_model._default_manager.filter(username="test").exists()) # noqa: SLF001 def test_get_user(self): self.assertEqual(UserSocialAuth.get_user(pk=self.user.pk), self.user) @@ -216,11 +216,12 @@ def test_get_code(self): class TestPartial(TestCase): def test_load_destroy(self): - p = Partial.objects.create(token="x", backend="y", data={}) - self.assertEqual(Partial.load(token="x"), p) - self.assertIsNone(Partial.load(token="y")) + token_value = "x" # noqa: S105 + p = Partial.objects.create(token=token_value, backend="y", data={}) + self.assertEqual(Partial.load(token=token_value), p) + self.assertIsNone(Partial.load(token="y")) # noqa: S106 - Partial.destroy(token="x") + Partial.destroy(token=token_value) self.assertEqual(Partial.objects.count(), 0) diff --git a/tests/test_strategy.py b/tests/test_strategy.py index 5b0de58f..eac07e6d 100644 --- a/tests/test_strategy.py +++ b/tests/test_strategy.py @@ -50,7 +50,7 @@ def test_random_string(self): def test_session_value(self): user_model = get_user_model() - user = user_model._default_manager.create_user(username="test") + user = user_model._default_manager.create_user(username="test") # noqa: SLF001 ctype = ContentType.objects.get_for_model(user_model) val = self.strategy.to_session_value(val=user) diff --git a/tests/test_views.py b/tests/test_views.py index db10f3b5..b9fa10fd 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -9,7 +9,7 @@ from social_django.views import get_session_timeout -@override_settings(SOCIAL_AUTH_FACEBOOK_KEY="1", SOCIAL_AUTH_FACEBOOK_SECRET="2") +@override_settings(SOCIAL_AUTH_FACEBOOK_KEY="1", SOCIAL_AUTH_FACEBOOK_SECRET="2") # noqa: S106 class TestViews(TestCase): def setUp(self): session = self.client.session @@ -43,11 +43,14 @@ def test_complete(self, mock_request): self.assertEqual(response.url, "/accounts/profile/") @mock.patch("social_core.backends.base.BaseAuth.request") - def test_disconnect(self, mock_request): + def test_disconnect(self, _mock_request): user_model = get_user_model() - user = user_model._default_manager.create_user(username="test", password="pwd") + user = user_model._default_manager.create_user( # noqa: SLF001 + username="test", + password="pwd", # noqa: S106 + ) UserSocialAuth.objects.create(user=user, provider="facebook", uid="some-mock-facebook-uid") - self.client.login(username="test", password="pwd") + self.client.login(username="test", password="pwd") # noqa: S106 url = reverse("social:disconnect", kwargs={"backend": "facebook"}) response = self.client.post(url) @@ -78,7 +81,7 @@ def setUp(self): def set_user_expiration(self, seconds): self.social_user.expiration_datetime.return_value = mock.MagicMock( - total_seconds=mock.MagicMock(return_value=seconds) + total_seconds=mock.MagicMock(return_value=seconds), ) def test_expiration_disabled_no_max(self): @@ -88,7 +91,9 @@ def test_expiration_disabled_no_max(self): def test_expiration_disabled_with_max(self): expiration_length = get_session_timeout( - self.social_user, enable_session_expiration=False, max_session_length=60 + self.social_user, + enable_session_expiration=False, + max_session_length=60, ) self.assertEqual(expiration_length, 60)