jenkins-bot submitted this change.

View Change


Approvals: Xqt: Looks good to me, approved jenkins-bot: Verified
[format] Convert format-strings to f-strings using flynt

Change-Id: I5dca76b45a9f8eea21609db551b4d4a0ebe49baf
---
M tests/__init__.py
M tests/api_tests.py
M tests/aspects.py
M tests/eventstreams_tests.py
M tests/family_tests.py
M tests/generate_family_file_tests.py
M tests/i18n_tests.py
M tests/l10n_tests.py
M tests/namespace_tests.py
M tests/page_tests.py
M tests/pagegenerators_tests.py
M tests/plural_tests.py
M tests/proofreadpage_tests.py
M tests/script_tests.py
M tests/site_generators_tests.py
M tests/sparql_tests.py
M tests/textlib_tests.py
M tests/timestripper_tests.py
M tests/ui_options_tests.py
M tests/ui_tests.py
M tests/user_tests.py
M tests/utils.py
M tests/wikistats_tests.py
23 files changed, 122 insertions(+), 154 deletions(-)

diff --git a/tests/__init__.py b/tests/__init__.py
index 97e2a07..7aaa681 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -1,6 +1,6 @@
"""Package tests."""
#
-# (C) Pywikibot team, 2007-2023
+# (C) Pywikibot team, 2007-2024
#
# Distributed under the terms of the MIT license.
#
@@ -57,8 +57,7 @@
join_root_path.path = 'root'
join_tests_path = create_path_func(join_root_path, 'tests')
join_cache_path = create_path_func(join_tests_path,
- 'apicache-py{}'
- .format(PYTHON_VERSION[0]))
+ f'apicache-py{PYTHON_VERSION[0]}')
join_data_path = create_path_func(join_tests_path, 'data')
join_pages_path = create_path_func(join_tests_path, 'pages')

@@ -273,8 +272,8 @@
# fail more frequently in code paths resulting from mishandled server problems.
if config.max_retries > 3:
if 'PYWIKIBOT_TEST_QUIET' not in os.environ:
- unittest_print('tests: max_retries reduced from {} to 1'
- .format(config.max_retries))
+ unittest_print(
+ f'tests: max_retries reduced from {config.max_retries} to 1')
config.max_retries = 1

