Skip to content

Commit

Permalink
PROTON-2322/PROTON-2813: [Python] Finish PEP8 sanitization
Browse files Browse the repository at this point in the history
This is a broad but shallow change, that changes a lot of files in
fairly minor ways.
  • Loading branch information
astitcher committed Apr 12, 2024
1 parent df1e9b6 commit 39892d9
Show file tree
Hide file tree
Showing 36 changed files with 254 additions and 237 deletions.
23 changes: 18 additions & 5 deletions python/cproton.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
# under the License.
#

# Ignore unused imports in this file
# flake8: noqa: F401

import atexit
from uuid import UUID

Expand Down Expand Up @@ -202,7 +205,7 @@ def bytes2string(b, encoding='utf8'):


def py2bytes(py):
if isinstance(py, (bytes, bytearray,memoryview)):
if isinstance(py, (bytes, bytearray, memoryview)):
s = ffi.from_buffer(py)
return len(s), s
elif isinstance(py, str):
Expand Down Expand Up @@ -299,17 +302,21 @@ def pn_transport_set_pytracer(transport, tracer):
attrs['_tracer'] = tracer
lib.pn_transport_set_tracer(transport, lib.pn_pytracer)


retained_objects = set()
lib.init()


@atexit.register
def clear_retained_objects():
retained_objects.clear()


def retained_count():
""" Debugging aid to give the number of wrapper objects retained by the bindings"""
return len(retained_objects)


@ffi.def_extern()
def pn_pyref_incref(obj):
retained_objects.add(obj)
Expand Down Expand Up @@ -443,10 +450,12 @@ def pn_condition_get_description(cond):
def pn_error_text(error):
return utf82string(lib.pn_error_text(error))


# pn_data bindings
def pn_data_lookup(data, name):
return lib.pn_data_lookup(data, string2utf8(name))


def pn_data_put_decimal128(data, d):
return lib.pn_data_put_decimal128(data, py2decimal128(d))

Expand All @@ -466,6 +475,7 @@ def pn_data_put_string(data, s):
def pn_data_put_symbol(data, s):
return lib.pn_data_put_symbol(data, string2bytes(s, 'ascii'))


def pn_data_get_decimal128(data):
return decimal1282py(lib.pn_data_get_decimal128(data))

Expand Down Expand Up @@ -545,6 +555,7 @@ def pn_receiver(session, name):
def pn_delivery(link, tag):
return lib.pn_delivery(link, py2bytes(tag))


def pn_link_name(link):
return utf82string(lib.pn_link_name(link))

Expand Down Expand Up @@ -644,6 +655,7 @@ def pn_message_set_reply_to_group_id(message, value):
def pn_transport_log(transport, message):
lib.pn_transport_log(transport, string2utf8(message))


def pn_transport_get_user(transport):
return utf82string(lib.pn_transport_get_user(transport))

Expand Down Expand Up @@ -671,6 +683,7 @@ def pn_sasl_config_name(sasl, name):
def pn_sasl_config_path(sasl, path):
lib.pn_sasl_config_path(sasl, string2utf8(path))


def pn_ssl_domain_set_credentials(domain, cert_file, key_file, password):
return lib.pn_ssl_domain_set_credentials(domain, string2utf8(cert_file), string2utf8(key_file), string2utf8(password))

Expand All @@ -692,7 +705,7 @@ def pn_ssl_get_remote_subject_subfield(ssl, subfield_name):


def pn_ssl_get_remote_subject(ssl):
return utf82string(lib.pn_ssl_get_remote_subject(ssl))
return utf82string(lib.pn_ssl_get_remote_subject(ssl))


# int pn_ssl_domain_set_protocols(pn_ssl_domain_t *domain, const char *protocols);
Expand Down Expand Up @@ -727,7 +740,7 @@ def pn_ssl_get_protocol_name(ssl, size):
def pn_ssl_get_cert_fingerprint(ssl, fingerprint_len, hash_alg):
buff = ffi.new('char[]', fingerprint_len)
r = lib.pn_ssl_get_cert_fingerprint(ssl, buff, fingerprint_len, hash_alg)
if r==PN_OK:
if r == PN_OK:
return utf82string(buff)
return None

Expand All @@ -736,10 +749,10 @@ def pn_ssl_get_cert_fingerprint(ssl, fingerprint_len, hash_alg):
def pn_ssl_get_peer_hostname(ssl, size):
buff = ffi.new('char[]', size)
r = lib.pn_ssl_get_peer_hostname_py(ssl, buff, size)
if r==PN_OK:
if r == PN_OK:
return r, utf82string(buff)
return r, None


def pn_ssl_set_peer_hostname(ssl, hostname):
return lib.pn_ssl_set_peer_hostname(ssl, string2utf8(hostname))

10 changes: 5 additions & 5 deletions python/examples/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ def on_disconnected(self, event):
self.remove_stale_consumers(event.connection)

