Run pyupgrade to clean up Python 2 syntaxes

Update all .py source files by
 $ pyupgrade --py3-only $(git ls-files | grep ".py$")
to modernize the code according to Python 3 syntaxes.

Also add the pyupgrade hook to pre-commit to avoid merging additional
Python 2 syntaxes.

Change-Id: I904e16214939a52e42ca509ea5d5e06d59b18503
This commit is contained in:
Takashi Kajinami 2024-10-19 23:21:19 +09:00
parent b2be069675
commit 06123454ef
19 changed files with 43 additions and 40 deletions

View File

@ -1,6 +1,6 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
rev: v5.0.0
hooks:
- id: trailing-whitespace
# Replaces or checks mixed line ending
@ -19,13 +19,18 @@ repos:
- id: check-yaml
files: .*\.(yaml|yml)$
- repo: https://opendev.org/openstack/hacking
rev: 6.1.0
rev: 7.0.0
hooks:
- id: hacking
additional_dependencies: []
exclude: '^(doc|releasenotes|tools)/.*$'
- repo: https://github.com/PyCQA/bandit
rev: 1.7.6
rev: 1.7.10
hooks:
- id: bandit
args: ['-x', 'tests']
- repo: https://github.com/asottile/pyupgrade
rev: v3.18.0
hooks:
- id: pyupgrade
args: [--py3-only]

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2020 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -32,7 +32,7 @@ class NoContentTypeRequest(webob.request.Request):
ResponseClass = NoContentTypeResponse
class ConfigurableMiddleware(object):
class ConfigurableMiddleware:
"""Base WSGI middleware wrapper.
These classes require an application to be initialized that will be called

View File

@ -82,7 +82,7 @@ def authenticate(auth_file, username, password):
line_prefix = username + ':'
try:
with open(auth_file, 'r') as f:
with open(auth_file) as f:
for line in f:
entry = line.strip()
if entry and entry.startswith(line_prefix):
@ -124,7 +124,7 @@ def validate_auth_file(auth_file):
"""
try:
with open(auth_file, 'r') as f:
with open(auth_file) as f:
for line in f:
entry = line.strip()
if entry and ':' in entry:

View File

@ -74,9 +74,9 @@ def set_defaults(**kwargs):
# there's no good way for a user to override only one option, because all
# the others would be overridden to 'None'.
valid_params = set(k.name for k in CORS_OPTS
if k.name != 'allowed_origin')
passed_params = set(k for k in kwargs)
valid_params = {k.name for k in CORS_OPTS
if k.name != 'allowed_origin'}
passed_params = {k for k in kwargs}
wrong_params = passed_params - valid_params
if wrong_params:
@ -92,7 +92,7 @@ class InvalidOriginError(Exception):
def __init__(self, origin):
self.origin = origin
super(InvalidOriginError, self).__init__(
super().__init__(
'CORS request from origin \'%s\' not permitted.' % origin)
@ -117,7 +117,7 @@ class CORS(base.ConfigurableMiddleware):
]
def __init__(self, application, *args, **kwargs):
super(CORS, self).__init__(application, *args, **kwargs)
super().__init__(application, *args, **kwargs)
# Begin constructing our configuration hash.
self.allowed_origins = {}
self._init_conf()
@ -143,7 +143,7 @@ class CORS(base.ConfigurableMiddleware):
'oslo_config_project' not in local_conf):
raise TypeError("allowed_origin or oslo_config_project "
"is required")
return super(CORS, cls).factory(global_conf, **local_conf)
return super().factory(global_conf, **local_conf)
def _init_conf(self):
'''Initialize this middleware from an oslo.config instance.'''

View File