# Raise CaptchaError if a test requires solving a captcha
diff --git a/tests/api_tests.py b/tests/api_tests.py
index 8f4eb41..bfbcd09 100755
--- a/tests/api_tests.py
+++ b/tests/api_tests.py
@@ -926,8 +926,7 @@
if ('dbrepllag' not in mysite.siteinfo
or mysite.siteinfo['dbrepllag'][0]['lag'] == -1):
self.skipTest(
- '{} is not running on a replicated database cluster.'
- .format(mysite)
+ f'{mysite} is not running on a replicated database cluster.'
)
mythrottle = DummyThrottle(mysite)
mysite._throttle = mythrottle
diff --git a/tests/aspects.py b/tests/aspects.py
index f6dc453..3a44491 100644
--- a/tests/aspects.py
+++ b/tests/aspects.py
@@ -5,7 +5,7 @@
such as API result caching and excessive test durations.
"""
#
-# (C) Pywikibot team, 2014-2023
+# (C) Pywikibot team, 2014-2024
#
# Distributed under the terms of the MIT license.
#
@@ -91,8 +91,7 @@
self.assertIsInstance(
seq, Sized, 'seq argument is not a Sized class containing __len__')
if seq:
- msg = self._formatMessage(msg, '{} is not empty'
- .format(safe_repr(seq)))
+ msg = self._formatMessage(msg, f'{safe_repr(seq)} is not empty')
self.fail(msg)

def assertIsNotEmpty(self, seq, msg=None):
@@ -100,8 +99,7 @@
self.assertIsInstance(
seq, Sized, 'seq argument is not a Sized class containing __len__')
if not seq:
- msg = self._formatMessage(msg, '{} is empty'
- .format(safe_repr(seq)))
+ msg = self._formatMessage(msg, f'{safe_repr(seq)} is empty')
self.fail(msg)

def assertLength(self, seq, other, msg=None):
@@ -217,8 +215,8 @@

if skip and page_namespaces < namespaces:
raise unittest.SkipTest(
- 'No pages in namespaces {} found.'
- .format(list(namespaces - page_namespaces)))
+ f'No pages in namespaces {list(namespaces - page_namespaces)}'
+ ' found.')

self.assertEqual(page_namespaces, namespaces)

@@ -296,8 +294,7 @@
missing += [required_module]
if not missing:
return obj
- skip_decorator = unittest.skip('{} not installed'.format(
- ', '.join(missing)))
+ skip_decorator = unittest.skip(f"{', '.join(missing)} not installed")
return skip_decorator(obj)

return test_requirement
@@ -408,8 +405,7 @@
def __init__(self, code, fam=None, user=None):
"""Initializer."""
raise SiteDefinitionError(
- 'Loading site {}:{} during dry test not permitted'
- .format(fam, code))
+ f'Loading site {fam}:{code} during dry test not permitted')


class DisconnectedSiteMixin(TestCaseBase):
@@ -468,8 +464,8 @@

for key, data in cls.sites.items():
if 'hostname' not in data:
- raise Exception('{}: hostname not defined for {}'
- .format(cls.__name__, key))
+ raise Exception(
+ f'{cls.__name__}: hostname not defined for {key}')
hostname = data['hostname']

if hostname in cls._checked_hostnames:
@@ -504,8 +500,7 @@

cls._checked_hostnames[hostname] = e
raise unittest.SkipTest(
- '{}: hostname {} failed: {}'
- .format(cls.__name__, hostname, e))
+ f'{cls.__name__}: hostname {hostname} failed: {e}')

cls._checked_hostnames[hostname] = True

@@ -551,9 +546,8 @@

if os.environ.get(env_var, '0') != '1':
raise unittest.SkipTest(
- '{!r} write tests disabled. '
- 'Set {}=1 to enable.'
- .format(cls.__name__, env_var))
+ f'{cls.__name__!r} write tests disabled. '
+ f'Set {env_var}=1 to enable.')

if (not hasattr(site.family, 'test_codes')
or site.code not in site.family.test_codes):
@@ -574,8 +568,8 @@
def require_site_user(cls, family, code):
"""Check the user config has a valid login to the site."""
if not cls.has_site_user(family, code):
- raise unittest.SkipTest('{}: No username for {}:{}'
- .format(cls.__name__, family, code))
+ raise unittest.SkipTest(
+ f'{cls.__name__}: No username for {family}:{code}')

@classmethod
def setUpClass(cls):
@@ -604,8 +598,7 @@

if not site.user():
raise unittest.SkipTest(
- '{}: Not able to login to {}'
- .format(cls.__name__, site))
+ f'{cls.__name__}: Not able to login to {site}')

def setUp(self):
"""
@@ -643,8 +636,8 @@
site.login()

if skip_if_login_fails and not site.user(): # during setUp() only
- self.skipTest('{}: Not able to re-login to {}'
- .format(type(self).__name__, site))
+ self.skipTest(
+ f'{type(self).__name__}: Not able to re-login to {site}')

def get_userpage(self, site=None):
"""Create a User object for the user's userpage."""
@@ -798,9 +791,8 @@

# If there isn't a site, require declaration of net activity.
if 'net' not in dct:
- raise Exception(
- '{}: Test classes without a site configured must set "net"'
- .format(name))
+ raise Exception(f'{name}: Test classes without a site'
+ ' configured must set "net"')

# If the 'net' attribute is a false value,
# remove it so it matches 'not net' in pytest.
@@ -927,9 +919,8 @@
for data in cls.sites.values():
if (data.get('code') in ('test', 'mediawiki')
and prod_only and not dry):
- raise unittest.SkipTest(
- 'Site code {!r} and PYWIKIBOT_TEST_PROD_ONLY is set.'
- .format(data['code']))
+ raise unittest.SkipTest(f"Site code {data['code']!r} and"
+ ' PYWIKIBOT_TEST_PROD_ONLY is set.')

if 'site' not in data and 'code' in data and 'family' in data:
with suppress_warnings(WARN_SITE_CODE, category=UserWarning):
@@ -966,13 +957,11 @@
if len(cls.sites) == 1:
name = next(iter(cls.sites.keys()))
else:
- raise Exception(
- '"{}.get_site(name=None)" called with multiple sites'
- .format(cls.__name__))
+ raise Exception(f'"{cls.__name__}.get_site(name=None)"'
+ ' called with multiple sites')

