From b964b044a68d6c6e27fe156a40f356b60eaf0099 Mon Sep 17 00:00:00 2001 From: Situphen Date: Sun, 6 Mar 2022 13:40:35 +0100 Subject: [PATCH 1/2] =?UTF-8?q?Mise=20=C3=A0=20jour=20de=20pyupgrade=20et?= =?UTF-8?q?=20Black?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 2 +- .pre-commit-config.yaml | 6 +++--- pyproject.toml | 1 + requirements-dev.txt | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf16a0831a..9bc1e704c8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,7 +7,7 @@ env: PYTHON_VERSION: "3.7" MARIADB_VERSION: "10.4.10" COVERALLS_VERSION: "3.3.1" # check if Coverage needs to be also updated in requirements-ci.txt - BLACK_VERSION: "21.12b0" # needs to be also updated in requirements-dev.txt and .pre-commit-config.yaml + BLACK_VERSION: "22.3.0" # needs to be also updated in requirements-dev.txt and .pre-commit-config.yaml # As GitHub Action does not allow environment variables # to be used in services definitions, these are only for diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5f8a27b7b5..1a7702c0ec 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,11 +1,11 @@ repos: - repo: https://github.com/asottile/pyupgrade - rev: v2.10.0 + rev: v2.31.0 hooks: - id: pyupgrade - args: [--py36-plus] + args: [--py37-plus] - repo: https://github.com/psf/black - rev: 21.12b0 # needs to be also updated in requirements-dev.txt and .github/workflows/ci.yml + rev: 22.3.0 # needs to be also updated in requirements-dev.txt and .github/workflows/ci.yml hooks: - id: black language_version: python3 diff --git a/pyproject.toml b/pyproject.toml index 6fa711c4ea..f9b6c6c860 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,6 @@ [tool.black] line-length = 120 +target-version = ["py37", "py38", "py39", "py310"] extend-exclude = """ ^/doc """ diff --git a/requirements-dev.txt b/requirements-dev.txt index ba4238a695..7e3b38aade 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,6 +1,6 @@ -r requirements.txt -black==21.12b0 # needs to be also updated in .github/workflows/ci.yml and .pre-commit-config.yaml +black==22.3.0 # needs to be also updated in .github/workflows/ci.yml and .pre-commit-config.yaml colorlog==6.6.0 django-debug-toolbar==3.2.4 django-extensions==3.1.5 From 632d9a28f43e36f7e255d6c8bc816f652e67bee3 Mon Sep 17 00:00:00 2001 From: Situphen Date: Mon, 28 Mar 2022 22:27:17 +0200 Subject: [PATCH 2/2] =?UTF-8?q?Modifications=20cosm=C3=A9tiques=20des=20fi?= =?UTF-8?q?chiers=20Python?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zds/forum/models.py | 2 +- zds/forum/tests/tests_views.py | 4 +- zds/gallery/models.py | 2 +- zds/gallery/tests/factories.py | 4 +- zds/notification/tests/tests_tricky.py | 2 +- zds/searchv2/forms.py | 2 +- zds/searchv2/models.py | 2 +- zds/settings/prod.py | 2 +- .../management/commands/migrate_to_zep25.py | 2 +- zds/tutorialv2/managers.py | 2 +- zds/tutorialv2/models/versioned.py | 2 +- zds/tutorialv2/publish_container.py | 6 +-- zds/tutorialv2/tests/factories.py | 4 +- .../tests_views/tests_editcontentlicense.py | 2 +- .../tests_views/tests_editcontenttags.py | 2 +- .../tests/tests_views/tests_published.py | 8 ++- zds/tutorialv2/views/beta.py | 2 +- zds/tutorialv2/views/misc.py | 2 +- zds/utils/context_processor.py | 2 +- zds/utils/forms.py | 4 +- zds/utils/management/commands/clean_tags.py | 6 +-- .../management/commands/load_fixtures.py | 50 +++++++++---------- zds/utils/models.py | 4 +- zds/utils/templatetags/append_query_params.py | 4 +- zds/utils/templatetags/email_obfuscator.py | 2 +- zds/utils/templatetags/emarkdown.py | 4 +- zds/utils/tests/factories.py | 6 +-- zds/utils/tests/test_htmldiff.py | 2 +- zds/utils/tests/tests_messages.py | 4 +- zds/utils/tokens.py | 2 +- 30 files changed, 68 insertions(+), 74 deletions(-) diff --git a/zds/forum/models.py b/zds/forum/models.py index 8cd5830c01..5125928002 100644 --- a/zds/forum/models.py +++ b/zds/forum/models.py @@ -21,7 +21,7 @@ def sub_tag(tag): start = tag.group("start") end = tag.group("end") - return "{}".format(start + end) + return f"{start + end}" class ForumCategory(models.Model): diff --git a/zds/forum/tests/tests_views.py b/zds/forum/tests/tests_views.py index 7bd4b43800..04dbd71d45 100644 --- a/zds/forum/tests/tests_views.py +++ b/zds/forum/tests/tests_views.py @@ -560,7 +560,7 @@ def test_success_edit_topic_solved_by_author(self): self.assertEqual(302, response.status_code) topic = Topic.objects.get(pk=topic.pk) self.assertTrue(topic.is_solved) - self.assertEquals(topic.solved_by, profile.user) + self.assertEqual(topic.solved_by, profile.user) def test_success_edit_topic_solved_by_staff(self): staff = StaffProfileFactory() @@ -576,7 +576,7 @@ def test_success_edit_topic_solved_by_staff(self): self.assertEqual(302, response.status_code) topic = Topic.objects.get(pk=topic.pk) self.assertTrue(topic.is_solved) - self.assertEquals(topic.solved_by, staff.user) + self.assertEqual(topic.solved_by, staff.user) def test_failure_edit_topic_lock_by_user(self): profile = ProfileFactory() diff --git a/zds/gallery/models.py b/zds/gallery/models.py index 007d2e7f3a..29c0a11ce9 100644 --- a/zds/gallery/models.py +++ b/zds/gallery/models.py @@ -33,7 +33,7 @@ def image_path(instance, filename): :rtype: unicode """ ext = filename.split(".")[-1].lower() - filename = "{}.{}".format(str(uuid4()), ext) + filename = f"{str(uuid4())}.{ext}" return os.path.join("galleries", str(instance.gallery.pk), filename) diff --git a/zds/gallery/tests/factories.py b/zds/gallery/tests/factories.py index b6499a863c..ae80e55deb 100644 --- a/zds/gallery/tests/factories.py +++ b/zds/gallery/tests/factories.py @@ -10,7 +10,7 @@ class Meta: model = Image title = factory.Sequence("titre de l'image {}".format) - slug = factory.LazyAttribute(lambda o: "{}".format(old_slugify(o.title))) + slug = factory.LazyAttribute(lambda o: f"{old_slugify(o.title)}") legend = factory.Sequence("legende de l'image {}".format) physical = factory.django.ImageField(color="blue") @@ -31,7 +31,7 @@ class Meta: title = factory.Sequence("titre de la gallerie {}".format) subtitle = factory.Sequence("Sous-titre de la gallerie {}".format) - slug = factory.LazyAttribute(lambda o: "{}".format(old_slugify(o.title))) + slug = factory.LazyAttribute(lambda o: f"{old_slugify(o.title)}") @classmethod def _generate(cls, create, attrs): diff --git a/zds/notification/tests/tests_tricky.py b/zds/notification/tests/tests_tricky.py index 22b9cf37b3..7de53c73fb 100644 --- a/zds/notification/tests/tests_tricky.py +++ b/zds/notification/tests/tests_tricky.py @@ -108,7 +108,7 @@ def test_edit_with_more_than_max_ping(self): { "title": "Super sujet", "subtitle": "Pour tester les notifs", - "text": "@{} @{} are pinged".format(pinged_users[1].user.username, pinged_users[3].user.username), + "text": f"@{pinged_users[1].user.username} @{pinged_users[3].user.username} are pinged", "tags": "", }, follow=False, diff --git a/zds/searchv2/forms.py b/zds/searchv2/forms.py index 92fc252d9c..560b9a1dd6 100644 --- a/zds/searchv2/forms.py +++ b/zds/searchv2/forms.py @@ -19,7 +19,7 @@ class SearchForm(forms.Form): ) choices = sorted( - [(k, v[0]) for k, v in settings.ZDS_APP["search"]["search_groups"].items()], key=lambda pair: pair[1] + ((k, v[0]) for k, v in settings.ZDS_APP["search"]["search_groups"].items()), key=lambda pair: pair[1] ) models = forms.MultipleChoiceField( diff --git a/zds/searchv2/models.py b/zds/searchv2/models.py index 0bb8632110..d1e8458ab3 100644 --- a/zds/searchv2/models.py +++ b/zds/searchv2/models.py @@ -555,7 +555,7 @@ def es_bulk_indexing_of_model(self, model, force_reindexing=False): if abs(1 - ratio) > 0.1: objects_per_batch = int(objects_per_batch * ratio) if force_reindexing: - print(" {}x, new batch size: {}".format(round(ratio, 2), objects_per_batch)) + print(f" {round(ratio, 2)}x, new batch size: {objects_per_batch}") prev_obj_per_sec = obj_per_sec # fetch next batch diff --git a/zds/settings/prod.py b/zds/settings/prod.py index ce96723775..dfc5ce977c 100644 --- a/zds/settings/prod.py +++ b/zds/settings/prod.py @@ -83,7 +83,7 @@ def _get_version(): if git_version is None: return __version__ else: - return "{}/{}".format(__version__, git_version[:7]) + return f"{__version__}/{git_version[:7]}" sentry_sdk.init( diff --git a/zds/tutorialv2/management/commands/migrate_to_zep25.py b/zds/tutorialv2/management/commands/migrate_to_zep25.py index 47f2102ace..701ebc3e07 100644 --- a/zds/tutorialv2/management/commands/migrate_to_zep25.py +++ b/zds/tutorialv2/management/commands/migrate_to_zep25.py @@ -121,7 +121,7 @@ def update_categories(self): sub = SubCategory() sub.title = subcategory[0] sub.subtitle = subcategory[1] - sub.slug = slugify("{}".format(subcategory[0])) + sub.slug = slugify(f"{subcategory[0]}") sub.save() self.stdout.write(f'[ZEP-25] : New subcategory "{sub}" added') catsubcat = CategorySubCategory() diff --git a/zds/tutorialv2/managers.py b/zds/tutorialv2/managers.py index 5bc72ffcd3..381bb6403f 100644 --- a/zds/tutorialv2/managers.py +++ b/zds/tutorialv2/managers.py @@ -25,7 +25,7 @@ def __get_list(self, subcategories=None, tags=None, content_type=None, with_comm if not isinstance(content_type, list): content_type = [content_type] content_type = filter(None, content_type) - queryset = queryset.filter(content_type__in=list([c.upper() for c in content_type])) + queryset = queryset.filter(content_type__in=list(c.upper() for c in content_type)) # prefetch: queryset = ( diff --git a/zds/tutorialv2/models/versioned.py b/zds/tutorialv2/models/versioned.py index e4b9eea29f..6710cb7078 100644 --- a/zds/tutorialv2/models/versioned.py +++ b/zds/tutorialv2/models/versioned.py @@ -140,7 +140,7 @@ def get_tree_level(self): elif isinstance(self.children[0], Extract): return 2 else: - return 1 + max([i.get_tree_level() for i in self.children]) + return 1 + max(i.get_tree_level() for i in self.children) def has_child_with_path(self, child_path): """Return ``True`` if this container has a child matching the given diff --git a/zds/tutorialv2/publish_container.py b/zds/tutorialv2/publish_container.py index d096241f61..05b101202a 100644 --- a/zds/tutorialv2/publish_container.py +++ b/zds/tutorialv2/publish_container.py @@ -31,7 +31,7 @@ def publish_container_new( rendered, template="tutorialv2/export/chapter.html", file_ext="html", - **ctx + **ctx, ): """ Generate the browser-diplay or epub of a content and its possible hierarchy @@ -128,7 +128,7 @@ def publish_container( template="tutorialv2/export/chapter.html", file_ext="html", image_callback=None, - **ctx + **ctx, ): """'Publish' a given container, in a recursive way Only here for epub publication (complexity of image/path traversal for the archive to be built) @@ -221,7 +221,7 @@ def publish_container( file_ext=file_ext, image_callback=image_callback, template=template, - **ctx + **ctx, ) path_to_title_dict.update(result) if container.conclusion and container.get_conclusion(): diff --git a/zds/tutorialv2/tests/factories.py b/zds/tutorialv2/tests/factories.py index bbb9270f89..75cf7e1229 100644 --- a/zds/tutorialv2/tests/factories.py +++ b/zds/tutorialv2/tests/factories.py @@ -101,7 +101,7 @@ class ContainerFactory(factory.Factory): class Meta: model = Container - title = factory.Sequence(lambda n: "Mon container No{}".format(n + 1)) + title = factory.Sequence(lambda n: f"Mon container No{n + 1}") @classmethod def _generate(cls, create, attrs): @@ -139,7 +139,7 @@ class ExtractFactory(factory.Factory): class Meta: model = Extract - title = factory.Sequence(lambda n: "Mon extrait No{}".format(n + 1)) + title = factory.Sequence(lambda n: f"Mon extrait No{n + 1}") @classmethod def _generate(cls, create, attrs): diff --git a/zds/tutorialv2/tests/tests_views/tests_editcontentlicense.py b/zds/tutorialv2/tests/tests_views/tests_editcontentlicense.py index 015a4336a5..0e4eb2a660 100644 --- a/zds/tutorialv2/tests/tests_views/tests_editcontentlicense.py +++ b/zds/tutorialv2/tests/tests_views/tests_editcontentlicense.py @@ -56,7 +56,7 @@ def test_authenticated_outsider(self): """Test that on form submission, unauthorized users get a 403.""" self.client.force_login(self.outsider) response = self.client.post(self.form_url, self.form_data) - self.assertEquals(response.status_code, 403) + self.assertEqual(response.status_code, 403) @override_for_contents() diff --git a/zds/tutorialv2/tests/tests_views/tests_editcontenttags.py b/zds/tutorialv2/tests/tests_views/tests_editcontenttags.py index c58bc11598..d8dab90718 100644 --- a/zds/tutorialv2/tests/tests_views/tests_editcontenttags.py +++ b/zds/tutorialv2/tests/tests_views/tests_editcontenttags.py @@ -55,7 +55,7 @@ def test_authenticated_outsider(self): """Test that on form submission, unauthorized users get a 403.""" self.client.force_login(self.outsider) response = self.client.post(self.form_url, self.form_data) - self.assertEquals(response.status_code, 403) + self.assertEqual(response.status_code, 403) @override_for_contents() diff --git a/zds/tutorialv2/tests/tests_views/tests_published.py b/zds/tutorialv2/tests/tests_views/tests_published.py index cc1a2998fc..e6b52eadf7 100644 --- a/zds/tutorialv2/tests/tests_views/tests_published.py +++ b/zds/tutorialv2/tests/tests_views/tests_published.py @@ -553,7 +553,7 @@ def test_add_note(self): # test quoting (without JS) result = self.client.get( - reverse("content:add-reaction") + "?pk={}&cite={}".format(self.published.content.pk, reactions[0].pk) + reverse("content:add-reaction") + f"?pk={self.published.content.pk}&cite={reactions[0].pk}" ) self.assertEqual(result.status_code, 200) @@ -565,7 +565,7 @@ def test_add_note(self): # test quoting (with JS) result = self.client.get( - reverse("content:add-reaction") + "?pk={}&cite={}".format(self.published.content.pk, reactions[0].pk), + reverse("content:add-reaction") + f"?pk={self.published.content.pk}&cite={reactions[0].pk}", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) @@ -1151,9 +1151,7 @@ def test_quote_note(self): self.assertEqual(404, result.status_code) # cite not existing note just gives the form empty - result = self.client.get( - reverse("content:add-reaction") + "?pk={}&cite={}".format(tuto.pk, 99999999), follow=True - ) + result = self.client.get(reverse("content:add-reaction") + f"?pk={tuto.pk}&cite={99999999}", follow=True) self.assertEqual(200, result.status_code) self.assertTrue("text" not in result.context["form"]) # nothing quoted, so no text cited diff --git a/zds/tutorialv2/views/beta.py b/zds/tutorialv2/views/beta.py index abe3e73a7a..adbc4d9496 100644 --- a/zds/tutorialv2/views/beta.py +++ b/zds/tutorialv2/views/beta.py @@ -42,7 +42,7 @@ def _create_beta_topic(self, msg, beta_version, _type, tags): max_len = Topic._meta.get_field("title").max_length while i < len(tags) and len(topic_title) + len(_tags) + len(tags[i].title) + 2 < max_len: - _tags += "[{}]".format(tags[i]) + _tags += f"[{tags[i]}]" i += 1 forum = get_object_or_404(Forum, pk=settings.ZDS_APP["forum"]["beta_forum_id"]) topic = create_topic( diff --git a/zds/tutorialv2/views/misc.py b/zds/tutorialv2/views/misc.py index ed484bf7e4..1f74df11bf 100644 --- a/zds/tutorialv2/views/misc.py +++ b/zds/tutorialv2/views/misc.py @@ -105,7 +105,7 @@ def get_form_kwargs(self): def form_valid(self, form): user = self.request.user authors = list(Profile.objects.contactable_members().filter(user__in=self.object.authors.all())) - authors = list([author.user for author in authors]) + authors = list(author.user for author in authors) # check if the warn is done on a public or beta version : is_public = False diff --git a/zds/utils/context_processor.py b/zds/utils/context_processor.py index eacb23a9f7..73f34f3e3c 100644 --- a/zds/utils/context_processor.py +++ b/zds/utils/context_processor.py @@ -12,7 +12,7 @@ def get_version(): Retrieve version informations from `zds/_version.py`. """ if git_version is not None: - name = "{}/{}".format(__version__, git_version[:7]) + name = f"{__version__}/{git_version[:7]}" url = get_repository_url(settings.ZDS_APP["github_projects"]["default_repository"], "base_url") return {"name": name, "url": f"{url}/tree/{git_version}"} else: diff --git a/zds/utils/forms.py b/zds/utils/forms.py index 7a95d9740b..9e2b864e9e 100644 --- a/zds/utils/forms.py +++ b/zds/utils/forms.py @@ -29,7 +29,7 @@ def __init__(self, *args, **kwargs): HTML(""), HTML(""), *args, - **kwargs + **kwargs, ) @@ -52,7 +52,7 @@ def __init__(self, *args, send_label="Envoyer", display_save=False, **kwargs): ), ), *args, - **kwargs + **kwargs, ) diff --git a/zds/utils/management/commands/clean_tags.py b/zds/utils/management/commands/clean_tags.py index 9ed0e02245..e5a54a160d 100644 --- a/zds/utils/management/commands/clean_tags.py +++ b/zds/utils/management/commands/clean_tags.py @@ -15,7 +15,7 @@ def title_pk(tag): return f'"{tag.title}" ({tag.pk})' def replace(tag_to_delete, tag_to_use_instead): - self.stdout.write("Replacing {} with {}".format(title_pk(tag_to_delete), title_pk(tag_to_use_instead))) + self.stdout.write(f"Replacing {title_pk(tag_to_delete)} with {title_pk(tag_to_use_instead)}") topics = Topic.objects.filter(tags__pk=tag_to_delete["pk"]) for topic in topics: @@ -29,7 +29,7 @@ def replace(tag_to_delete, tag_to_use_instead): content.tags.add(tag_to_use_instead.pk) content.tags.remove(tag_to_delete["pk"]) - self.stdout.write(" Deleting {}".format(title_pk(tag_to_delete))) + self.stdout.write(f" Deleting {title_pk(tag_to_delete)}") Tag.objects.get(pk=tag_to_delete["pk"]).delete() self.stdout.write(self.help) @@ -57,4 +57,4 @@ def replace(tag_to_delete, tag_to_use_instead): stripped = Tag.objects.get(pk=tag["pk"]) stripped.name = tag["stripped"] stripped.save() - self.stdout.write("Stripped {} to {}".format(title_pk(tag), title_pk(stripped))) + self.stdout.write(f"Stripped {title_pk(tag)} to {title_pk(stripped)}") diff --git a/zds/utils/management/commands/load_fixtures.py b/zds/utils/management/commands/load_fixtures.py index a5b45ab859..6c20fc5129 100644 --- a/zds/utils/management/commands/load_fixtures.py +++ b/zds/utils/management/commands/load_fixtures.py @@ -78,10 +78,10 @@ def load_member(cli, size, fake, root, *_): profile.last_ip_address = fake.ipv4() profile.save() cpt += 1 - sys.stdout.write(" User {}/{} \r".format(i + 1, nb_users)) + sys.stdout.write(f" User {i + 1}/{nb_users} \r") sys.stdout.flush() tps2 = time.time() - cli.stdout.write("\nFait en {} sec".format(tps2 - tps1)) + cli.stdout.write(f"\nFait en {tps2 - tps1} sec") def load_staff(cli, size, fake, root, *_): @@ -106,10 +106,10 @@ def load_staff(cli, size, fake, root, *_): profile.last_ip_address = fake.ipv6() profile.save() cpt += 1 - sys.stdout.write(" Staff {}/{} \r".format(i + 1, nb_staffs)) + sys.stdout.write(f" Staff {i + 1}/{nb_staffs} \r") sys.stdout.flush() tps2 = time.time() - cli.stdout.write("\nFait en {} sec".format(tps2 - tps1)) + cli.stdout.write(f"\nFait en {tps2 - tps1} sec") def load_gallery(cli, size, fake, *_, **__): @@ -134,7 +134,7 @@ def load_gallery(cli, size, fake, *_, **__): UserGalleryFactory(user=profiles[user_index].user, gallery=gal) __push_images_into_gallery(gal, user_index, gallery_index, nb_galleries, nb_images, nb_users) tps2 = time.time() - cli.stdout.write("\nFait en {} sec".format(tps2 - tps1)) + cli.stdout.write(f"\nFait en {tps2 - tps1} sec") def __push_images_into_gallery(gal, i, j, nb_galleries, nb_images, nb_users): @@ -159,10 +159,10 @@ def load_categories_forum(cli, size, fake, *_, **__): cat = ForumCategoryFactory(position=i + 1) cat.title = fake.word() cat.save() - sys.stdout.write(" Cat. {}/{} \r".format(i + 1, nb_categories)) + sys.stdout.write(f" Cat. {i + 1}/{nb_categories} \r") sys.stdout.flush() tps2 = time.time() - cli.stdout.write("\nFait en {} sec".format(tps2 - tps1)) + cli.stdout.write(f"\nFait en {tps2 - tps1} sec") def load_forums(cli, size, fake, *_, **__): @@ -188,10 +188,10 @@ def load_forums(cli, size, fake, *_, **__): forum.title = fake.word() forum.subtitle = fake.sentence(nb_words=15, variable_nb_words=True) forum.save() - sys.stdout.write(" Forum {}/{} \r".format(i + 1, nb_forums)) + sys.stdout.write(f" Forum {i + 1}/{nb_forums} \r") sys.stdout.flush() tps2 = time.time() - cli.stdout.write("\nFait en {} sec".format(tps2 - tps1)) + cli.stdout.write(f"\nFait en {tps2 - tps1} sec") def load_tags(cli, size, fake, *_, **__): @@ -206,10 +206,10 @@ def load_tags(cli, size, fake, *_, **__): with contextlib.suppress(IntegrityError): tag, created = Tag.objects.get_or_create(title=title.lower()) logging.getLogger(cli.__class__.__name__).debug("tag=%s is_new=%s", tag, created) - sys.stdout.write(" Tag {}/{} \r".format(i + 1, nb_tags)) + sys.stdout.write(f" Tag {i + 1}/{nb_tags} \r") sys.stdout.flush() tps2 = time.time() - cli.stdout.write("\nFait en {} sec".format(tps2 - tps1)) + cli.stdout.write(f"\nFait en {tps2 - tps1} sec") def load_topics(cli, size, fake, *_, **__): @@ -249,10 +249,10 @@ def load_topics(cli, size, fake, *_, **__): topic.subtitle = fake.text(max_nb_chars=200) topic.save() PostFactory(topic=topic, author=topic.author, position=1) - sys.stdout.write(" Topic {}/{} \r".format(i + 1, nb_topics)) + sys.stdout.write(f" Topic {i + 1}/{nb_topics} \r") sys.stdout.flush() tps2 = time.time() - cli.stdout.write("\nFait en {} sec".format(tps2 - tps1)) + cli.stdout.write(f"\nFait en {tps2 - tps1} sec") def add_generated_tags_to_topic(nb_rand_tags, nb_tags, topic): @@ -297,12 +297,10 @@ def __generate_topic_and_post(cli, fake, nb_avg_posts_in_topic, nb_topics, nb_us post.text_html = emarkdown(post.text) post.is_useful = int(nb_posts * 0.3) > 0 and post_index % int(nb_posts * 0.3) == 0 post.save() - sys.stdout.write( - " Topic {}/{} \tPost {}/{} \r".format(topic_index + 1, nb_topics, post_index + 1, nb_posts) - ) + sys.stdout.write(f" Topic {topic_index + 1}/{nb_topics} \tPost {post_index + 1}/{nb_posts} \r") sys.stdout.flush() tps2 = time.time() - cli.stdout.write("\nFait en {} sec".format(tps2 - tps1)) + cli.stdout.write(f"\nFait en {tps2 - tps1} sec") def load_categories_content(cli, size, fake, *_, **__): @@ -331,7 +329,7 @@ def load_categories_content(cli, size, fake, *_, **__): ) cat.save() categories.append(cat) - sys.stdout.write(" Cat. {}/{} \r".format(i + 1, nb_categories)) + sys.stdout.write(f" Cat. {i + 1}/{nb_categories} \r") sys.stdout.flush() for i in range(0, nb_sub_categories): @@ -342,7 +340,7 @@ def load_categories_content(cli, size, fake, *_, **__): ) subcat.save() sub_categories.append(subcat) - sys.stdout.write(" SubCat. {}/{} \r".format(i + 1, nb_sub_categories)) + sys.stdout.write(f" SubCat. {i + 1}/{nb_sub_categories} \r") sys.stdout.flush() for i in range(0, nb_sub_categories): @@ -351,11 +349,11 @@ def load_categories_content(cli, size, fake, *_, **__): category=categories[i % nb_categories], subcategory=sub_categories[i], is_main=True ) catsubcat.save() - sys.stdout.write(" CatSubCat. {}/{} \r".format(i + 1, nb_sub_categories)) + sys.stdout.write(f" CatSubCat. {i + 1}/{nb_sub_categories} \r") sys.stdout.flush() tps2 = time.time() - cli.stdout.write("\nFait en {} sec".format(tps2 - tps1)) + cli.stdout.write(f"\nFait en {tps2 - tps1} sec") def load_comment_content(cli, size, fake, *_, **__): @@ -379,12 +377,12 @@ def load_comment_content(cli, size, fake, *_, **__): post.text = fake.paragraph(nb_sentences=5, variable_nb_sentences=True) post.text_html = emarkdown(post.text) post.save() - sys.stdout.write("Contenu {}/{} \tCommentaire {}/{} \r".format(i + 1, nb_contents, j + 1, nb_posts)) + sys.stdout.write(f"Contenu {i + 1}/{nb_contents} \tCommentaire {j + 1}/{nb_posts} \r") sys.stdout.flush() contents[i].last_note = post contents[i].save() tps2 = time.time() - cli.stdout.write("\nFait en {:.3f} sec".format(tps2 - tps1)) + cli.stdout.write(f"\nFait en {tps2 - tps1:.3f} sec") def load_contents(cli, size, fake, _type, *_, **__): @@ -442,7 +440,7 @@ def load_contents(cli, size, fake, _type, *_, **__): nb_contents * percent_contents_with_validator, ) ) - cli.stdout.write(" - {:g} publiés".format(nb_contents * percent_contents_public)) + cli.stdout.write(f" - {nb_contents * percent_contents_public:g} publiés") tps1 = time.time() @@ -512,7 +510,7 @@ def load_contents(cli, size, fake, _type, *_, **__): # create and so all: for created_content_index in range(nb_contents): - sys.stdout.write("Création {} : {}/{} \r".format(textual_type, created_content_index + 1, nb_contents)) + sys.stdout.write(f"Création {textual_type} : {created_content_index + 1}/{nb_contents} \r") current_size = content_sizes[created_content_index] action_flag = what_to_do[created_content_index] @@ -552,7 +550,7 @@ def load_contents(cli, size, fake, _type, *_, **__): sys.stdout.flush() tps2 = time.time() - cli.stdout.write("\nFait en {:.3f} sec".format(tps2 - tps1)) + cli.stdout.write(f"\nFait en {tps2 - tps1:.3f} sec") def validate_edited_content(content, fake, nb_staffs, staffs, to_do, versioned): diff --git a/zds/utils/models.py b/zds/utils/models.py index 08aec11959..bdf4237682 100644 --- a/zds/utils/models.py +++ b/zds/utils/models.py @@ -36,14 +36,14 @@ def image_path_category(instance, filename): """Return path to an image.""" ext = filename.split(".")[-1] - filename = "{}.{}".format(str(uuid.uuid4()), string.lower(ext)) + filename = f"{str(uuid.uuid4())}.{string.lower(ext)}" return os.path.join("categorie/normal", str(instance.pk), filename) def image_path_help(instance, filename): """Return path to an image.""" ext = filename.split(".")[-1] - filename = "{}.{}".format(str(uuid.uuid4()), string.lower(ext)) + filename = f"{str(uuid.uuid4())}.{string.lower(ext)}" return os.path.join("helps/normal", str(instance.pk), filename) diff --git a/zds/utils/templatetags/append_query_params.py b/zds/utils/templatetags/append_query_params.py index cded005ae6..da2d170644 100644 --- a/zds/utils/templatetags/append_query_params.py +++ b/zds/utils/templatetags/append_query_params.py @@ -82,9 +82,7 @@ def render(self, context): get[key] = self.__dict_pairs[key].resolve(context) if len(get) > 0: - list_arg = [ - "{}={}".format(key, quote(str(value))) for key in list(get.keys()) for value in get.getlist(key) - ] + list_arg = [f"{key}={quote(str(value))}" for key in list(get.keys()) for value in get.getlist(key)] path += "?" + "&".join(list_arg) return path diff --git a/zds/utils/templatetags/email_obfuscator.py b/zds/utils/templatetags/email_obfuscator.py index f1274e8be4..387d339d6c 100644 --- a/zds/utils/templatetags/email_obfuscator.py +++ b/zds/utils/templatetags/email_obfuscator.py @@ -9,7 +9,7 @@ def obfuscate_string(value): - return "".join(["&#{:s};".format(str(ord(char))) for char in value]) + return "".join([f"&#{str(ord(char)):s};" for char in value]) @register.filter diff --git a/zds/utils/templatetags/emarkdown.py b/zds/utils/templatetags/emarkdown.py index d4213abeb0..0556f8ae86 100644 --- a/zds/utils/templatetags/emarkdown.py +++ b/zds/utils/templatetags/emarkdown.py @@ -127,9 +127,9 @@ def render_markdown(md_input, *, on_error=None, disable_jsfiddle=True, **kwargs) # FIXME: This cannot work with LaTeX. if inline: - return mark_safe("

