From f8b64c4fbb80953dbb606f73baad49fc3edab748 Mon Sep 17 00:00:00 2001 From: mahiuddin-dev Date: Tue, 24 Oct 2023 11:47:49 +0600 Subject: [PATCH] Refactor code for improved readability and PEP 8 compliance --- tests/utils.py | 48 +++++++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/tests/utils.py b/tests/utils.py index 4ceb35309..037a19894 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -1,45 +1,44 @@ from operator import attrgetter - from django.core.exceptions import ObjectDoesNotExist from django.urls import NoReverseMatch - class MockObject: + """ + A mock object for testing purposes. + """ + def __init__(self, **kwargs): self._kwargs = kwargs - for key, val in kwargs.items(): - setattr(self, key, val) + for key, value in kwargs.items(): + setattr(self, key, value) def __str__(self): - kwargs_str = ', '.join([ - '%s=%s' % (key, value) - for key, value in sorted(self._kwargs.items()) - ]) - return '' % kwargs_str + sorted_kwargs = ', '.join(['%s=%s' % (key, value) for key, value in sorted(self._kwargs.items())]) + return f'' class MockQueryset: + """ + A mock queryset for testing purposes. + """ + def __init__(self, iterable): self.items = iterable - def __getitem__(self, val): - return self.items[val] + def __getitem__(self, index): + return self.items[index] def get(self, **lookup): for item in self.items: - if all([ - attrgetter(key.replace('__', '.'))(item) == value - for key, value in lookup.items() - ]): + if all(attrgetter(key.replace('__', '.'))(item) == value for key, value in lookup.items()): return item raise ObjectDoesNotExist() class BadType: """ - When used as a lookup with a `MockQueryset`, these objects - will raise a `TypeError`, as occurs in Django when making - queryset lookups with an incorrect type for the lookup value. + Raise a `TypeError` when used as a lookup value with a `MockQueryset`. + This behavior mimics Django's queryset lookups with incorrect types. """ def __eq__(self): @@ -47,13 +46,20 @@ class BadType: def mock_reverse(view_name, args=None, kwargs=None, request=None, format=None): + """ + Mocked implementation of Django's reverse function for testing. + """ + args = args or [] kwargs = kwargs or {} - value = (args + list(kwargs.values()) + ['-'])[0] + first_value = (args + list(kwargs.values()) + ['-'])[0] prefix = 'http://example.org' if request else '' - suffix = ('.' + format) if (format is not None) else '' - return '%s/%s/%s%s/' % (prefix, view_name, value, suffix) + suffix = f'.{format}' if format is not None else '' + return f'{prefix}/{view_name}/{first_value}{suffix}/' def fail_reverse(view_name, args=None, kwargs=None, request=None, format=None): + """ + Mocked implementation of Django's reverse function to raise a NoReverseMatch for testing. + """ raise NoReverseMatch()