if name and name not in cls.sites:
- raise Exception('"{}" not declared in {}'
- .format(name, cls.__name__))
+ raise Exception(f'"{name}" not declared in {cls.__name__}')

if isinstance(cls.site, BaseSite):
assert cls.sites[name]['site'] == cls.site
@@ -1214,9 +1203,8 @@

site = data['site']
if not site.has_data_repository:
- raise unittest.SkipTest(
- '{}: {!r} does not have data repository'
- .format(cls.__name__, site))
+ raise unittest.SkipTest(f'{cls.__name__}: {site!r} does'
+ ' not have data repository')

if (hasattr(cls, 'repo')
and cls.repo != site.data_repository()):
@@ -1258,9 +1246,8 @@

for site in cls.sites.values():
if not site['site'].has_data_repository:
- raise unittest.SkipTest(
- '{}: {!r} does not have data repository'
- .format(cls.__name__, site['site']))
+ raise unittest.SkipTest(f"{cls.__name__}: {site['site']!r}"
+ ' does not have data repository')


class DefaultWikibaseClientTestCase(WikibaseClientTestCase,
@@ -1293,9 +1280,8 @@
super().setUpClass()

if str(cls.get_repo()) != 'wikidata:wikidata':
- raise unittest.SkipTest(
- '{}: {} is not connected to Wikidata.'
- .format(cls.__name__, cls.get_site()))
+ raise unittest.SkipTest(f'{cls.__name__}: {cls.get_site()} is not'
+ 'connected to Wikidata.')


class PwbTestCase(TestCase):
@@ -1517,9 +1503,8 @@
continue

if item.filename != filename:
- self.fail(
- 'expected warning filename {}; warning item: {}'
- .format(filename, item))
+ self.fail(f'expected warning filename {filename}; warning '
+ f'item: {item}')

@classmethod
def setUpClass(cls):
diff --git a/tests/eventstreams_tests.py b/tests/eventstreams_tests.py
index ef17dcc..e53472b 100755
--- a/tests/eventstreams_tests.py
+++ b/tests/eventstreams_tests.py
@@ -46,8 +46,7 @@
self.assertIsNone(e._total)
self.assertIsNone(e._streams)
self.assertEqual(repr(e),
- "EventStreams(url='{}')"
- .format(self.sites[key]['hostname']))
+ f"EventStreams(url='{self.sites[key]['hostname']}')")

def test_url_from_site(self, key):
"""Test EventStreams with url from site."""
@@ -62,8 +61,7 @@
self.assertEqual(e._streams, streams)
site_repr = f'site={repr(site)}, ' if site != Site() else ''
self.assertEqual(repr(e),
- "EventStreams({}streams='{}')"
- .format(site_repr, streams))
+ f"EventStreams({site_repr}streams='{streams}')")


@mock.patch('pywikibot.comms.eventstreams.EventSource', new=mock.MagicMock())
@@ -78,8 +76,7 @@
fam = site.family
if not isinstance(fam, WikimediaFamily):
self.skipTest(
- "Family '{}' of site '{}' is not a WikimediaFamily."
- .format(fam, site))
+ f"Family '{fam}' of site '{site}' is not a WikimediaFamily.")