{}

".format(json.dumps(messages))), metadata, [] + return mark_safe(f"

{json.dumps(messages)}

"), metadata, [] else: - return mark_safe('

{}

'.format(json.dumps(messages))), metadata, [] + return mark_safe(f'

{json.dumps(messages)}

'), metadata, [] def render_markdown_stats(md_input, **kwargs): diff --git a/zds/utils/tests/factories.py b/zds/utils/tests/factories.py index 405decdede..61f1f7af0e 100644 --- a/zds/utils/tests/factories.py +++ b/zds/utils/tests/factories.py @@ -18,7 +18,7 @@ class Meta: model = HelpWriting title = factory.Sequence("titre de l'image {}".format) - slug = factory.LazyAttribute(lambda o: "{}".format(old_slugify(o.title))) + slug = factory.LazyAttribute(lambda o: f"{old_slugify(o.title)}") tablelabel = factory.LazyAttribute(lambda n: "Besoin de " + n.title) @classmethod @@ -97,5 +97,5 @@ class LicenceFactory(factory.django.DjangoModelFactory): class Meta: model = Licence - code = factory.Sequence(lambda n: "bidon-no{}".format(n + 1)) - title = factory.Sequence(lambda n: "Licence bidon no{}".format(n + 1)) + code = factory.Sequence(lambda n: f"bidon-no{n + 1}") + title = factory.Sequence(lambda n: f"Licence bidon no{n + 1}") diff --git a/zds/utils/tests/test_htmldiff.py b/zds/utils/tests/test_htmldiff.py index 418c7e59eb..611178b5fa 100644 --- a/zds/utils/tests/test_htmldiff.py +++ b/zds/utils/tests/test_htmldiff.py @@ -5,7 +5,7 @@ class HtmlDiffTests(TestCase): def test_empty(self): - self.assertEquals(htmldiff(b"essai", b"essai"), "