@ -388,7 +388,7 @@ Reason
"""
def __init__(self, *args, **kwargs):
super(Healthcheck, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.oslo_conf.register_opts(opts.HEALTHCHECK_OPTS,
group='healthcheck')
self._path = self._conf_get('path')
@ -430,14 +430,14 @@ Reason
'enabled at the same time.')
def _conf_get(self, key, group='healthcheck'):
return super(Healthcheck, self)._conf_get(key, group=group)
return super()._conf_get(key, group=group)
@removals.remove(
message="The healthcheck middleware must now be configured as "
"an application, not as a filter")
@classmethod
def factory(cls, global_conf, **local_conf):
return super(Healthcheck, cls).factory(global_conf, **local_conf)
return super().factory(global_conf, **local_conf)
@classmethod
def app_factory(cls, global_conf, **local_conf):
@ -539,7 +539,7 @@ Reason
def _make_html_response(self, results, healthy):
try:
hostname = socket.gethostname()
except socket.error:
except OSError:
hostname = None
translated_results = []
for result in results:

View File

@ -44,7 +44,7 @@ class DisableByFilesPortsHealthcheck(pluginbase.HealthcheckBaseExtension):
"""
def __init__(self, *args, **kwargs):
super(DisableByFilesPortsHealthcheck, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.oslo_conf.register_opts(opts.DISABLE_BY_FILES_OPTS,
group='healthcheck')
self.status_files = {}
@ -99,7 +99,7 @@ class DisableByFileHealthcheck(pluginbase.HealthcheckBaseExtension):
"""
def __init__(self, *args, **kwargs):
super(DisableByFileHealthcheck, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.oslo_conf.register_opts(opts.DISABLE_BY_FILE_OPTS,
group='healthcheck')

View File

@ -42,7 +42,7 @@ class EnableByFilesHealthcheck(pluginbase.HealthcheckBaseExtension):
"""
def __init__(self, *args, **kwargs):
super(EnableByFilesHealthcheck, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.oslo_conf.register_opts(opts.ENABLE_BY_FILES_OPTS,
group='healthcheck')
self.file_paths = self._conf_get('enable_by_file_paths')

View File

@ -16,7 +16,7 @@
import abc
class HealthcheckResult(object):
class HealthcheckResult:
"""Result of a ``healthcheck`` method call should be this object."""
def __init__(self, available, reason, details=None):

View File

@ -1,4 +1,3 @@
# -*- encoding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -33,7 +32,7 @@ class HTTPProxyToWSGI(base.ConfigurableMiddleware):
"""
def __init__(self, application, *args, **kwargs):
super(HTTPProxyToWSGI, self).__init__(application, *args, **kwargs)
super().__init__(application, *args, **kwargs)
self.oslo_conf.register_opts(OPTS, group='oslo_middleware')
@staticmethod

View File

@ -44,7 +44,7 @@ _opts = [
]
class LimitingReader(object):
class LimitingReader:
"""Reader to limit the size of an incoming request."""
def __init__(self, data, limit):
"""Initiates LimitingReader object.
@ -83,7 +83,7 @@ class RequestBodySizeLimiter(base.ConfigurableMiddleware):
"""Limit the size of incoming requests."""
def __init__(self, application, conf=None):
super(RequestBodySizeLimiter, self).__init__(application, conf)
super().__init__(application, conf)
self.oslo_conf.register_opts(_opts, group='oslo_middleware')
@webob.dec.wsgify

View File

@ -64,7 +64,7 @@ class StatsMiddleware(base.ConfigurableMiddleware):
"""
def __init__(self, application, conf):
super(StatsMiddleware, self).__init__(application, conf)
super().__init__(application, conf)
self.application = application
self.stat_name = conf.get('name')
if self.stat_name is None:

View File

@ -24,7 +24,7 @@ from oslo_middleware import correlation_id
class CorrelationIdTest(test_base.BaseTestCase):
def setUp(self):
super(CorrelationIdTest, self).setUp()
super().setUp()
def test_process_request(self):
app = mock.Mock()

View File

@ -56,7 +56,7 @@ class CORSTestBase(test_base.BaseTestCase):
def setUp(self):
"""Setup the tests."""
super(CORSTestBase, self).setUp()
super().setUp()
# Set up the config fixture.
self.config_fixture = self.useFixture(fixture.Config())
@ -132,7 +132,7 @@ class CORSTestBase(test_base.BaseTestCase):
class CORSTestDefaultOverrides(CORSTestBase):
def setUp(self):
super(CORSTestDefaultOverrides, self).setUp()
super().setUp()
fixture = self.config_fixture # Line length accommodation
@ -292,7 +292,7 @@ class CORSRegularRequestTest(CORSTestBase):
def setUp(self):
"""Setup the tests."""
super(CORSRegularRequestTest, self).setUp()
super().setUp()
fixture = self.config_fixture # Line length accommodation
fixture.load_raw_values(group='cors',
@ -613,7 +613,7 @@ class CORSPreflightRequestTest(CORSTestBase):
"""
def setUp(self):
super(CORSPreflightRequestTest, self).setUp()
super().setUp()
fixture = self.config_fixture # Line length accommodation
fixture.load_raw_values(group='cors',
@ -1146,7 +1146,7 @@ class CORSTestWildcard(CORSTestBase):
"""Test the CORS wildcard specification."""
def setUp(self):
super(CORSTestWildcard, self).setUp()
super().setUp()
fixture = self.config_fixture # Line length accommodation
fixture.load_raw_values(group='cors',

View File

@ -54,7 +54,7 @@ class HealthcheckMainTests(test_base.BaseTestCase):
class HealthcheckTests(test_base.BaseTestCase):
def setUp(self):
super(HealthcheckTests, self).setUp()
super().setUp()
self.useFixture(config.Config())
@staticmethod
@ -191,8 +191,9 @@ class HealthcheckTests(test_base.BaseTestCase):
def test_disable_by_port_many_files(self):
filename = self.create_tempfiles([('test', 'foobar')])[0]
filename2 = self.create_tempfiles([('test2', 'foobar2')])[0]
conf = {'backends': 'disable_by_files_ports',
'disable_by_file_paths': "80:%s,81:%s" % (filename, filename2)}
conf = {
'backends': 'disable_by_files_ports',
'disable_by_file_paths': "80:{},81:{}".format(filename, filename2)}
self._do_test(conf,
expected_code=webob.exc.HTTPServiceUnavailable.code,
expected_body=b'DISABLED BY FILE')

View File

@ -22,7 +22,7 @@ from oslo_middleware import http_proxy_to_wsgi
class TestHTTPProxyToWSGI(test_base.BaseTestCase):
def setUp(self):
super(TestHTTPProxyToWSGI, self).setUp()
super().setUp()
@webob.dec.wsgify()
def fake_app(req):
@ -139,7 +139,7 @@ class TestHTTPProxyToWSGI(test_base.BaseTestCase):
class TestHTTPProxyToWSGIDisabled(test_base.BaseTestCase):
def setUp(self):
super(TestHTTPProxyToWSGIDisabled, self).setUp()
super().setUp()
@webob.dec.wsgify()
def fake_app(req):

View File

@ -78,7 +78,7 @@ class TestLimitingReader(test_base.BaseTestCase):
class TestRequestBodySizeLimiter(test_base.BaseTestCase):
def setUp(self):
super(TestRequestBodySizeLimiter, self).setUp()
super().setUp()
self.useFixture(config.Config())
@webob.dec.wsgify()

View File

@ -47,7 +47,7 @@ class TestStaticMethods(test_base.BaseTestCase):
class TestStatsMiddleware(test_base.BaseTestCase):
def setUp(self):
super(TestStatsMiddleware, self).setUp()
super().setUp()
self.patch(statsd, 'StatsClient', mock.MagicMock())
def make_stats_middleware(self, stat_name=None, stats_host=None,

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at