def test_url_with_streams(self):
"""Test EventStreams with url from default site."""
diff --git a/tests/family_tests.py b/tests/family_tests.py
index 02b3860..1c8f227 100755
--- a/tests/family_tests.py
+++ b/tests/family_tests.py
@@ -219,8 +219,7 @@
for family in pywikibot.config.family_files:
if family == 'wowwiki':
self.skipTest(
- 'Family.from_url() does not work for {} (T215077)'
- .format(family))
+ f'Family.from_url() does not work for {family} (T215077)')
self.current_family = family
family = Family.load(family)
for code in family.codes:
diff --git a/tests/generate_family_file_tests.py b/tests/generate_family_file_tests.py
index 0f8f25c..dccc037 100755
--- a/tests/generate_family_file_tests.py
+++ b/tests/generate_family_file_tests.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Test generate_family_file script."""
#
-# (C) Pywikibot team, 2018-2022
+# (C) Pywikibot team, 2018-2024
#
# Distributed under the terms of the MIT license.
#
@@ -52,8 +52,7 @@
super().setUpClass()
# test fails on wowwiki (T297042)
if cls.site.family.name == 'wowwiki':
- raise unittest.SkipTest('skipping {} due to T297042'
- .format(cls.site))
+ raise unittest.SkipTest(f'skipping {cls.site} due to T297042')

def setUp(self):
"""Set up tests."""
@@ -99,9 +98,8 @@
with self.subTest(url=url):
if lang_parse.netloc != wiki_parse.netloc:
# skip redirected url (T241413)
- self.skipTest(
- '{} is redirected to {}'
- .format(lang_parse.netloc, wiki_parse.netloc))
+ self.skipTest(f'{lang_parse.netloc} is redirected to '
+ f'{wiki_parse.netloc}')

site = Site(url=url)

diff --git a/tests/i18n_tests.py b/tests/i18n_tests.py
index f14639c..8f5522b 100755
--- a/tests/i18n_tests.py
+++ b/tests/i18n_tests.py
@@ -307,8 +307,7 @@

if cls.code in i18n.twget_keys(cls.message):
raise unittest.SkipTest(
- '{} has a translation for {}'
- .format(cls.code, cls.message))
+ f'{cls.code} has a translation for {cls.message}')

def test_pagegen_i18n_input(self):
"""Test i18n.input fallback via pwb."""
diff --git a/tests/l10n_tests.py b/tests/l10n_tests.py
index 18a0b32..0fb0327 100755
--- a/tests/l10n_tests.py
+++ b/tests/l10n_tests.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Test valid templates."""
#
-# (C) Pywikibot team, 2015-2022
+# (C) Pywikibot team, 2015-2024
#
# Distributed under the terms of the MIT license.
#
@@ -76,12 +76,10 @@
keys = i18n.twget_keys(package)
for code in codes:
current_site = pywikibot.Site(code, dct['family'])
- test_name = ('test_{}_{}'
- .format(package, code)).replace('-', '_')
+ test_name = f'test_{package}_{code}'.replace('-', '_')
cls.add_method(
dct, test_name, test_method(current_site, package),
- doc_suffix='{} and language {}'.format(
- package, code))
+ doc_suffix=f'{package} and language {code}')

return super().__new__(cls, name, bases, dct)

@@ -131,9 +129,10 @@
for key in bundle.keys():
if key == '@metadata':
continue
- self.assertTrue(key.startswith(dirname),
- '{!r} does not start with {!r}'
- .format(key, dirname))
+ self.assertTrue(
+ key.startswith(dirname),
+ f'{key!r} does not start with {dirname!r}'
+ )


if __name__ == '__main__': # pragma: no cover
diff --git a/tests/namespace_tests.py b/tests/namespace_tests.py
index 6b5044c..447575c 100755
--- a/tests/namespace_tests.py
+++ b/tests/namespace_tests.py
@@ -293,13 +293,11 @@

with self.subTest(name=name, ns_id=ns_id):
if name.isupper():
- result = eval('self.namespaces.{name}.id'
- .format(name=name))
+ result = eval(f'self.namespaces.{name}.id')
self.assertEqual(result, ns_id)
else:
with self.assertRaises(AttributeError):
- exec('self.namespaces.{name}.id'
- .format(name=name))
+ exec(f'self.namespaces.{name}.id')

