Skip to content

Commit

Permalink
fix AbstractTransport repr socket error (#361)
Browse files Browse the repository at this point in the history
If AbstractTransport's self.sock is disconnected, then
self.sock.getpeername() will raise an error in __repr__, which shows up
in backtraces for other upstream errors.

Fix this by catching socket.error in __repr__ and putting the error info
in to the returned repr string.

Fixes #361
  • Loading branch information
nburlett authored and auvipy committed Jun 4, 2024
1 parent ec138c2 commit db7af5f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
5 changes: 4 additions & 1 deletion amqp/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,10 @@ def __init__(self, host, connect_timeout=None,
def __repr__(self):
if self.sock:
src = f'{self.sock.getsockname()[0]}:{self.sock.getsockname()[1]}'
dst = f'{self.sock.getpeername()[0]}:{self.sock.getpeername()[1]}'
try:
dst = f'{self.sock.getpeername()[0]}:{self.sock.getpeername()[1]}'
except (socket.error) as e:
dst = f'ERROR: {e}'
return f'<{type(self).__name__}: {src} -> {dst} at {id(self):#x}>'
else:
return f'<{type(self).__name__}: (disconnected) at {id(self):#x}>'
Expand Down
16 changes: 15 additions & 1 deletion t/unit/test_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ def getsockname(self):
return ('127.0.0.1', 1234)

def getpeername(self):
return ('1.2.3.4', 5671)
if self.connected:
return ('1.2.3.4', 5671)
else:
raise socket.error


TCP_KEEPIDLE = 4
Expand Down Expand Up @@ -237,6 +240,17 @@ def test_set_sockopt_opts_timeout(self):
assert expected_sndtimeo == self.socket.getsockopt(socket.SOL_TCP,
socket.SO_SNDTIMEO)

def test_transport_repr_issue_361(self):
"Regression test for https://github.com/celery/py-amqp/issues/361"
self.t = transport.Transport(self.host)
self.t.sock = MockSocket()
self.t.sock.connect(None)
assert '127.0.0.1:1234 -> 1.2.3.4:5671' in repr(self.t)

self.t.sock.connected = False
self.t.sock.close()
assert '127.0.0.1:1234 -> ERROR:' in repr(self.t)


class test_AbstractTransport:
class Transport(transport._AbstractTransport):
Expand Down

0 comments on commit db7af5f

Please sign in to comment.