diff options
author | Omer Katz <omer.drow@gmail.com> | 2020-09-03 10:24:58 +0300 |
---|---|---|
committer | Omer Katz <omer.drow@gmail.com> | 2020-09-03 14:56:00 +0300 |
commit | f5bca3d670b65c04aa2bfcfd3b64905d1237047b (patch) | |
tree | f19c9a8f0f45a3fc4c60befed9ae6dca40a0bfc7 | |
parent | 84ca0ce91a58bbd0a3e22826587500debdd61ff2 (diff) | |
download | py-amqp-f5bca3d670b65c04aa2bfcfd3b64905d1237047b.tar.gz |
pyupgrade.
-rw-r--r-- | amqp/__init__.py | 1 | ||||
-rw-r--r-- | amqp/abstract_channel.py | 4 | ||||
-rw-r--r-- | amqp/basic_message.py | 2 | ||||
-rw-r--r-- | amqp/channel.py | 2 | ||||
-rw-r--r-- | amqp/connection.py | 14 | ||||
-rw-r--r-- | amqp/method_framing.py | 4 | ||||
-rw-r--r-- | amqp/sasl.py | 2 | ||||
-rw-r--r-- | amqp/serialization.py | 4 | ||||
-rw-r--r-- | amqp/transport.py | 30 | ||||
-rw-r--r-- | docs/conf.py | 3 | ||||
-rw-r--r-- | extra/update_comments_from_spec.py | 16 | ||||
-rw-r--r-- | setup.py | 3 | ||||
-rw-r--r-- | t/integration/test_integration.py | 2 | ||||
-rw-r--r-- | t/integration/test_rmq.py | 2 | ||||
-rw-r--r-- | t/unit/test_exceptions.py | 2 | ||||
-rw-r--r-- | t/unit/test_method_framing.py | 4 | ||||
-rw-r--r-- | t/unit/test_serialization.py | 2 | ||||
-rw-r--r-- | t/unit/test_transport.py | 10 | ||||
-rw-r--r-- | t/unit/test_utils.py | 8 |
19 files changed, 54 insertions, 61 deletions
diff --git a/amqp/__init__.py b/amqp/__init__.py index 15039ba..a8de91c 100644 --- a/amqp/__init__.py +++ b/amqp/__init__.py @@ -1,6 +1,5 @@ """Low-level AMQP client for Python (fork of amqplib).""" # Copyright (C) 2007-2008 Barry Pederson <bp@barryp.org> -from __future__ import absolute_import, unicode_literals import re from collections import namedtuple diff --git a/amqp/abstract_channel.py b/amqp/abstract_channel.py index 6059de4..f09c2ee 100644 --- a/amqp/abstract_channel.py +++ b/amqp/abstract_channel.py @@ -17,7 +17,7 @@ Received method %s during closing channel %s. This method will be ignored\ """ -class AbstractChannel(object): +class AbstractChannel: """Superclass for Connection and Channel. The connection is treated as channel 0, then comes @@ -120,7 +120,7 @@ class AbstractChannel(object): amqp_method = self._METHODS[method_sig] except KeyError: raise AMQPNotImplementedError( - 'Unknown AMQP method {0!r}'.format(method_sig)) + f'Unknown AMQP method {method_sig!r}') try: listeners = [self._callbacks[method_sig]] diff --git a/amqp/basic_message.py b/amqp/basic_message.py index c4e968e..222d366 100644 --- a/amqp/basic_message.py +++ b/amqp/basic_message.py @@ -101,7 +101,7 @@ class Message(GenericContent): ] def __init__(self, body='', children=None, channel=None, **properties): - super(Message, self).__init__(**properties) + super().__init__(**properties) #: set by basic_consume/basic_get self.delivery_info = None self.body = body diff --git a/amqp/channel.py b/amqp/channel.py index 5d0a343..8918210 100644 --- a/amqp/channel.py +++ b/amqp/channel.py @@ -103,7 +103,7 @@ class Channel(AbstractChannel): AMQP_LOGGER.debug('using channel_id: %s', channel_id) - super(Channel, self).__init__(connection, channel_id) + super().__init__(connection, channel_id) self.is_open = False self.active = True # Flow control diff --git a/amqp/connection.py b/amqp/connection.py index c77654d..7b34321 100644 --- a/amqp/connection.py +++ b/amqp/connection.py @@ -244,7 +244,7 @@ class Connection(AbstractChannel): self.channels = {} # The connection object itself is treated as channel 0 - super(Connection, self).__init__(self, 0) + super().__init__(self, 0) self._frame_writer = None self._on_inbound_frame = None @@ -319,7 +319,7 @@ class Connection(AbstractChannel): while not self._handshake_complete: self.drain_events(timeout=self.connect_timeout) - except (OSError, IOError, SSLError): + except (OSError, SSLError): self.collect() raise @@ -397,7 +397,7 @@ class Connection(AbstractChannel): else: raise ConnectionError( "Couldn't find appropriate auth mechanism " - "(can offer: {0}; available: {1})".format( + "(can offer: {}; available: {})".format( b", ".join(m.mechanism for m in self.authentication if m.mechanism).decode(), @@ -471,7 +471,7 @@ class Connection(AbstractChannel): for ch in channels: ch.collect() - except socket.error: + except OSError: pass # connection already closed on the other end finally: self._transport = self.connection = self.channels = None @@ -481,14 +481,14 @@ class Connection(AbstractChannel): return self._avail_channel_ids.pop() except IndexError: raise ResourceError( - 'No free channel ids, current={0}, channel_max={1}'.format( + 'No free channel ids, current={}, channel_max={}'.format( len(self.channels), self.channel_max), spec.Channel.Open) def _claim_channel_id(self, channel_id): try: return self._avail_channel_ids.remove(channel_id) except ValueError: - raise ConnectionError('Channel %r already open' % (channel_id,)) + raise ConnectionError(f'Channel {channel_id!r} already open') def channel(self, channel_id=None, callback=None): """Create new channel. @@ -592,7 +592,7 @@ class Connection(AbstractChannel): (reply_code, reply_text, method_sig[0], method_sig[1]), wait=spec.Connection.CloseOk, ) - except (OSError, IOError, SSLError): + except (OSError, SSLError): # close connection self.collect() raise diff --git a/amqp/method_framing.py b/amqp/method_framing.py index 39be438..5fe0505 100644 --- a/amqp/method_framing.py +++ b/amqp/method_framing.py @@ -36,7 +36,7 @@ def frame_handler(connection, callback, connection.bytes_recv += 1 if frame_type not in (expected_types[channel], 8): raise UnexpectedFrame( - 'Received frame {0} while expecting type: {1}'.format( + 'Received frame {} while expecting type: {}'.format( frame_type, expected_types[channel]), ) elif frame_type == 1: @@ -83,7 +83,7 @@ def frame_handler(connection, callback, return on_frame -class Buffer(object): +class Buffer: def __init__(self, buf): self.buf = buf diff --git a/amqp/sasl.py b/amqp/sasl.py index d890a1b..9a98a7a 100644 --- a/amqp/sasl.py +++ b/amqp/sasl.py @@ -7,7 +7,7 @@ from io import BytesIO from amqp.serialization import _write_table -class SASL(object): +class SASL: """The base class for all amqp SASL authentication mechanisms. You should sub-class this if you're implementing your own authentication. diff --git a/amqp/serialization.py b/amqp/serialization.py index e441c9d..90f5857 100644 --- a/amqp/serialization.py +++ b/amqp/serialization.py @@ -138,7 +138,7 @@ def _read_item(buf, offset): val = None else: raise FrameSyntaxError( - 'Unknown value in table: {0!r} ({1!r})'.format( + 'Unknown value in table: {!r} ({!r})'.format( ftype, type(ftype))) return val, offset @@ -469,7 +469,7 @@ PROPERTY_CLASSES = { } -class GenericContent(object): +class GenericContent: """Abstract base class for AMQP content. Subclasses should override the PROPERTIES attribute. diff --git a/amqp/transport.py b/amqp/transport.py index fdf20d9..dfe7cfa 100644 --- a/amqp/transport.py +++ b/amqp/transport.py @@ -23,7 +23,7 @@ EMPTY_BUFFER = bytes() SIGNED_INT_MAX = 0x7FFFFFFF # Yes, Advanced Message Queuing Protocol Protocol is redundant -AMQP_PROTOCOL_HEADER = 'AMQP\x00\x00\x09\x01'.encode('latin_1') +AMQP_PROTOCOL_HEADER = b'AMQP\x00\x00\x09\x01' # Match things like: [fe80::1]:5432, from RFC 2732 IPV6_LITERAL = re.compile(r'\[([\.0-9a-f:]+)\](?::(\d+))?') @@ -52,7 +52,7 @@ def to_host_port(host, default=AMQP_PORT): return host, port -class _AbstractTransport(object): +class _AbstractTransport: """Common superclass for TCP and SSL transports.""" def __init__(self, host, connect_timeout=None, @@ -81,7 +81,7 @@ class _AbstractTransport(object): # EINTR, EAGAIN, EWOULDBLOCK would signal that the banner # has _not_ been sent self.connected = True - except (OSError, IOError, SSLError): + except (OSError, SSLError): # if not fully connected, close socket, and reraise error if self.sock and not self.connected: self.sock.close() @@ -107,7 +107,7 @@ class _AbstractTransport(object): # Non-blocking SSL sockets can throw SSLError raise socket.timeout() raise - except socket.error as exc: + except OSError as exc: if exc.errno == errno.EWOULDBLOCK: raise socket.timeout() raise @@ -158,7 +158,7 @@ class _AbstractTransport(object): pass self.sock.settimeout(timeout) self.sock.connect(sa) - except socket.error as ex: + except OSError as ex: e = ex if self.sock is not None: self.sock.close() @@ -258,7 +258,7 @@ class _AbstractTransport(object): try: part2 = read(size - SIGNED_INT_MAX) - except (socket.timeout, socket.error, SSLError): + except (socket.timeout, OSError, SSLError): # In case this read times out, we need to make sure to not # lose part1 when we retry the read read_frame_buffer += part1 @@ -272,7 +272,7 @@ class _AbstractTransport(object): except socket.timeout: self._read_buffer = read_frame_buffer + self._read_buffer raise - except (OSError, IOError, SSLError, socket.error) as exc: + except (OSError, SSLError) as exc: if ( isinstance(exc, socket.error) and os.name == 'nt' and exc.errno == errno.EWOULDBLOCK # noqa @@ -296,14 +296,14 @@ class _AbstractTransport(object): return frame_type, channel, payload else: raise UnexpectedFrame( - 'Received {0:#04x} while expecting 0xce'.format(ch)) + f'Received {ch:#04x} while expecting 0xce') def write(self, s): try: self._write(s) except socket.timeout: raise - except (OSError, IOError, socket.error) as exc: + except OSError as exc: if exc.errno not in _UNAVAIL: self.connected = False raise @@ -315,7 +315,7 @@ class SSLTransport(_AbstractTransport): def __init__(self, host, connect_timeout=None, ssl=None, **kwargs): self.sslopts = ssl if isinstance(ssl, dict) else {} self._read_buffer = EMPTY_BUFFER - super(SSLTransport, self).__init__( + super().__init__( host, connect_timeout=connect_timeout, **kwargs) def _setup_transport(self): @@ -381,7 +381,7 @@ class SSLTransport(_AbstractTransport): while len(rbuf) < n: try: s = recv(n - len(rbuf)) # see note above - except socket.error as exc: + except OSError as exc: # ssl.sock.read may cause ENOENT if the # operation couldn't be performed (Issue celery#1414). if exc.errno in _errnos: @@ -390,7 +390,7 @@ class SSLTransport(_AbstractTransport): continue raise if not s: - raise IOError('Server unexpectedly closed connection') + raise OSError('Server unexpectedly closed connection') rbuf += s except: # noqa self._read_buffer = rbuf @@ -411,7 +411,7 @@ class SSLTransport(_AbstractTransport): # None. n = 0 if not n: - raise IOError('Socket closed') + raise OSError('Socket closed') s = s[n:] @@ -433,14 +433,14 @@ class TCPTransport(_AbstractTransport): while len(rbuf) < n: try: s = recv(n - len(rbuf)) - except socket.error as exc: + except OSError as exc: if exc.errno in _errnos: if initial and self.raise_on_initial_eintr: raise socket.timeout() continue raise if not s: - raise IOError('Server unexpectedly closed connection') + raise OSError('Server unexpectedly closed connection') rbuf += s except: # noqa self._read_buffer = rbuf diff --git a/docs/conf.py b/docs/conf.py index b24fc11..9c5e13b 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, unicode_literals - from sphinx_celery import conf globals().update(conf.build_config( diff --git a/extra/update_comments_from_spec.py b/extra/update_comments_from_spec.py index f13601a..f4d470c 100644 --- a/extra/update_comments_from_spec.py +++ b/extra/update_comments_from_spec.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, unicode_literals - import os import sys import re @@ -10,8 +8,8 @@ default_source_file = os.path.join( ) RE_COMMENTS = re.compile( - '(?P<methodsig>def\s+(?P<mname>[a-zA-Z0-9_]+)\(.*?\)' - ':\n+\s+""")(?P<comment>.*?)(?=""")', + r'(?P<methodsig>def\s+(?P<mname>[a-zA-Z0-9_]+)\(.*?\)' + ':\n+\\s+""")(?P<comment>.*?)(?=""")', re.MULTILINE | re.DOTALL ) @@ -21,7 +19,7 @@ Usage: %s <comments-file> <output-file> [<source-file>]\ def update_comments(comments_file, impl_file, result_file): - text_file = open(impl_file, 'r') + text_file = open(impl_file) source = text_file.read() comments = get_comments(comments_file) @@ -35,7 +33,7 @@ def update_comments(comments_file, impl_file, result_file): def get_comments(filename): - text_file = open(filename, 'r') + text_file = open(filename) whole_source = text_file.read() comments = {} @@ -49,11 +47,11 @@ def get_comments(filename): def replace_comment_per_def(source, result_file, def_name, new_comment): - regex = ('(?P<methodsig>def\s+' + + regex = (r'(?P<methodsig>def\s+' + def_name + - '\(.*?\):\n+\s+""".*?\n).*?(?=""")') + '\\(.*?\\):\n+\\s+""".*?\n).*?(?=""")') # print('method and comment:' + def_name + new_comment) - result = re.sub(regex, '\g<methodsig>' + new_comment, source, 0, + result = re.sub(regex, r'\g<methodsig>' + new_comment, source, 0, re.MULTILINE | re.DOTALL) return result @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- import codecs import os @@ -81,7 +80,7 @@ def reqs(f): def long_description(): try: return codecs.open('README.rst', 'r', 'utf-8').read() - except IOError: + except OSError: return 'Long description error: Missing README.rst file' diff --git a/t/integration/test_integration.py b/t/integration/test_integration.py index 27712a4..951bf9c 100644 --- a/t/integration/test_integration.py +++ b/t/integration/test_integration.py @@ -112,7 +112,7 @@ def build_frame_type_3(channel, body): return 3, channel, body -class DataComparator(object): +class DataComparator: # Comparator used for asserting serialized data. It can be used # in cases when direct comparision of bytestream cannot be used # (mainly cases of Table type where order of items can vary) diff --git a/t/integration/test_rmq.py b/t/integration/test_rmq.py index 2602630..ff13484 100644 --- a/t/integration/test_rmq.py +++ b/t/integration/test_rmq.py @@ -9,7 +9,7 @@ import amqp def get_connection( hostname, port, vhost, use_tls=False, keyfile=None, certfile=None): - host = '%s:%s' % (hostname, port) + host = f'{hostname}:{port}' if use_tls: return amqp.Connection(host=host, vhost=vhost, ssl={ 'keyfile': keyfile, diff --git a/t/unit/test_exceptions.py b/t/unit/test_exceptions.py index adcdbd0..1335bec 100644 --- a/t/unit/test_exceptions.py +++ b/t/unit/test_exceptions.py @@ -28,7 +28,7 @@ class test_AMQPError: @pytest.mark.parametrize("amqp_exception", AMQP_EXCEPTIONS) def test_str_subclass(self, amqp_exception): - exp = '<{}: unknown error>'.format(amqp_exception) + exp = f'<{amqp_exception}: unknown error>' exception_class = getattr(amqp.exceptions, amqp_exception) assert str(exception_class()) == exp diff --git a/t/unit/test_method_framing.py b/t/unit/test_method_framing.py index 05f6b72..1ece372 100644 --- a/t/unit/test_method_framing.py +++ b/t/unit/test_method_framing.py @@ -115,7 +115,7 @@ class test_frame_writer: self.write.assert_called() memory = self.write.call_args[0][0] assert isinstance(memory, memoryview) - assert '\N{CHECK MARK}'.encode('utf-8') in memory.tobytes() + assert '\N{CHECK MARK}'.encode() in memory.tobytes() assert msg.properties['content_encoding'] == 'utf-8' def test_write_slow_unicode(self): @@ -125,7 +125,7 @@ class test_frame_writer: self.write.assert_called() memory = self.write.call_args[0][0] assert isinstance(memory, bytes) - assert '\N{CHECK MARK}'.encode('utf-8') in memory + assert '\N{CHECK MARK}'.encode() in memory assert msg.properties['content_encoding'] == 'utf-8' def test_write_non_utf8(self): diff --git a/t/unit/test_serialization.py b/t/unit/test_serialization.py index 8bccc1d..134d602 100644 --- a/t/unit/test_serialization.py +++ b/t/unit/test_serialization.py @@ -11,7 +11,7 @@ from amqp.exceptions import FrameSyntaxError from amqp.serialization import GenericContent, _read_item, dumps, loads -class _ANY(object): +class _ANY: def __eq__(self, other): return other is not None diff --git a/t/unit/test_transport.py b/t/unit/test_transport.py index a1bb2b1..7152a60 100644 --- a/t/unit/test_transport.py +++ b/t/unit/test_transport.py @@ -18,11 +18,11 @@ class DummyException(Exception): pass -class MockSocket(object): +class MockSocket: options = {} def __init__(self, *args, **kwargs): - super(MockSocket, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.connected = False self.sa = None @@ -33,7 +33,7 @@ class MockSocket(object): if is_sol_socket and is_receive_or_send_timeout: self.options[key] = value elif not isinstance(value, int): - raise socket.error() + raise OSError() self.options[key] = value def getsockopt(self, family, key): @@ -174,7 +174,7 @@ class test_socket_options: self.transp.connect() def test_passing_wrong_value_options(self): - socket_settings = {TCP_KEEPINTVL: 'a'.encode()} + socket_settings = {TCP_KEEPINTVL: b'a'} self.transp = transport.Transport( self.host, self.connect_timeout, socket_settings=socket_settings, @@ -183,7 +183,7 @@ class test_socket_options: self.transp.connect() def test_passing_value_as_string(self): - socket_settings = {TCP_KEEPIDLE: '5'.encode()} + socket_settings = {TCP_KEEPIDLE: b'5'} self.transp = transport.Transport( self.host, self.connect_timeout, socket_settings=socket_settings, diff --git a/t/unit/test_utils.py b/t/unit/test_utils.py index 60f5079..af8f2c5 100644 --- a/t/unit/test_utils.py +++ b/t/unit/test_utils.py @@ -17,26 +17,26 @@ class test_coro: class test_str_to_bytes: def test_from_unicode(self): - assert isinstance(str_to_bytes(u'foo'), bytes) + assert isinstance(str_to_bytes('foo'), bytes) def test_from_bytes(self): assert isinstance(str_to_bytes(b'foo'), bytes) def test_supports_surrogates(self): bytes_with_surrogates = '\ud83d\ude4f'.encode('utf-8', 'surrogatepass') - assert str_to_bytes(u'\ud83d\ude4f') == bytes_with_surrogates + assert str_to_bytes('\ud83d\ude4f') == bytes_with_surrogates class test_bytes_to_str: def test_from_unicode(self): - assert isinstance(bytes_to_str(u'foo'), str) + assert isinstance(bytes_to_str('foo'), str) def test_from_bytes(self): assert bytes_to_str(b'foo') def test_support_surrogates(self): - assert bytes_to_str(u'\ud83d\ude4f') == u'\ud83d\ude4f' + assert bytes_to_str('\ud83d\ude4f') == '\ud83d\ude4f' class test_get_logger: |