def test_lookup_normalized_name(self):
"""Test lookup_normalized_name."""
diff --git a/tests/page_tests.py b/tests/page_tests.py
index 075c79e..f04a467 100755
--- a/tests/page_tests.py
+++ b/tests/page_tests.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Tests for the page module."""
#
-# (C) Pywikibot team, 2008-2023
+# (C) Pywikibot team, 2008-2024
#
# Distributed under the terms of the MIT license.
#
@@ -481,8 +481,7 @@
mainpage = self.get_mainpage()
maintalk = mainpage.toggleTalkPage()
if not maintalk.exists():
- self.skipTest("No talk page for {}'s main page"
- .format(self.get_site()))
+ self.skipTest(f"No talk page for {self.get_site()}'s main page")
self.assertIsInstance(maintalk.get(get_redirect=True), str)
self.assertEqual(mainpage.toggleTalkPage(), maintalk)
self.assertEqual(maintalk.toggleTalkPage(), mainpage)
@@ -685,7 +684,7 @@
def test_unicode_value(self):
"""Test to capture actual Python result pre unicode_literals."""
self.assertEqual(repr(self.page), "Page('Ō')")
- self.assertEqual('%r' % self.page, "Page('Ō')")
+ self.assertEqual(f'{self.page!r}', "Page('Ō')")
self.assertEqual(f'{self.page!r}', "Page('Ō')")


@@ -1027,8 +1026,8 @@
def test_watch(self):
"""Test Page.watch, with and without unwatch enabled."""
if not self.site.has_right('editmywatchlist'):
- self.skipTest('user {} cannot edit its watch list'
- .format(self.site.user()))
+ self.skipTest(
+ f'user {self.site.user()} cannot edit its watch list')

# Note: this test uses the userpage, so that it is unwatched and
# therefore is not listed by script_tests test_watchlist_simulate.
@@ -1249,8 +1248,8 @@
if not meta.logged_in():
meta.login()
if not meta.user():
- self.skipTest('{}: Not able to login to {}'
- .format(type(self).__name__, meta))
+ self.skipTest(
+ f'{type(self).__name__}: Not able to login to {meta}')

site = self.get_site()
p1 = pywikibot.Page(site, 'User:Framawiki/pwb_tests/shortlink')
diff --git a/tests/pagegenerators_tests.py b/tests/pagegenerators_tests.py
index c27ac84..fc5e5e7 100755
--- a/tests/pagegenerators_tests.py
+++ b/tests/pagegenerators_tests.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Test pagegenerators module."""
#
-# (C) Pywikibot team, 2009-2023
+# (C) Pywikibot team, 2009-2024
#
# Distributed under the terms of the MIT license.
from __future__ import annotations
@@ -506,9 +506,8 @@
site = self.get_site()
# Some languages are missing (T85681)
if site.lang not in date.formats['YearBC']:
- self.skipTest(
- 'Date formats for {!r} language are missing from date.py'
- .format(site.lang))
+ self.skipTest(f'Date formats for {site.lang!r} language are'
+ ' missing from date.py')
start = -20
end = 2026

@@ -1118,8 +1117,8 @@
def test_recentchanges_default(self):
"""Test recentchanges generator with default namespace setting."""
if self.site.family.name in ('wpbeta', 'wsbeta'):
- self.skipTest('Skipping {} due to too many autoblocked users'
- .format(self.site))
+ self.skipTest(
+ f'Skipping {self.site} due to too many autoblocked users')
gf = pagegenerators.GeneratorFactory(site=self.site)
gf.handle_arg('-ns:0,1,2')
gf.handle_arg('-recentchanges:50')
@@ -1291,8 +1290,8 @@
def test_linter_generator_ns_valid_cat(self):
"""Test generator of pages with lint errors."""
if not self.site.has_extension('Linter'):
- self.skipTest('The site {} does not use Linter extension'
- .format(self.site))
+ self.skipTest(
+ f'The site {self.site} does not use Linter extension')
gf = pagegenerators.GeneratorFactory(site=self.site)
gf.handle_arg('-ns:1')
gf.handle_arg('-limit:3')
@@ -1309,8 +1308,8 @@
def test_linter_generator_invalid_cat(self):
"""Test generator of pages with lint errors."""
if not self.site.has_extension('Linter'):
- self.skipTest('The site {} does not use Linter extension'
- .format(self.site))
+ self.skipTest(
+ f'The site {self.site} does not use Linter extension')
gf = pagegenerators.GeneratorFactory(site=self.site)
with self.assertRaises(AssertionError):
gf.handle_arg('-linter:dummy')
diff --git a/tests/plural_tests.py b/tests/plural_tests.py
index 51a5219..2c71287 100755
--- a/tests/plural_tests.py
+++ b/tests/plural_tests.py
@@ -47,7 +47,7 @@
return test_static_rule