def remove_stale_consumers(self, connection):
l = connection.link_head(Endpoint.REMOTE_ACTIVE)
while l:
if l.is_sender:
self._unsubscribe(l)
l = l.next(Endpoint.REMOTE_ACTIVE)
link = connection.link_head(Endpoint.REMOTE_ACTIVE)
while link:
if link.is_sender:
self._unsubscribe(link)
link = link.next(Endpoint.REMOTE_ACTIVE)

def on_sendable(self, event):
self._queue(event.link.source.address).dispatch(event.link)
Expand Down
6 changes: 3 additions & 3 deletions python/examples/db_ctrl.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@
print(r)
elif sys.argv[1] == "insert":
while True:
l = sys.stdin.readline()
if not l:
line = sys.stdin.readline()
if not line:
break
conn.execute("INSERT INTO records(description) VALUES (?)", (l.rstrip(),))
conn.execute("INSERT INTO records(description) VALUES (?)", (line.rstrip(),))
conn.commit()
else:
print("Unrecognised command: %s" % sys.argv[1])
3 changes: 2 additions & 1 deletion python/examples/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ def on_start(self, event):
self.conn = event.container.connect(self.url, desired_capabilities="ANONYMOUS-RELAY")

def on_connection_opened(self, event):
if event.connection.remote_offered_capabilities and 'ANONYMOUS-RELAY' in event.connection.remote_offered_capabilities:
capabilities = event.connection.remote_offered_capabilities
if capabilities and 'ANONYMOUS-RELAY' in capabilities:
self.receiver = event.container.create_receiver(self.conn, self.address)
self.server = self.container.create_sender(self.conn, None)
else:
Expand Down
3 changes: 2 additions & 1 deletion python/examples/server_tx.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ def on_message(self, event):
self.container.declare_transaction(self.conn, handler=TxRequest(response, sender, event.delivery))

def on_connection_opened(self, event):
if event.connection.remote_offered_capabilities and 'ANONYMOUS-RELAY' in event.connection.remote_offered_capabilities:
capabilities = event.connection.remote_offered_capabilities
if capabilities and 'ANONYMOUS-RELAY' in capabilities:
self.relay = self.container.create_sender(self.conn, None)


Expand Down
20 changes: 10 additions & 10 deletions python/examples/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def check_call(args, **kwargs):
class ExamplesTest(unittest.TestCase):
def test_helloworld(self, example="helloworld.py"):
with run([example]) as p:
output = [l.strip() for l in p.stdout]
output = [line.strip() for line in p.stdout]
self.assertEqual(output, ['Hello World!'])

def test_helloworld_direct(self):
Expand All @@ -74,7 +74,7 @@ def test_simple_send_recv(self, recv='simple_recv.py', send='simple_send.py'):
with Popen([recv]) as r:
with run([send]):
pass
actual = [l.strip() for l in r.stdout]
actual = [line.strip() for line in r.stdout]
expected = ["{'sequence': %i}" % (i + 1,) for i in range(100)]
self.assertEqual(actual, expected)

