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: Ic65f3ab3bd46678c9b604516bc5c99458207a2ff
This commit is contained in:
Takashi Kajinami 2024-10-19 23:13:58 +09:00
parent b1a299d2e2
commit d664c17409
12 changed files with 39 additions and 37 deletions

View File

@ -28,3 +28,8 @@ repos:
hooks: hooks:
- id: bandit - id: bandit
args: ['-x', 'tests', '--skip', 'B404,B603'] args: ['-x', 'tests', '--skip', 'B404,B603']
- 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. # Copyright (C) 2020 Red Hat, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -50,7 +50,7 @@ class PrivsepTimeout(Exception):
pass pass
class Serializer(object): class Serializer:
def __init__(self, writesock): def __init__(self, writesock):
self.writesock = writesock self.writesock = writesock
@ -66,7 +66,7 @@ class Serializer(object):
self.writesock.shutdown(socket.SHUT_WR) self.writesock.shutdown(socket.SHUT_WR)
class Deserializer(object): class Deserializer:
def __init__(self, readsock): def __init__(self, readsock):
self.readsock = readsock self.readsock = readsock
self.unpacker = msgpack.Unpacker( self.unpacker = msgpack.Unpacker(
@ -96,7 +96,7 @@ class Deserializer(object):
pass pass
class Future(object): class Future:
"""A very simple object to track the return of a function call""" """A very simple object to track the return of a function call"""
def __init__(self, lock, timeout=None): def __init__(self, lock, timeout=None):
@ -124,15 +124,15 @@ class Future(object):
'time elapsed: %s', self.timeout, 'time elapsed: %s', self.timeout,
(now - before).total_seconds()) (now - before).total_seconds())
return (Message.ERR.value, return (Message.ERR.value,
'%s.%s' % (PrivsepTimeout.__module__, '{}.{}'.format(PrivsepTimeout.__module__,
PrivsepTimeout.__name__), PrivsepTimeout.__name__),
'') '')
if self.error is not None: if self.error is not None:
raise self.error raise self.error
return self.data return self.data
class ClientChannel(object): class ClientChannel:
def __init__(self, sock): def __init__(self, sock):
self.running = False self.running = False
self.writer = Serializer(sock) self.writer = Serializer(sock)
@ -207,7 +207,7 @@ class ClientChannel(object):
self.reader_thread.join() self.reader_thread.join()
class ServerChannel(object): class ServerChannel:
"""Server-side twin to ClientChannel""" """Server-side twin to ClientChannel"""
def __init__(self, sock): def __init__(self, sock):

View File