for lang, rule in plural.plural_rules.items():
- cls.add_method(dct, 'test_{}'.format(lang.replace('-', '_')),
+ cls.add_method(dct, f"test_{lang.replace('-', '_')}",
create_test(rule),
doc_suffix=f'for "{lang}"')
return super().__new__(cls, name, bases, dct)
diff --git a/tests/proofreadpage_tests.py b/tests/proofreadpage_tests.py
index 7af71e1..d547242 100755
--- a/tests/proofreadpage_tests.py
+++ b/tests/proofreadpage_tests.py
@@ -443,8 +443,7 @@
"""Check whether bs4 module is installed already."""
if not has_module('bs4'):
unittest_print(
- 'all tests ({module}.{name})\n{doc}.. '
- .format(module=__name__, doc=cls.__doc__, name=cls.__name__),
+ f'all tests ({__name__}.{cls.__name__})\n{cls.__doc__}.. ',
end='\n')
cls.skipTest(cls, 'bs4 not installed')
super().setUpClass()
diff --git a/tests/script_tests.py b/tests/script_tests.py
index d705e53..d59eb01 100755
--- a/tests/script_tests.py
+++ b/tests/script_tests.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Test that each script can be compiled and executed."""
#
-# (C) Pywikibot team, 2014-2023
+# (C) Pywikibot team, 2014-2024
#
# Distributed under the terms of the MIT license.
#
@@ -38,9 +38,8 @@
if script_name in script_deps:
for package_name in script_deps[script_name]:
if not has_module(package_name):
- unittest_print(
- "{} depends on {}, which isn't available"
- .format(script_name, package_name))
+ unittest_print(f'{script_name} depends on {package_name},'
+ " which isn't available")
return False
return True

@@ -265,8 +264,8 @@
unittest_print(
' auto-run script stderr within {} seconds: {!r}'
.format(timeout, err_result), end=' ')
- unittest_print(' exit code: {}'
- .format(result['exit_code']), end=' ')
+ unittest_print(f" exit code: {result['exit_code']}",
+ end=' ')

self.assertNotIn('Traceback (most recent call last)',
err_result)
@@ -304,20 +303,19 @@

cls.add_method(dct, test_name,
test_execution(script_name, arguments.split()),
- 'Test running {} {}.'
- .format(script_name, arguments))
+ f'Test running {script_name} {arguments}.')

if script_name in dct['_expected_failures']:
dct[test_name] = unittest.expectedFailure(dct[test_name])
elif script_name in dct['_allowed_failures']:
dct[test_name] = unittest.skip(
- '{} is in _allowed_failures set'
- .format(script_name))(dct[test_name])
+ f'{script_name} is in _allowed_failures set'
+ )(dct[test_name])
elif script_name in failed_dep_script_set \
and arguments == '-simulate':
dct[test_name] = unittest.skip(
- '{} has dependencies; skipping'
- .format(script_name))(dct[test_name])
+ f'{script_name} has dependencies; skipping'
+ )(dct[test_name])

# Disable test by default in pytest
if script_name in unrunnable_script_set:
diff --git a/tests/site_generators_tests.py b/tests/site_generators_tests.py
index f73189a..be6007b 100755
--- a/tests/site_generators_tests.py
+++ b/tests/site_generators_tests.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Tests for generators of the site module."""
#
-# (C) Pywikibot team, 2008-2023
+# (C) Pywikibot team, 2008-2024
#
# Distributed under the terms of the MIT license.
#
@@ -594,8 +594,7 @@
levels.add(level)
if not levels:
self.skipTest(
- 'The site "{}" has no protected pages in main namespace.'
- .format(site))
+ f'The site "{site}" has no protected pages in main namespace.')
# select one level which won't yield all pages from above
level = next(iter(levels))
if len(levels) == 1:
@@ -763,8 +762,8 @@
msg=f'No images on the main page of site {mysite!r}'):
imagepage = next(page.imagelinks()) # 1st image of page

- unittest_print('site_tests.TestImageUsage found {} on {}'
- .format(imagepage, page))
+ unittest_print(
+ f'site_tests.TestImageUsage found {imagepage} on {page}')

self.__class__._image_page = imagepage
return imagepage
@@ -1545,7 +1544,7 @@
site = cls.get_site()
if site.family.name in ('wpbeta', 'wsbeta'):
cls.skipTest(cls,
- 'Skipping test on {} due to T282602' .format(site))
+ f'Skipping test on {site} due to T282602')

