Skip to content

Commit

Permalink
Merge pull request #203 from justmobilize/simplify-socket-exceptions
Browse files Browse the repository at this point in the history
Simplify socket exceptions
  • Loading branch information
brentru authored Feb 14, 2024
2 parents a05b19f + 3e5d4ab commit 4742286
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 11 deletions.
12 changes: 3 additions & 9 deletions adafruit_minimqtt/adafruit_minimqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,6 @@ def _get_connect_socket(self, host: str, port: int, *, timeout: int = 1):
connect_host = host
sock.settimeout(timeout)

last_exception = None
try:
sock.connect((connect_host, port))
except MemoryError as exc:
Expand All @@ -363,10 +362,9 @@ def _get_connect_socket(self, host: str, port: int, *, timeout: int = 1):
raise TemporaryError from exc
except OSError as exc:
sock.close()
last_exception = exc

if last_exception:
raise last_exception
self.logger.warning(f"Failed to connect: {exc}")
# Do not consider this for back-off.
raise TemporaryError from exc

self._backwards_compatible_sock = not hasattr(sock, "recv_into")
return sock
Expand Down Expand Up @@ -543,10 +541,6 @@ def connect(
except TemporaryError as e:
self.logger.warning(f"temporary error when connecting: {e}")
backoff = False
except OSError as e:
last_exception = e
self.logger.info(f"failed to connect: {e}")
backoff = True
except MMQTTException as e:
last_exception = e
self.logger.info(f"MMQT error: {e}")
Expand Down
5 changes: 3 additions & 2 deletions tests/test_port_ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class PortSslSetup(TestCase):
def test_default_port(self) -> None:
"""verify default port value and that TLS is not used"""
host = "127.0.0.1"
port = 1883
expected_port = 1883

with patch.object(socket.socket, "connect") as connect_mock:
ssl_context = ssl.create_default_context()
Expand All @@ -31,14 +31,15 @@ def test_default_port(self) -> None:
connect_retries=1,
)

connect_mock.side_effect = OSError
ssl_mock = Mock()
ssl_context.wrap_socket = ssl_mock

with self.assertRaises(MQTT.MMQTTException):
expected_port = port
mqtt_client.connect()

ssl_mock.assert_not_called()

connect_mock.assert_called()
# Assuming the repeated calls will have the same arguments.
connect_mock.assert_has_calls([call((host, expected_port))])
Expand Down

0 comments on commit 4742286

Please sign in to comment.