@ -46,7 +46,6 @@ The privsep daemon exits when the communication channel is closed,
from concurrent import futures from concurrent import futures
import enum import enum
import errno import errno
import io
import logging as pylogging import logging as pylogging
import os import os
import platform import platform
@ -153,7 +152,7 @@ def setgid(group_id_or_name):
class PrivsepLogHandler(pylogging.Handler): class PrivsepLogHandler(pylogging.Handler):
def __init__(self, channel, processName=None): def __init__(self, channel, processName=None):
super(PrivsepLogHandler, self).__init__() super().__init__()
self.channel = channel self.channel = channel
self.processName = processName self.processName = processName
@ -183,7 +182,7 @@ class _ClientChannel(comm.ClientChannel):
def __init__(self, sock, context): def __init__(self, sock, context):
self.log = logging.getLogger(context.conf.logger_name) self.log = logging.getLogger(context.conf.logger_name)
super(_ClientChannel, self).__init__(sock) super().__init__(sock)
self.exchange_ping() self.exchange_ping()
def exchange_ping(self): def exchange_ping(self):
@ -239,7 +238,7 @@ def fdopen(fd, *args, **kwargs):
if eventlet.patcher.is_monkey_patched('socket'): if eventlet.patcher.is_monkey_patched('socket'):
return eventlet.greenio.GreenPipe(fd, *args, **kwargs) return eventlet.greenio.GreenPipe(fd, *args, **kwargs)
else: else:
return io.open(fd, *args, **kwargs) return open(fd, *args, **kwargs)
def _fd_logger(level=logging.WARN): def _fd_logger(level=logging.WARN):
@ -321,7 +320,7 @@ class ForkingClientChannel(_ClientChannel):
# parent # parent
sock_b.close() sock_b.close()
super(ForkingClientChannel, self).__init__(sock_a, context) super().__init__(sock_a, context)
class RootwrapClientChannel(_ClientChannel): class RootwrapClientChannel(_ClientChannel):
@ -371,10 +370,10 @@ class RootwrapClientChannel(_ClientChannel):
raise raise
os.rmdir(tmpdir) os.rmdir(tmpdir)
super(RootwrapClientChannel, self).__init__(sock, context) super().__init__(sock, context)
class Daemon(object): class Daemon:
"""NB: This doesn't fork() - do that yourself before calling run()""" """NB: This doesn't fork() - do that yourself before calling run()"""
def __init__(self, channel, context): def __init__(self, channel, context):
@ -478,7 +477,7 @@ class Daemon(object):
'privsep: Exception during request[%(msgid)s]: ' 'privsep: Exception during request[%(msgid)s]: '
'%(err)s', {'msgid': msgid, 'err': e}, exc_info=True) '%(err)s', {'msgid': msgid, 'err': e}, exc_info=True)
cls = e.__class__ cls = e.__class__
cls_name = '%s.%s' % (cls.__module__, cls.__name__) cls_name = '{}.{}'.format(cls.__module__, cls.__name__)
return (comm.Message.ERR.value, cls_name, e.args) return (comm.Message.ERR.value, cls_name, e.args)
def _create_done_callback(self, msgid): def _create_done_callback(self, msgid):
@ -499,18 +498,18 @@ class Daemon(object):
LOG.debug('privsep: reply[%(msgid)s]: %(reply)s', LOG.debug('privsep: reply[%(msgid)s]: %(reply)s',
{'msgid': msgid, 'reply': reply}) {'msgid': msgid, 'reply': reply})
channel.send((msgid, reply)) channel.send((msgid, reply))
except IOError: except OSError:
self.communication_error = sys.exc_info() self.communication_error = sys.exc_info()
except Exception as e: except Exception as e:
LOG.debug( LOG.debug(
'privsep: Exception during request[%(msgid)s]: ' 'privsep: Exception during request[%(msgid)s]: '
'%(err)s', {'msgid': msgid, 'err': e}, exc_info=True) '%(err)s', {'msgid': msgid, 'err': e}, exc_info=True)
cls = e.__class__ cls = e.__class__
cls_name = '%s.%s' % (cls.__module__, cls.__name__) cls_name = '{}.{}'.format(cls.__module__, cls.__name__)
reply = (comm.Message.ERR.value, cls_name, e.args) reply = (comm.Message.ERR.value, cls_name, e.args)
try: try:
channel.send((msgid, reply)) channel.send((msgid, reply))
except IOError as exc: except OSError as exc:
self.communication_error = exc self.communication_error = exc
return _call_back return _call_back

View File

