Skip to content

Commit 75bb35b

Browse files
committed
Simplify socket exceptions
1 parent a05b19f commit 75bb35b

File tree

2 files changed

+11
-16
lines changed

2 files changed

+11
-16
lines changed

adafruit_minimqtt/adafruit_minimqtt.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,6 @@ def _get_connect_socket(self, host: str, port: int, *, timeout: int = 1):
353353
connect_host = host
354354
sock.settimeout(timeout)
355355

356-
last_exception = None
357356
try:
358357
sock.connect((connect_host, port))
359358
except MemoryError as exc:
@@ -363,10 +362,9 @@ def _get_connect_socket(self, host: str, port: int, *, timeout: int = 1):
363362
raise TemporaryError from exc
364363
except OSError as exc:
365364
sock.close()
366-
last_exception = exc
367-
368-
if last_exception:
369-
raise last_exception
365+
self.logger.warning(f"Failed to connect: {exc}")
366+
# Do not consider this for back-off.
367+
raise TemporaryError from exc
370368

371369
self._backwards_compatible_sock = not hasattr(sock, "recv_into")
372370
return sock
@@ -543,10 +541,6 @@ def connect(
543541
except TemporaryError as e:
544542
self.logger.warning(f"temporary error when connecting: {e}")
545543
backoff = False
546-
except OSError as e:
547-
last_exception = e
548-
self.logger.info(f"failed to connect: {e}")
549-
backoff = True
550544
except MMQTTException as e:
551545
last_exception = e
552546
self.logger.info(f"MMQT error: {e}")

tests/test_port_ssl.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
"""tests that verify the connect behavior w.r.t. port number and TLS"""
66

77
import socket
8-
import ssl
98
from unittest import TestCase, main
109
from unittest.mock import Mock, call, patch
1110

@@ -20,25 +19,27 @@ class PortSslSetup(TestCase):
2019
def test_default_port(self) -> None:
2120
"""verify default port value and that TLS is not used"""
2221
host = "127.0.0.1"
23-
port = 1883
22+
expected_port = 1883
2423

2524
with patch.object(socket.socket, "connect") as connect_mock:
26-
ssl_context = ssl.create_default_context()
25+
ssl_mock = Mock()
2726
mqtt_client = MQTT.MQTT(
2827
broker=host,
2928
socket_pool=socket,
30-
ssl_context=ssl_context,
29+
ssl_context=ssl_mock,
3130
connect_retries=1,
3231
)
3332

34-
ssl_mock = Mock()
35-
ssl_context.wrap_socket = ssl_mock
33+
socket_mock = Mock()
34+
connect_mock = Mock(side_effect=OSError)
35+
socket_mock.connect = connect_mock
36+
ssl_mock.wrap_socket = Mock(return_value=socket_mock)
3637

3738
with self.assertRaises(MQTT.MMQTTException):
38-
expected_port = port
3939
mqtt_client.connect()
4040

4141
ssl_mock.assert_not_called()
42+
4243
connect_mock.assert_called()
4344
# Assuming the repeated calls will have the same arguments.
4445
connect_mock.assert_has_calls([call((host, expected_port))])

0 commit comments

Comments
 (0)