Skip to content

Commit

Permalink
Add additional error handling around code where an OSError may be rai…
Browse files Browse the repository at this point in the history
…sed on failed connections. Fixes #378
  • Loading branch information
michael-lazar authored and auvipy committed Dec 16, 2021
1 parent be6b5ed commit f4fd4f9
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
12 changes: 10 additions & 2 deletions amqp/transport.py
Expand Up @@ -272,15 +272,23 @@ def _write(self, s):

def close(self):
if self.sock is not None:
self._shutdown_transport()
try:
self._shutdown_transport()
except OSError:
pass

# Call shutdown first to make sure that pending messages
# reach the AMQP broker if the program exits after
# calling this method.
try:
self.sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
self.sock.close()

try:
self.sock.close()
except OSError:
pass
self.sock = None
self.connected = False

Expand Down
17 changes: 17 additions & 0 deletions t/unit/test_transport.py
Expand Up @@ -835,6 +835,23 @@ def test_shutdown_transport(self):
self.t._shutdown_transport()
assert self.t.sock is sock.unwrap()

def test_close__unwrap_error(self):
# sock.unwrap() can raise an error if the was a connection failure
# make sure the socket is properly closed and deallocated
sock = self.t.sock = Mock()
sock.unwrap.side_effect = OSError
self.t.close()
assert self.t.sock is None

def test_close__close_error(self):
# sock.close() can raise an error if the fd is invalid
# make sure the socket is properly deallocated
sock = self.t.sock = Mock()
sock.close.side_effect = OSError
self.t.close()
sock.close.assert_called_with()
assert self.t.sock is None and self.t.connected is False

def test_read_EOF(self):
self.t.sock = Mock(name='SSLSocket')
self.t.connected = True
Expand Down

0 comments on commit f4fd4f9

Please sign in to comment.