Skip to content

check is_connected in loop() #174

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 4 commits into from
Nov 20, 2023
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
2 changes: 1 addition & 1 deletion adafruit_minimqtt/adafruit_minimqtt.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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()