Skip to content

Commit 1c25441

Browse files
authored
Merge pull request #174 from vladak/loop_is_connected
check is_connected in loop()
2 parents 926846c + 6b345de commit 1c25441

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

adafruit_minimqtt/adafruit_minimqtt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -986,7 +986,7 @@ def loop(self, timeout: float = 0) -> Optional[list[int]]:
986986
:param float timeout: return after this timeout, in seconds.
987987
988988
"""
989-
989+
self._connected()
990990
self.logger.debug(f"waiting for messages for {timeout} seconds")
991991
if self._timestamp == 0:
992992
self._timestamp = time.monotonic()

tests/test_loop.py

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,16 +44,21 @@ def test_loop_basic(self) -> None:
4444
ssl_context=ssl.create_default_context(),
4545
)
4646

47-
with patch.object(mqtt_client, "_wait_for_msg") as mock_method:
48-
mock_method.side_effect = self.fake_wait_for_msg
47+
with patch.object(
48+
mqtt_client, "_wait_for_msg"
49+
) as wait_for_msg_mock, patch.object(
50+
mqtt_client, "is_connected"
51+
) as is_connected_mock:
52+
wait_for_msg_mock.side_effect = self.fake_wait_for_msg
53+
is_connected_mock.side_effect = lambda: True
4954

5055
time_before = time.monotonic()
5156
timeout = random.randint(3, 8)
5257
rcs = mqtt_client.loop(timeout=timeout)
5358
time_after = time.monotonic()
5459

5560
assert time_after - time_before >= timeout
56-
mock_method.assert_called()
61+
wait_for_msg_mock.assert_called()
5762

5863
# Check the return value.
5964
assert rcs is not None
@@ -63,6 +68,22 @@ def test_loop_basic(self) -> None:
6368
assert ret_code == expected_rc
6469
expected_rc += 1
6570

71+
def test_loop_is_connected(self):
72+
"""
73+
loop() should throw MMQTTException if not connected
74+
"""
75+
mqtt_client = MQTT.MQTT(
76+
broker="127.0.0.1",
77+
port=1883,
78+
socket_pool=socket,
79+
ssl_context=ssl.create_default_context(),
80+
)
81+
82+
with self.assertRaises(MQTT.MMQTTException) as context:
83+
mqtt_client.loop(timeout=1)
84+
85+
assert "not connected" in str(context.exception)
86+
6687

6788
if __name__ == "__main__":
6889
main()

0 commit comments

Comments
 (0)