Skip to content

Commit

Permalink
Merge "[format] Convert format-strings to f-strings using flynt"
Browse files Browse the repository at this point in the history
  • Loading branch information
jenkins-bot authored and Gerrit Code Review committed Jan 21, 2024
2 parents 600afce + 6c281bd commit fd024ee
Show file tree
Hide file tree
Showing 23 changed files with 112 additions and 153 deletions.
9 changes: 4 additions & 5 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Package tests."""
#
# (C) Pywikibot team, 2007-2023
# (C) Pywikibot team, 2007-2024
#
# Distributed under the terms of the MIT license.
#
Expand Down Expand Up @@ -57,8 +57,7 @@ def create_path_func(base_func, subpath):
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')

Expand Down Expand Up @@ -273,8 +272,8 @@ def load_tests(loader=unittest.loader.defaultTestLoader,
# 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
Expand Down
3 changes: 1 addition & 2 deletions tests/api_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -926,8 +926,7 @@ def test_valid_lagpattern(self):
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
Expand Down
79 changes: 32 additions & 47 deletions tests/aspects.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
#
Expand Down Expand Up @@ -91,17 +91,15 @@ def assertIsEmpty(self, seq, msg=None):
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):
"""Check that the sequence is not empty."""
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):
Expand Down Expand Up @@ -217,8 +215,8 @@ def assertPagesInNamespacesAll(self, gen, namespaces, skip=False):

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)

Expand Down Expand Up @@ -296,8 +294,7 @@ def test_requirement(obj):
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
Expand Down Expand Up @@ -408,8 +405,7 @@ class SiteNotPermitted(pywikibot.site.BaseSite):
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):
Expand Down Expand Up @@ -468,8 +464,8 @@ def setUpClass(cls):

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:
Expand Down Expand Up @@ -504,8 +500,7 @@ def setUpClass(cls):

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

Expand Down Expand Up @@ -551,9 +546,8 @@ def setUpClass(cls):

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):
Expand All @@ -574,8 +568,8 @@ class RequireLoginMixin(TestCaseBase):
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):
Expand Down Expand Up @@ -604,8 +598,7 @@ def setUpClass(cls):

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):
"""
Expand Down Expand Up @@ -643,8 +636,8 @@ def _reset_login(self, skip_if_login_fails: bool = False):
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."""
Expand Down Expand Up @@ -798,9 +791,8 @@ def wrapped_method(self):

# 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.
Expand Down Expand Up @@ -927,9 +919,8 @@ class has declared are needed.
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):
Expand Down Expand Up @@ -966,13 +957,11 @@ def get_site(cls, name=None):
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
Expand Down Expand Up @@ -1214,9 +1203,8 @@ def setUpClass(cls):

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()):
Expand Down Expand Up @@ -1258,9 +1246,8 @@ def setUpClass(cls):

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,
Expand Down Expand Up @@ -1293,9 +1280,8 @@ def setUpClass(cls):
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):
Expand Down Expand Up @@ -1517,9 +1503,8 @@ def assertDeprecationFile(self, filename):
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):
Expand Down
9 changes: 3 additions & 6 deletions tests/eventstreams_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@ def test_url_parameter(self, key):
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."""
Expand All @@ -62,8 +61,7 @@ def test_url_from_site(self, key):
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())
Expand All @@ -78,8 +76,7 @@ def setUp(self):
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."""
Expand Down
3 changes: 1 addition & 2 deletions tests/family_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,7 @@ def test_each_family(self):
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:
Expand Down
10 changes: 4 additions & 6 deletions tests/generate_family_file_tests.py
Original file line number Diff line number Diff line change
@@ -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.
#
Expand Down Expand Up @@ -52,8 +52,7 @@ def setUpClass(cls):
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."""
Expand Down Expand Up @@ -99,9 +98,8 @@ def test_attributes_after_run(self):
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)

Expand Down
3 changes: 1 addition & 2 deletions tests/i18n_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,8 +307,7 @@ def setUpClass(cls):

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."""
Expand Down
15 changes: 7 additions & 8 deletions tests/l10n_tests.py
Original file line number Diff line number Diff line change
@@ -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.
#
Expand Down Expand Up @@ -76,12 +76,10 @@ def test_template(self):
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)

Expand Down Expand Up @@ -131,9 +129,10 @@ def test_package_bundles(self):
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
Expand Down
6 changes: 2 additions & 4 deletions tests/namespace_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,13 +293,11 @@ def test_getattr(self):

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."""
Expand Down
Loading

0 comments on commit fd024ee

Please sign in to comment.