Expand All @@ -84,12 +84,12 @@ def test_client_server(self, client=['client.py'], server=['server.py'], sleep=0
time.sleep(sleep)
with run(client) as c:
s.terminate()
actual = [l.strip() for l in c.stdout]
actual = [line.strip() for line in c.stdout]
inputs = ["Twas brillig, and the slithy toves",
"Did gire and gymble in the wabe.",
"All mimsy were the borogroves,",
"And the mome raths outgrabe."]
expected = ["%s => %s" % (l, l.upper()) for l in inputs]
expected = ["%s => %s" % (line, line.upper()) for line in inputs]
self.assertEqual(actual, expected)

def test_sync_client_server(self):
Expand Down Expand Up @@ -125,14 +125,14 @@ def test_db_send_recv(self):
pass
r.wait()
# verify output of receive
actual = [l.strip() for l in r.stdout]
actual = [line.strip() for line in r.stdout]
expected = ["inserted message %i" % (i + 1) for i in range(100)]
self.assertEqual(actual, expected)

# verify state of databases
with run(['db_ctrl.py', 'list', './dst_db']) as v:
expected = ["(%i, 'Message-%i')" % (i + 1, i + 1) for i in range(100)]
actual = [l.strip() for l in v.stdout]
actual = [line.strip() for line in v.stdout]
self.assertEqual(actual, expected)

def test_tx_send_tx_recv(self):
Expand All @@ -145,15 +145,15 @@ def test_simple_send_direct_recv(self):
with run(['simple_send.py', '-a', 'localhost:8888']):
pass
r.wait()
actual = [l.strip() for l in r.stdout]
actual = [line.strip() for line in r.stdout]
expected = ["{'sequence': %i}" % (i + 1,) for i in range(100)]
self.assertEqual(actual, expected)

def test_direct_send_simple_recv(self):
with Popen(['direct_send.py', '-a', 'localhost:8888']):
time.sleep(0.5)
with run(['simple_recv.py', '-a', 'localhost:8888']) as r:
actual = [l.strip() for l in r.stdout]
actual = [line.strip() for line in r.stdout]
expected = ["{'sequence': %i}" % (i + 1,) for i in range(100)]
self.assertEqual(actual, expected)

Expand All @@ -162,11 +162,11 @@ def test_selected_recv(self):
pass

with run(['selected_recv.py', '-m', '50']) as r:
actual = [l.strip() for l in r.stdout]
actual = [line.strip() for line in r.stdout]
expected = ["green %i" % (i + 1) for i in range(100) if i % 2 == 0]
self.assertEqual(actual, expected)

with run(['simple_recv.py', '-m', '50']) as r:
actual = [l.strip() for l in r.stdout]
actual = [line.strip() for line in r.stdout]
expected = ["red %i" % (i + 1) for i in range(100) if i % 2 == 1]
self.assertEqual(actual, expected)
24 changes: 12 additions & 12 deletions python/proton/_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ class ulong(long):
An unsigned 64 bit integer in the range :math:`0` to :math:`2^{64} - 1` inclusive.
"""

def __init__(self, l: int) -> None:
if l < 0:
def __init__(self, u64: int) -> None:
if u64 < 0:
raise AssertionError("initializing ulong with negative value")
super(ulong, self).__new__(ulong, l)
super(ulong, self).__new__(ulong, u64)

def __repr__(self) -> str:
return "ulong(%s)" % long.__repr__(self)
Expand Down Expand Up @@ -194,10 +194,10 @@ class uint(long):
A 32 bit unsigned integer in the range :math:`0` to :math:`2^{32} - 1` inclusive.
"""

def __init__(self, l: int) -> None:
if l < 0:
def __init__(self, u32: int) -> None:
if u32 < 0:
raise AssertionError("initializing uint with negative value")
super(uint, self).__new__(uint, l)
super(uint, self).__new__(uint, u32)

def __repr__(self) -> str:
return "uint(%s)" % long.__repr__(self)
Expand Down Expand Up @@ -517,11 +517,11 @@ def __init__(

def _check_list(self, t: Iterable[Any]) -> List[Any]:
""" Check all items in list are :class:`symbol`s (or are converted to symbols). """
l = []
item = []
if t:
for v in t:
l.append(_check_is_symbol(v, self.raise_on_error))
return l
item.append(_check_is_symbol(v, self.raise_on_error))
return item

def to_array(self):
return Array(UNDESCRIBED, PN_SYMBOL, *self)
Expand Down Expand Up @@ -1004,15 +1004,15 @@ def put_ulong(self, ul: Union[ulong, int]) -> None:
"""
self._check(pn_data_put_ulong(self._data, ul))

def put_long(self, l: Union[long, int]) -> None:
def put_long(self, i64: Union[long, int]) -> None:
"""
Puts a signed long value.
:param l: an integral value in the range :math:`-(2^{63})` to :math:`2^{63} - 1` inclusive.
:param i64: an integral value in the range :math:`-(2^{63})` to :math:`2^{63} - 1` inclusive.
:raise: * ``AssertionError`` if parameter is out of the range :math:`-(2^{63})` to :math:`2^{63} - 1` inclusive.
* :exc:`DataException` if there is a Proton error.
"""
self._check(pn_data_put_long(self._data, l))
self._check(pn_data_put_long(self._data, i64))

def put_timestamp(self, t: Union[timestamp, int]) -> None:
"""
Expand Down
2 changes: 1 addition & 1 deletion python/proton/_delivery.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
from ._data import dat2obj, obj2dat
from ._wrapper import Wrapper

from typing import Dict, List, Optional, Type, Union, TYPE_CHECKING, Any
from typing import Dict, List, Optional, Type, Union, TYPE_CHECKING

if TYPE_CHECKING:
from ._condition import Condition
Expand Down
19 changes: 9 additions & 10 deletions python/proton/_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ def more(self) -> bool:
return pn_collector_more(self._impl)

def pop(self) -> None:
ev = self.peek()
pn_collector_pop(self._impl)

def release(self) -> None:
Expand Down Expand Up @@ -484,9 +483,9 @@ def handler(self) -> Optional[Handler]:
If none of these has a handler, then ``None`` is returned.
"""
l = self.link
if l:
h = l.handler
link = self.link
if link:
h = link.handler
if h:
return h
s = self.session
Expand Down Expand Up @@ -572,9 +571,9 @@ def sender(self) -> Optional['Sender']:
``link`` property, that does an additional check on the type of the
link.
"""
l = self.link
if l and l.is_sender:
return l
link = self.link
if link and link.is_sender:
return link
else:
return None

Expand All @@ -585,9 +584,9 @@ def receiver(self) -> Optional['Receiver']:
none is associated with it. This is essentially an alias for
``link`` property, that does an additional check on the type of the link.
"""
l = self.link
if l and l.is_receiver:
return l
link = self.link
if link and link.is_receiver:
return link
else:
return None

Expand Down
Loading

0 comments on commit 39892d9

Please sign in to comment.