Skip to content

Simplify socket exceptions #203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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