Skip to content

Commit

Permalink
Merge pull request #174 from vladak/loop_is_connected
Browse files Browse the repository at this point in the history
check is_connected in loop()
  • Loading branch information
FoamyGuy committed Nov 20, 2023
2 parents 926846c + 6b345de commit 1c25441
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
2 changes: 1 addition & 1 deletion adafruit_minimqtt/adafruit_minimqtt.py
Expand Up @@ -986,7 +986,7 @@ def loop(self, timeout: float = 0) -> Optional[list[int]]:
:param float timeout: return after this timeout, in seconds.
"""

self._connected()
self.logger.debug(f"waiting for messages for {timeout} seconds")
if self._timestamp == 0:
self._timestamp = time.monotonic()
Expand Down
27 changes: 24 additions & 3 deletions tests/test_loop.py
Expand Up @@ -44,16 +44,21 @@ def test_loop_basic(self) -> None:
ssl_context=ssl.create_default_context(),
)

with patch.object(mqtt_client, "_wait_for_msg") as mock_method:
mock_method.side_effect = self.fake_wait_for_msg
with patch.object(
mqtt_client, "_wait_for_msg"
) as wait_for_msg_mock, patch.object(
mqtt_client, "is_connected"
) as is_connected_mock:
wait_for_msg_mock.side_effect = self.fake_wait_for_msg
is_connected_mock.side_effect = lambda: True

time_before = time.monotonic()
timeout = random.randint(3, 8)
rcs = mqtt_client.loop(timeout=timeout)
time_after = time.monotonic()

assert time_after - time_before >= timeout
mock_method.assert_called()
wait_for_msg_mock.assert_called()

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

def test_loop_is_connected(self):
"""
loop() should throw MMQTTException if not connected
"""
mqtt_client = MQTT.MQTT(
broker="127.0.0.1",
port=1883,
socket_pool=socket,
ssl_context=ssl.create_default_context(),
)

with self.assertRaises(MQTT.MMQTTException) as context:
mqtt_client.loop(timeout=1)

assert "not connected" in str(context.exception)


if __name__ == "__main__":
main()

0 comments on commit 1c25441

Please sign in to comment.