Pas de changements.

") + self.assertEqual(htmldiff(b"essai", b"essai"), "

Pas de changements.

") def test_nominal(self): self.assertIn("Agrume", htmldiff(b"Agrume", b"")) diff --git a/zds/utils/tests/tests_messages.py b/zds/utils/tests/tests_messages.py index 508c34c791..6d62d69f70 100644 --- a/zds/utils/tests/tests_messages.py +++ b/zds/utils/tests/tests_messages.py @@ -16,14 +16,14 @@ class FunctionTests(SimpleTestCase): def test_messages(self): for tag in self.tags: - txt = "some message with {}".format(repr(tag)) + txt = f"some message with {repr(tag)}" test_messages = [Message(tag, txt)] self.assertEqual( messages(test_messages), {"messages": [{"text": txt, "tags": LEVEL_TAGS[tag]}]} ) # clean one - txt = "['some dirty message with {}']".format(repr(tag)) + txt = f"['some dirty message with {repr(tag)}']" txt_altered = txt.replace("['", "").replace("']", "") test_messages = [Message(tag, txt)] self.assertEqual( diff --git a/zds/utils/tokens.py b/zds/utils/tokens.py index 41edafd8f0..ce9b97cee9 100644 --- a/zds/utils/tokens.py +++ b/zds/utils/tokens.py @@ -3,7 +3,7 @@ def generate_token(): - return md5(f"lcdldses?nas. {time()} salt".encode("utf-8")).hexdigest()[:12] + return md5(f"lcdldses?nas. {time()} salt".encode()).hexdigest()[:12] def get_token(request):