def test_unlimited_small_step(self):
"""Test site.randompages() continuation.
diff --git a/tests/sparql_tests.py b/tests/sparql_tests.py
index 1e8a904..99e0bb0 100755
--- a/tests/sparql_tests.py
+++ b/tests/sparql_tests.py
@@ -106,8 +106,7 @@
def testQuerySelect(self, mock_method):
"""Test SELECT query."""
mock_method.return_value = Container(
- SQL_RESPONSE_CONTAINER % '{}, {}'.format(
- ITEM_Q498787, ITEM_Q677525))
+ SQL_RESPONSE_CONTAINER % f'{ITEM_Q498787}, {ITEM_Q677525}')
with skipping(pywikibot.exceptions.TimeoutError):
q = sparql.SparqlQuery()
res = q.select('SELECT * WHERE { ?x ?y ?z }')
@@ -129,8 +128,7 @@
def testQuerySelectFull(self, mock_method):
"""Test SELECT query with full data."""
mock_method.return_value = Container(
- SQL_RESPONSE_CONTAINER % '{}, {}'.format(
- ITEM_Q498787, ITEM_Q677525))
+ SQL_RESPONSE_CONTAINER % f'{ITEM_Q498787}, {ITEM_Q677525}')
with skipping(pywikibot.exceptions.TimeoutError):
q = sparql.SparqlQuery()
res = q.select('SELECT * WHERE { ?x ?y ?z }', full_data=True)
diff --git a/tests/textlib_tests.py b/tests/textlib_tests.py
index 76662ba..c6c158f 100755
--- a/tests/textlib_tests.py
+++ b/tests/textlib_tests.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Test textlib module."""
#
-# (C) Pywikibot team, 2011-2023
+# (C) Pywikibot team, 2011-2024
#
# Distributed under the terms of the MIT license.
#
@@ -733,8 +733,7 @@
self._count += 1
if link.section:
return pywikibot.Link(
- '{}#{}'
- .format(self._count, link.section), link.site)
+ f'{self._count}#{link.section}', link.site)
return pywikibot.Link(f'{self._count}', link.site)

return None
@@ -1396,8 +1395,8 @@
"""Test replacing not inside interwiki links."""
if ('es' not in self.site.family.langs
or 'ey' in self.site.family.langs):
- raise unittest.SkipTest("family {} doesn't have languages"
- .format(self.site))
+ raise unittest.SkipTest(
+ f"family {self.site} doesn't have languages")