@ -70,7 +70,7 @@ def logs():
class TestDaemon(base.BaseTestCase): class TestDaemon(base.BaseTestCase):
def setUp(self): def setUp(self):
super(TestDaemon, self).setUp() super().setUp()
venv_path = os.environ['VIRTUAL_ENV'] venv_path = os.environ['VIRTUAL_ENV']
self.cfg_fixture = self.useFixture(config_fixture.Config()) self.cfg_fixture = self.useFixture(config_fixture.Config())
self.cfg_fixture.config( self.cfg_fixture.config(

View File

@ -126,7 +126,7 @@ def init(root_helper=None):
_HELPER_COMMAND_PREFIX = root_helper _HELPER_COMMAND_PREFIX = root_helper
class PrivContext(object): class PrivContext:
def __init__(self, prefix, cfg_section='privsep', pypath=None, def __init__(self, prefix, cfg_section='privsep', pypath=None,
capabilities=None, logger_name='oslo_privsep.daemon', capabilities=None, logger_name='oslo_privsep.daemon',
timeout=None): timeout=None):
@ -261,7 +261,7 @@ class PrivContext(object):
def _wrap(self, func, *args, _wrap_timeout=None, **kwargs): def _wrap(self, func, *args, _wrap_timeout=None, **kwargs):
if self.client_mode: if self.client_mode:
name = '%s.%s' % (func.__module__, func.__name__) name = '{}.{}'.format(func.__module__, func.__name__)
if self.channel is not None and not self.channel.running: if self.channel is not None and not self.channel.running:
LOG.warning("RESTARTING PrivContext for %s", name) LOG.warning("RESTARTING PrivContext for %s", name)
self.stop() self.stop()

View File

@ -30,7 +30,7 @@ class UnprivilegedPrivsepFixture(fixtures.Fixture):
self.context = context self.context = context
def setUp(self): def setUp(self):
super(UnprivilegedPrivsepFixture, self).setUp() super().setUp()
self.conf = self.useFixture(cfg_fixture.Config()).conf self.conf = self.useFixture(cfg_fixture.Config()).conf
self.conf.set_override('capabilities', [], self.conf.set_override('capabilities', [],

View File

@ -19,7 +19,7 @@ from oslotest import base
from oslo_privsep import comm from oslo_privsep import comm
class BufSock(object): class BufSock:
def __init__(self): def __init__(self):
self.readpos = 0 self.readpos = 0
self.buf = io.BytesIO() self.buf = io.BytesIO()
@ -42,7 +42,7 @@ class BufSock(object):
class TestSerialization(base.BaseTestCase): class TestSerialization(base.BaseTestCase):
def setUp(self): def setUp(self):
super(TestSerialization, self).setUp() super().setUp()
sock = BufSock() sock = BufSock()
@ -93,7 +93,7 @@ class TestSerialization(base.BaseTestCase):
) )
def test_badobj(self): def test_badobj(self):
class UnknownClass(object): class UnknownClass:
pass pass
obj = UnknownClass() obj = UnknownClass()

View File

@ -75,19 +75,19 @@ def logme(level, msg, exc_info=False):
class LogRecorder(pylogging.Formatter): class LogRecorder(pylogging.Formatter):
def __init__(self, logs, *args, **kwargs): def __init__(self, logs, *args, **kwargs):
kwargs['validate'] = False kwargs['validate'] = False
super(LogRecorder, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.logs = logs self.logs = logs
def format(self, record): def format(self, record):
self.logs.append(copy.deepcopy(record)) self.logs.append(copy.deepcopy(record))
return super(LogRecorder, self).format(record) return super().format(record)
@testtools.skipIf(platform.system() != 'Linux', @testtools.skipIf(platform.system() != 'Linux',
'works only on Linux platform.') 'works only on Linux platform.')
class LogTest(testctx.TestContextTestCase): class LogTest(testctx.TestContextTestCase):
def setUp(self): def setUp(self):
super(LogTest, self).setUp() super().setUp()
def test_priv_loglevel(self): def test_priv_loglevel(self):
logger = self.useFixture(fixtures.FakeLogger( logger = self.useFixture(fixtures.FakeLogger(
@ -185,8 +185,8 @@ class DaemonTest(base.BaseTestCase):
mock_keepcaps.mock_calls) mock_keepcaps.mock_calls)
mock_dropcaps.assert_called_once_with( mock_dropcaps.assert_called_once_with(
set((capabilities.CAP_SYS_ADMIN, capabilities.CAP_NET_ADMIN)), {capabilities.CAP_SYS_ADMIN, capabilities.CAP_NET_ADMIN},
set((capabilities.CAP_SYS_ADMIN, capabilities.CAP_NET_ADMIN)), {capabilities.CAP_SYS_ADMIN, capabilities.CAP_NET_ADMIN},
[]) [])
@ -213,7 +213,7 @@ class ClientChannelTestCase(base.BaseTestCase):
} }
def setUp(self): def setUp(self):
super(ClientChannelTestCase, self).setUp() super().setUp()
context = get_fake_context() context = get_fake_context()
with mock.patch.object(comm.ClientChannel, '__init__'), \ with mock.patch.object(comm.ClientChannel, '__init__'), \
mock.patch.object(daemon._ClientChannel, 'exchange_ping'): mock.patch.object(daemon._ClientChannel, 'exchange_ping'):

View File

@ -50,12 +50,12 @@ def do_some_long(long_timeout=0.4):
class CustomError(Exception): class CustomError(Exception):
def __init__(self, code, msg): def __init__(self, code, msg):
super(CustomError, self).__init__(code, msg) super().__init__(code, msg)
self.code = code self.code = code
self.msg = msg self.msg = msg
def __str__(self): def __str__(self):
return 'Code %s: %s' % (self.code, self.msg) return 'Code {}: {}'.format(self.code, self.msg)
@testctx.context.entrypoint @testctx.context.entrypoint
@ -172,7 +172,7 @@ class SeparationTest(testctx.TestContextTestCase):
'works only on Linux platform.') 'works only on Linux platform.')
class RootwrapTest(testctx.TestContextTestCase): class RootwrapTest(testctx.TestContextTestCase):
def setUp(self): def setUp(self):
super(RootwrapTest, self).setUp() super().setUp()
testctx.context.stop() testctx.context.stop()
# Generate a command that will run daemon.helper_main without # Generate a command that will run daemon.helper_main without

View File

@ -32,7 +32,7 @@ context = priv_context.PrivContext(
class TestContextTestCase(base.BaseTestCase): class TestContextTestCase(base.BaseTestCase):
def setUp(self): def setUp(self):
super(TestContextTestCase, self).setUp() super().setUp()
privsep_fixture = self.useFixture( privsep_fixture = self.useFixture(
fixture.UnprivilegedPrivsepFixture(context)) fixture.UnprivilegedPrivsepFixture(context))
self.privsep_conf = privsep_fixture.conf self.privsep_conf = privsep_fixture.conf

View File

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