From 9a8daee9e07ac8b700d30797b7104b15cfa9507b Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Wed, 20 Dec 2023 12:29:23 +0200 Subject: [PATCH] Replace string interpolation and .format calls with f-strings --- example/pexp/management/commands/p2cmd.py | 9 +++--- example/pexp/management/commands/polybench.py | 8 +++-- polymorphic/admin/childadmin.py | 21 +++++++------ polymorphic/admin/filters.py | 2 +- polymorphic/admin/helpers.py | 2 +- polymorphic/admin/inlines.py | 2 +- polymorphic/admin/parentadmin.py | 30 +++++++++---------- polymorphic/base.py | 22 +++++++------- polymorphic/formsets/generic.py | 2 +- polymorphic/formsets/models.py | 8 ++--- polymorphic/managers.py | 5 ++-- polymorphic/models.py | 12 +++----- polymorphic/query.py | 10 +++---- polymorphic/query_translate.py | 28 +++++++---------- polymorphic/showfields.py | 24 ++++++++------- polymorphic/tests/admintestcase.py | 6 ++-- polymorphic/tests/test_orm.py | 17 ++++++----- 17 files changed, 96 insertions(+), 112 deletions(-) diff --git a/example/pexp/management/commands/p2cmd.py b/example/pexp/management/commands/p2cmd.py index e06a001b..77719fdf 100644 --- a/example/pexp/management/commands/p2cmd.py +++ b/example/pexp/management/commands/p2cmd.py @@ -35,8 +35,8 @@ def wrapper(*arg): for r in results: res_sum += r print( - "%s%-19s: %.4f ms, %i queries (%i times)" - % (message, func.func_name, res_sum, len(connection.queries), iterations) + f"{message}{func.func_name:<19}: {res_sum:.4f} ms, " + f"{len(connection.queries)} queries ({iterations} times)" ) sys.stdout.flush() @@ -106,13 +106,12 @@ def poly_sql_query(): def poly_sql_query2(): cursor = connection.cursor() cursor.execute( - """ + f""" SELECT id, pexp_testmodela.field1 FROM pexp_testmodela - WHERE pexp_testmodela.field1=%i + WHERE pexp_testmodela.field1={rnd.randint(0, 100)} ORDER BY pexp_testmodela.id """ - % rnd.randint(0, 100) ) # row=cursor.fetchone() return diff --git a/example/pexp/management/commands/polybench.py b/example/pexp/management/commands/polybench.py index 9c0233d4..30729fc7 100644 --- a/example/pexp/management/commands/polybench.py +++ b/example/pexp/management/commands/polybench.py @@ -39,8 +39,8 @@ def wrapper(*arg): res_sum += r median = res_sum / len(results) print( - "%s%-19s: %.0f ms, %i queries" - % (message, func.func_name, median, len(connection.queries) / len(results)) + f"{message}{func.func_name:<19}: {median:.0f} ms, " + f"{len(connection.queries) / len(results):d} queries" ) sys.stdout.flush() @@ -61,7 +61,9 @@ def run_vanilla_any_poly(func, iterations=1): def bench_create(model): for i in range(num_objects): model.objects.create( - field1="abc" + str(i), field2="abcd" + str(i), field3="abcde" + str(i) + field1=f"abc{i}", + field2=f"abcd{i}", + field3=f"abcde{i}", ) # print 'count:',model.objects.count() diff --git a/polymorphic/admin/childadmin.py b/polymorphic/admin/childadmin.py index a824da4d..5f7f4a69 100644 --- a/polymorphic/admin/childadmin.py +++ b/polymorphic/admin/childadmin.py @@ -90,10 +90,10 @@ def change_form_template(self): return [ f"admin/{app_label}/{opts.object_name.lower()}/change_form.html", - "admin/%s/change_form.html" % app_label, + f"admin/{app_label}/change_form.html", # Added: - "admin/%s/%s/change_form.html" % (base_app_label, base_opts.object_name.lower()), - "admin/%s/change_form.html" % base_app_label, + f"admin/{base_app_label}/{base_opts.object_name.lower()}/change_form.html", + f"admin/{base_app_label}/change_form.html", "admin/polymorphic/change_form.html", "admin/change_form.html", ] @@ -108,12 +108,11 @@ def delete_confirmation_template(self): base_app_label = base_opts.app_label return [ - "admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()), - "admin/%s/delete_confirmation.html" % app_label, + f"admin/{app_label}/{opts.object_name.lower()}/delete_confirmation.html", + f"admin/{app_label}/delete_confirmation.html", # Added: - "admin/%s/%s/delete_confirmation.html" - % (base_app_label, base_opts.object_name.lower()), - "admin/%s/delete_confirmation.html" % base_app_label, + f"admin/{base_app_label}/{base_opts.object_name.lower()}/delete_confirmation.html", + f"admin/{base_app_label}/delete_confirmation.html", "admin/polymorphic/delete_confirmation.html", "admin/delete_confirmation.html", ] @@ -129,10 +128,10 @@ def object_history_template(self): return [ f"admin/{app_label}/{opts.object_name.lower()}/object_history.html", - "admin/%s/object_history.html" % app_label, + f"admin/{app_label}/object_history.html", # Added: - "admin/%s/%s/object_history.html" % (base_app_label, base_opts.object_name.lower()), - "admin/%s/object_history.html" % base_app_label, + f"admin/{base_app_label}/{base_opts.object_name.lower()}/object_history.html", + f"admin/{base_app_label}/object_history.html", "admin/polymorphic/object_history.html", "admin/object_history.html", ] diff --git a/polymorphic/admin/filters.py b/polymorphic/admin/filters.py index fe29f3cd..afe2fe6e 100644 --- a/polymorphic/admin/filters.py +++ b/polymorphic/admin/filters.py @@ -32,6 +32,6 @@ def queryset(self, request, queryset): if choice_value == value: return queryset.filter(polymorphic_ctype_id=choice_value) raise PermissionDenied( - 'Invalid ContentType "{}". It must be registered as child model.'.format(value) + f'Invalid ContentType "{value}". It must be registered as child model.' ) return queryset diff --git a/polymorphic/admin/helpers.py b/polymorphic/admin/helpers.py index f17de11b..bb5b80d7 100644 --- a/polymorphic/admin/helpers.py +++ b/polymorphic/admin/helpers.py @@ -91,7 +91,7 @@ def inline_formset_data(self): verbose_name = self.opts.verbose_name return json.dumps( { - "name": "#%s" % self.formset.prefix, + "name": f"#{self.formset.prefix}", "options": { "prefix": self.formset.prefix, "addText": gettext("Add another %(verbose_name)s") diff --git a/polymorphic/admin/inlines.py b/polymorphic/admin/inlines.py index 7e16ac78..39a1f71d 100644 --- a/polymorphic/admin/inlines.py +++ b/polymorphic/admin/inlines.py @@ -38,7 +38,7 @@ class PolymorphicInlineModelAdmin(InlineModelAdmin): #: This can be redefined for subclasses. polymorphic_media = Media( js=( - "admin/js/vendor/jquery/jquery{}.js".format("" if settings.DEBUG else ".min"), + f"admin/js/vendor/jquery/{'jquery' if settings.DEBUG else 'jquery.min'}.js", "admin/js/jquery.init.js", "polymorphic/js/polymorphic_inlines.js", ), diff --git a/polymorphic/admin/parentadmin.py b/polymorphic/admin/parentadmin.py index 44e6fcdd..d021522d 100644 --- a/polymorphic/admin/parentadmin.py +++ b/polymorphic/admin/parentadmin.py @@ -97,14 +97,10 @@ def register_child(self, model, model_admin): raise RegistrationClosed("The admin model can't be registered anymore at this point.") if not issubclass(model, self.base_model): - raise TypeError( - "{} should be a subclass of {}".format(model.__name__, self.base_model.__name__) - ) + raise TypeError(f"{model.__name__} should be a subclass of {self.base_model.__name__}") if not issubclass(model_admin, admin.ModelAdmin): raise TypeError( - "{} should be a subclass of {}".format( - model_admin.__name__, admin.ModelAdmin.__name__ - ) + f"{model_admin.__name__} should be a subclass of {admin.ModelAdmin.__name__}" ) self._child_admin_site.register(model, model_admin) @@ -159,7 +155,8 @@ def _get_real_admin_by_ct(self, ct_id, super_if_self=True): model_class = ct.model_class() if not model_class: # Handle model deletion - raise Http404("No model found for '{}.{}'.".format(*ct.natural_key())) + app_label, model = ct.natural_key() + raise Http404(f"No model found for '{app_label}.{model}'.") return self._get_real_admin_by_model(model_class, super_if_self=super_if_self) @@ -168,7 +165,7 @@ def _get_real_admin_by_model(self, model_class, super_if_self=True): # Hence, make sure this is a derived object, or risk exposing other admin interfaces. if model_class not in self._child_models: raise PermissionDenied( - "Invalid model '{}', it must be registered as child model.".format(model_class) + f"Invalid model '{model_class}', it must be registered as child model." ) try: @@ -177,7 +174,7 @@ def _get_real_admin_by_model(self, model_class, super_if_self=True): real_admin = self._child_admin_site._registry[model_class] except KeyError: raise ChildAdminNotRegistered( - "No child admin site was registered for a '{}' model.".format(model_class) + f"No child admin site was registered for a '{model_class}' model." ) if super_if_self and real_admin is self: @@ -273,7 +270,7 @@ def subclass_view(self, request, path): object_id = int(path[0:pos]) except ValueError: raise Http404( - "No ct_id parameter, unable to find admin subclass for path '{}'.".format(path) + f"No ct_id parameter, unable to find admin subclass for path '{path}'." ) ct_id = self.model.objects.values_list("polymorphic_ctype_id", flat=True).get( @@ -299,7 +296,8 @@ def add_type_view(self, request, form_url=""): if request.META["QUERY_STRING"]: # QUERY_STRING is bytes in Python 3, using force_str() to decode it as string. # See QueryDict how Django deals with that. - extra_qs = "&{}".format(force_str(request.META["QUERY_STRING"])) + # TODO: should this use a Django method instead of manipulating the string directly? + extra_qs = f"&{force_str(request.META['QUERY_STRING'])}" choices = self.get_child_type_choices(request, "add") if len(choices) == 0: @@ -315,7 +313,7 @@ def add_type_view(self, request, form_url=""): form.fields["ct_id"].choices = choices if form.is_valid(): - return HttpResponseRedirect("?ct_id={}{}".format(form.cleaned_data["ct_id"], extra_qs)) + return HttpResponseRedirect(f"?ct_id={form.cleaned_data['ct_id']}{extra_qs}") # Wrap in all admin layout fieldsets = ((None, {"fields": ("ct_id",)}),) @@ -351,7 +349,7 @@ def render_add_type_form(self, request, context, form_url=""): templates = self.add_type_template or [ f"admin/{app_label}/{opts.object_name.lower()}/add_type_form.html", - "admin/%s/add_type_form.html" % app_label, + f"admin/{app_label}/add_type_form.html", "admin/polymorphic/add_type_form.html", # added default here "admin/add_type_form.html", ] @@ -370,9 +368,9 @@ def change_list_template(self): return [ f"admin/{app_label}/{opts.object_name.lower()}/change_list.html", - "admin/%s/change_list.html" % app_label, + f"admin/{app_label}/change_list.html", # Added base class: - "admin/%s/%s/change_list.html" % (base_app_label, base_opts.object_name.lower()), - "admin/%s/change_list.html" % base_app_label, + f"admin/{base_app_label}/{base_opts.object_name.lower()}/change_list.html", + f"admin/{base_app_label}/change_list.html", "admin/change_list.html", ] diff --git a/polymorphic/base.py b/polymorphic/base.py index 91d52fee..c4fc6918 100644 --- a/polymorphic/base.py +++ b/polymorphic/base.py @@ -119,8 +119,10 @@ def validate_model_fields(self, new_class): "check if all fields names are allowed (i.e. not in POLYMORPHIC_SPECIAL_Q_KWORDS)" for f in new_class._meta.fields: if f.name in POLYMORPHIC_SPECIAL_Q_KWORDS: - e = 'PolymorphicModel: "%s" - field name "%s" is not allowed in polymorphic models' - raise AssertionError(e % (new_class.__name__, f.name)) + raise AssertionError( + f'PolymorphicModel: "{new_class.__name__}" - ' + f'field name "{f.name}" is not allowed in polymorphic models' + ) @classmethod def validate_model_manager(self, manager, model_name, manager_name): @@ -133,10 +135,8 @@ def validate_model_manager(self, manager, model_name, manager_name): else: extra = "" e = ( - 'PolymorphicModel: "{0}.{1}" manager is of type "{2}", but must be a subclass of' - " PolymorphicManager.{extra} to support retrieving subclasses".format( - model_name, manager_name, type(manager).__name__, extra=extra - ) + f'PolymorphicModel: "{model_name}.{manager_name}" manager is of type "{type(manager).__name__}", ' + f"but must be a subclass of PolymorphicManager.{extra} to support retrieving subclasses" ) warnings.warn(e, ManagerInheritanceWarning, stacklevel=3) return manager @@ -145,10 +145,8 @@ def validate_model_manager(self, manager, model_name, manager_name): manager.queryset_class, PolymorphicQuerySet ): e = ( - 'PolymorphicModel: "{}.{}" has been instantiated with a queryset class ' - "which is not a subclass of PolymorphicQuerySet (which is required)".format( - model_name, manager_name - ) + f'PolymorphicModel: "{model_name}.{manager_name}" has been instantiated with a queryset class ' + f"which is not a subclass of PolymorphicQuerySet (which is required)" ) warnings.warn(e, ManagerInheritanceWarning, stacklevel=3) return manager @@ -157,7 +155,7 @@ def validate_model_manager(self, manager, model_name, manager_name): def base_objects(self): warnings.warn( "Using PolymorphicModel.base_objects is deprecated.\n" - "Use {}.objects.non_polymorphic() instead.".format(self.__class__.__name__), + f"Use {self.__class__.__name__}.objects.non_polymorphic() instead.", DeprecationWarning, stacklevel=2, ) @@ -193,7 +191,7 @@ def _default_manager(self): manager = super()._default_manager if not isinstance(manager, PolymorphicManager): warnings.warn( - "{}._default_manager is not a PolymorphicManager".format(self.__class__.__name__), + f"{self.__class__.__name__}._default_manager is not a PolymorphicManager", ManagerInheritanceWarning, ) diff --git a/polymorphic/formsets/generic.py b/polymorphic/formsets/generic.py index e593d93c..7da59ba7 100644 --- a/polymorphic/formsets/generic.py +++ b/polymorphic/formsets/generic.py @@ -42,7 +42,7 @@ def get_form(self, ct_field="content_type", fk_field="object_id", **kwargs): not isinstance(ct_field, models.ForeignKey) or ct_field.remote_field.model != ContentType ): - raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field) + raise Exception(f"fk_name '{ct_field}' is not a ForeignKey to ContentType") fk_field = opts.get_field(self.fk_field) # let the exception propagate exclude.extend([ct_field.name, fk_field.name]) diff --git a/polymorphic/formsets/models.py b/polymorphic/formsets/models.py index 45bfb9cf..a8b29f8c 100644 --- a/polymorphic/formsets/models.py +++ b/polymorphic/formsets/models.py @@ -188,7 +188,7 @@ def _construct_form(self, i, **kwargs): ct_id = int(self.data[f"{prefix}-polymorphic_ctype"]) except (KeyError, ValueError): raise ValidationError( - "Formset row {} has no 'polymorphic_ctype' defined!".format(prefix) + f"Formset row {prefix} has no 'polymorphic_ctype' defined!" ) model = ContentType.objects.get_for_id(ct_id).model_class() @@ -243,10 +243,8 @@ def get_form_class(self, model): except KeyError: # This may happen when the query returns objects of a type that was not handled by the formset. raise UnsupportedChildType( - "The '{}' found a '{}' model in the queryset, " - "but no form class is registered to display it.".format( - self.__class__.__name__, model.__name__ - ) + f"The '{self.__class__.__name__}' found a '{model.__name__}' model in the queryset, " + f"but no form class is registered to display it." ) def is_multipart(self): diff --git a/polymorphic/managers.py b/polymorphic/managers.py index ac139a78..0f8fd71c 100644 --- a/polymorphic/managers.py +++ b/polymorphic/managers.py @@ -33,9 +33,8 @@ def get_queryset(self): return qs def __str__(self): - return "{} (PolymorphicManager) using {}".format( - self.__class__.__name__, - self.queryset_class.__name__, + return ( + f"{self.__class__.__name__} (PolymorphicManager) using {self.queryset_class.__name__}" ) # Proxied methods diff --git a/polymorphic/models.py b/polymorphic/models.py index df0cc485..0c31b339 100644 --- a/polymorphic/models.py +++ b/polymorphic/models.py @@ -98,11 +98,9 @@ def get_real_instance_class(self): """ if self.polymorphic_ctype_id is None: raise PolymorphicTypeUndefined( - ( - "The model {}#{} does not have a `polymorphic_ctype_id` value defined.\n" - "If you created models outside polymorphic, e.g. through an import or migration, " - "make sure the `polymorphic_ctype_id` field points to the ContentType ID of the model subclass." - ).format(self.__class__.__name__, self.pk) + f"The model {self.__class__.__name__}#{self.pk} does not have a `polymorphic_ctype_id` value defined.\n" + f"If you created models outside polymorphic, e.g. through an import or migration, " + f"make sure the `polymorphic_ctype_id` field points to the ContentType ID of the model subclass." ) # the following line would be the easiest way to do this, but it produces sql queries @@ -127,9 +125,7 @@ def get_real_instance_class(self): ) ): raise PolymorphicTypeInvalid( - "ContentType {} for {} #{} does not point to a subclass!".format( - self.polymorphic_ctype_id, model, self.pk - ) + f"ContentType {self.polymorphic_ctype_id} for {model} #{self.pk} does not point to a subclass!" ) return model diff --git a/polymorphic/query.py b/polymorphic/query.py index 72bc522b..9736256e 100644 --- a/polymorphic/query.py +++ b/polymorphic/query.py @@ -417,7 +417,7 @@ class self.model, but as a class derived from self.model. We want to re-fetch for real_concrete_class, idlist in idlist_per_model.items(): indices = indexlist_per_model[real_concrete_class] real_objects = real_concrete_class._base_objects.db_manager(self.db).filter( - **{("%s__in" % pk_name): idlist} + **{(f"{pk_name}__in"): idlist} ) # copy select related configuration to new qs real_objects.query.select_related = self.query.select_related @@ -504,15 +504,15 @@ class self.model, but as a class derived from self.model. We want to re-fetch def __repr__(self, *args, **kwargs): if self.model.polymorphic_query_multiline_output: - result = [repr(o) for o in self.all()] - return "[ " + ",\n ".join(result) + " ]" + result = ",\n ".join(repr(o) for o in self.all()) + return f"[ {result} ]" else: return super().__repr__(*args, **kwargs) class _p_list_class(list): def __repr__(self, *args, **kwargs): - result = [repr(o) for o in self] - return "[ " + ",\n ".join(result) + " ]" + result = ",\n ".join(repr(o) for o in self) + return f"[ {result} ]" def get_real_instances(self, base_result_objects=None): """ diff --git a/polymorphic/query_translate.py b/polymorphic/query_translate.py index 627f1840..89c00953 100644 --- a/polymorphic/query_translate.py +++ b/polymorphic/query_translate.py @@ -140,7 +140,7 @@ def translate_polymorphic_field_path(queryset_model, field_path): classname, sep, pure_field_path = field_path.partition("___") if not sep: return field_path - assert classname, "PolymorphicModel: %s: bad field specification" % field_path + assert classname, f"PolymorphicModel: {field_path}: bad field specification" negated = False if classname[0] == "-": @@ -151,10 +151,7 @@ def translate_polymorphic_field_path(queryset_model, field_path): # the user has app label prepended to class name via __ => use Django's get_model function appname, sep, classname = classname.partition("__") model = apps.get_model(appname, classname) - assert model, "PolymorphicModel: model {} (in app {}) not found!".format( - model.__name__, - appname, - ) + assert model, f"PolymorphicModel: model {model.__name__} (in app {appname}) not found!" if not issubclass(model, queryset_model): e = ( 'PolymorphicModel: queryset filter error: "' @@ -184,10 +181,7 @@ def translate_polymorphic_field_path(queryset_model, field_path): submodels = _get_all_sub_models(queryset_model) model = submodels.get(classname, None) - assert model, "PolymorphicModel: model {} not found (not a subclass of {})!".format( - classname, - queryset_model.__name__, - ) + assert model, f"PolymorphicModel: model {classname} not found (not a subclass of {queryset_model.__name__})!" basepath = _create_base_path(queryset_model, model) @@ -214,15 +208,13 @@ def _get_all_sub_models(base_model): if issubclass(model, models.Model) and model != models.Model: # model name is occurring twice in submodel inheritance tree => Error if model.__name__ in result and model != result[model.__name__]: + name1 = f"{model._meta.app_label}.{model.__name__}" + name2 = ( + f"{result[model.__name__]._meta.app_label}.{result[model.__name__].__name__}" + ) raise FieldError( - "PolymorphicModel: model name alone is ambiguous: %s.%s and %s.%s match!\n" - "In this case, please use the syntax: applabel__ModelName___field" - % ( - model._meta.app_label, - model.__name__, - result[model.__name__]._meta.app_label, - result[model.__name__].__name__, - ) + f"PolymorphicModel: model name alone is ambiguous: {name1} and {name2} match!\n" + f"In this case, please use the syntax: applabel__ModelName___field" ) result[model.__name__] = model @@ -243,7 +235,7 @@ def _create_base_path(baseclass, myclass): if b._meta.abstract or b._meta.proxy: return _get_query_related_name(myclass) else: - return path + "__" + _get_query_related_name(myclass) + return f"{path}__{_get_query_related_name(myclass)}" return "" diff --git a/polymorphic/showfields.py b/polymorphic/showfields.py index 26cb2c4b..7590e3fa 100644 --- a/polymorphic/showfields.py +++ b/polymorphic/showfields.py @@ -36,16 +36,17 @@ def _showfields_get_content(self, field_name, field_type=type(None)): else: out += content.__class__.__name__ elif issubclass(field_type, models.ManyToManyField): - out += "%d" % content.count() + out += f"{content.count()}" elif isinstance(content, int): out += str(content) elif content is None: out += "None" else: txt = str(content) - if len(txt) > self.polymorphic_showfield_max_field_width: - txt = txt[: self.polymorphic_showfield_max_field_width - 2] + ".." - out += '"' + txt + '"' + max_len = self.polymorphic_showfield_max_field_width + if len(txt) > max_len: + txt = f"{txt[:max_len - 2]}.." + out += f'"{txt}"' return out def _showfields_add_regular_fields(self, parts): @@ -62,12 +63,12 @@ def _showfields_add_regular_fields(self, parts): # if this is the standard primary key named "id", print it as we did with older versions of django_polymorphic if field.primary_key and field.name == "id" and type(field) == models.AutoField: - out += " " + str(getattr(self, field.name)) + out += f" {getattr(self, field.name)}" # otherwise, display it just like all other fields (with correct type, shortened content etc.) else: if self.polymorphic_showfield_type: - out += " (" + type(field).__name__ + out += f" ({type(field).__name__}" if field.primary_key: out += "/pk" out += ")" @@ -79,12 +80,12 @@ def _showfields_add_regular_fields(self, parts): def _showfields_add_dynamic_fields(self, field_list, title, parts): "helper for __unicode__" - parts.append((True, "- " + title, ":")) + parts.append((True, f"- {title}", ":")) for field_name in field_list: out = field_name content = getattr(self, field_name) if self.polymorphic_showfield_type: - out += " (" + type(content).__name__ + ")" + out += f" ({type(content).__name__})" if self.polymorphic_showfield_content: out += self._showfields_get_content(field_name) @@ -113,7 +114,8 @@ def __str__(self): if self.polymorphic_showfield_deferred: fields = self.get_deferred_fields() if fields: - parts.append((False, "deferred[{}]".format(",".join(sorted(fields))), "")) + fields_str = ",".join(sorted(fields)) + parts.append((False, f"deferred[{fields_str}]", "")) # format result @@ -136,7 +138,7 @@ def __str__(self): ): rest = out[possible_line_break_pos:] out = out[:possible_line_break_pos] - out += "\n" + indentstr + rest + out += f"\n{indentstr}{rest}" xpos = indent + len(rest) out += p @@ -152,7 +154,7 @@ def __str__(self): if not new_section: possible_line_break_pos = len(out) - return "<" + out + ">" + return f"<{out}>" class ShowFieldType(ShowFieldBase): diff --git a/polymorphic/tests/admintestcase.py b/polymorphic/tests/admintestcase.py index ac872598..d0bf01a1 100644 --- a/polymorphic/tests/admintestcase.py +++ b/polymorphic/tests/admintestcase.py @@ -219,9 +219,9 @@ def assertFormSuccess(self, request_url, response): else: raise KeyError("Unknown field for errors in the TemplateResponse!") - assert response.status_code == 302, "Form errors in calling {}:\n{}".format( - request_url, errors.as_text() - ) + assert ( + response.status_code == 302 + ), f"Form errors in calling {request_url}:\n{errors.as_text()}" assert ( "/login/?next=" not in response["Location"] ), f"Received login response for {request_url}" diff --git a/polymorphic/tests/test_orm.py b/polymorphic/tests/test_orm.py index 61f7d242..5bb837d4 100644 --- a/polymorphic/tests/test_orm.py +++ b/polymorphic/tests/test_orm.py @@ -135,8 +135,7 @@ def test_annotate_aggregate_order(self): , , ]""" - x = "\n" + repr(BlogBase.objects.order_by("-name")) - assert x == expected + assert repr(BlogBase.objects.order_by("-name")).strip() == expected.strip() # test ordering for field in one subclass only # MySQL and SQLite return this order @@ -161,8 +160,10 @@ def test_annotate_aggregate_order(self): , ]""" - x = "\n" + repr(BlogBase.objects.order_by("-BlogA___info")) - assert (x == expected1) or (x == expected2) + assert repr(BlogBase.objects.order_by("-BlogA___info")).strip() in ( + expected1.strip(), + expected2.strip(), + ) def test_limit_choices_to(self): """ @@ -203,8 +204,8 @@ def test_primary_key_custom_field_problem(self): c = UUIDPlainC.objects.create(field1="C1", field2="C2", field3="C3") qs = UUIDPlainA.objects.all() # Test that primary key values are valid UUIDs - assert uuid.UUID(("urn:uuid:%s" % a.pk), version=1) == a.pk - assert uuid.UUID(("urn:uuid:%s" % c.pk), version=1) == c.pk + assert uuid.UUID(f"urn:uuid:{a.pk}", version=1) == a.pk + assert uuid.UUID(f"urn:uuid:{c.pk}", version=1) == c.pk def create_model2abcd(self): """ @@ -903,7 +904,7 @@ def test_proxy_model_inheritance(self): object1 = ProxyModelBase.objects.get(name="object1") object2 = ProxyModelBase.objects.get(name="object2") assert repr(object1) == ( - '' % object1_pk + f'' ) assert repr(object2) == ( '' @@ -915,7 +916,7 @@ def test_proxy_model_inheritance(self): # Same for lists objects = list(ProxyModelBase.objects.all().order_by("name")) assert repr(objects[0]) == ( - '' % object1_pk + f'' ) assert repr(objects[1]) == ( ''