self.assertEqual(textlib.replaceExcept('[[es:s]]', 's', 't',
['interwiki'], site=self.site),
diff --git a/tests/timestripper_tests.py b/tests/timestripper_tests.py
index 8556b5a..00d9cf1 100755
--- a/tests/timestripper_tests.py
+++ b/tests/timestripper_tests.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Tests for archivebot.py/Timestripper."""
#
-# (C) Pywikibot team, 2014-2023
+# (C) Pywikibot team, 2014-2024
#
# Distributed under the terms of the MIT license.
#
@@ -336,8 +336,8 @@
txt_match = '[http://' + self.fake_date + ']' + self.date
self.assertEqual(ts(txt_match), self.expected_date)

- txt_match = ('{} [http://www.org | link with date {}]'
- .format(self.date, self.fake_date))
+ txt_match = (f'{self.date} [http://www.org | link with date '
+ f'{self.fake_date}]')
self.assertEqual(ts(txt_match), self.expected_date)

txt_match = '[http://' + self.fake_date + ']' + self.date
@@ -347,8 +347,10 @@
"""Test that skipping hyperlinks will not make gaps shorter."""
ts = self.ts.timestripper

- txt_match = ('{}[http://example.com Here is long enough text]{}'
- .format(self.date[:9], self.date[9:]))
+ txt_match = (
+ f'{self.date[:9]}[http://example.com Here is long enough text]'
+ f'{self.date[9:]}'
+ )
self.assertIsNone(ts(txt_match))

def test_timestripper_match_wikilink_with_date(self):
@@ -371,8 +373,8 @@
"""Test that skipping wikilinks will not make gaps shorter."""
ts = self.ts.timestripper

- txt_match = ('{}[[Here is long enough text]]{}'
- .format(self.date[:9], self.date[9:]))
+ txt_match = (f'{self.date[:9]}[[Here is long enough text]]'
+ f'{self.date[9:]}')
self.assertIsNone(ts(txt_match))

txt_match = self.date[:9] + '[[foo]]' + self.date[9:]
diff --git a/tests/ui_options_tests.py b/tests/ui_options_tests.py
index 701f359..ac1a0ee 100755
--- a/tests/ui_options_tests.py
+++ b/tests/ui_options_tests.py
@@ -137,14 +137,11 @@
f'? ({prefix}<number> [1-3])')
for i, elem in enumerate(options, 1):
self.assertTrue(option.test(f'{prefix}{i}'))
- self.assertIs(option.handled('{}{}'
- .format(prefix, i)), option)
+ self.assertIs(option.handled(f'{prefix}{i}'), option)
self.assertEqual(option.result(f'{prefix}{i}'),
(prefix, elem))
- self.assertFalse(option.test('{}{}'
- .format(prefix, len(options) + 1)))
- self.assertIsNone(option.handled('{}{}'.format(
- prefix, len(options) + 1)))
+ self.assertFalse(option.test(f'{prefix}{len(options) + 1}'))
+ self.assertIsNone(option.handled(f'{prefix}{len(options) + 1}'))

def test_showing_list(self):
"""Test ShowingListOption."""
diff --git a/tests/ui_tests.py b/tests/ui_tests.py
index 2e86b28..950dffb 100755
--- a/tests/ui_tests.py
+++ b/tests/ui_tests.py
@@ -187,8 +187,7 @@

end_str = ': Testing Exception'
self.assertTrue(stderrlines[-1].endswith(end_str),
- '\n{!r} does not end with {!r}'
- .format(stderrlines[-1], end_str))
+ f'\n{stderrlines[-1]!r} does not end with {end_str!r}')


class TestTerminalInput(UITestCase):
@@ -365,8 +364,7 @@
with self.subTest(lang=lang):
for char in digits:
self.assertIn(char, _trans,
- '{!r} not in transliteration table'
- .format(char))
+ f'{char!r} not in transliteration table')

def test_transliteration_table(self):
"""Test transliteration table consistency."""
diff --git a/tests/user_tests.py b/tests/user_tests.py
index ac6d83e..a46d88d 100755
--- a/tests/user_tests.py
+++ b/tests/user_tests.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Tests for the User page."""
#
-# (C) Pywikibot team, 2016-2023
+# (C) Pywikibot team, 2016-2024
#
# Distributed under the terms of the MIT license.
#
@@ -203,8 +203,8 @@
user = User(mysite, mysite.user())
le = list(user.logevents(total=10))
if not le:
- self.skipTest('User {} has no logevents on site {}.'
- .format(mysite.user(), mysite))
+ self.skipTest(
+ f'User {mysite.user()} has no logevents on site {mysite}.')
self.assertLessEqual(len(le), 10)
last = le[0]
self.assertEqual(last, user.last_event)
diff --git a/tests/utils.py b/tests/utils.py
index bfa2760..8057aa6 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -328,8 +328,7 @@

def submit(self):
"""Prevented method."""
- raise Exception('DryRequest rejecting request: {!r}'
- .format(self._params))
+ raise Exception(f'DryRequest rejecting request: {self._params!r}')


class DrySite(pywikibot.site.APISite):
diff --git a/tests/wikistats_tests.py b/tests/wikistats_tests.py
index 238bd15..5a3931b 100755
--- a/tests/wikistats_tests.py
+++ b/tests/wikistats_tests.py
@@ -73,8 +73,7 @@
curr = int(data[code]['good'])
self.assertGreaterEqual(
last, curr,
- '{} ({}) is greater than {} ({}).'
- .format(code, curr, last_code, last))
+ f'{code} ({curr}) is greater than {last_code} ({last}).')
last = curr
last_code = code


To view, visit change 991974. To unsubscribe, or for help writing mail filters, visit settings.

Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I5dca76b45a9f8eea21609db551b4d4a0ebe49baf
Gerrit-Change-Number: 991974
Gerrit-PatchSet: 3
Gerrit-Owner: Xqt <info@gno.de>
Gerrit-Reviewer: Xqt <info@gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged