diff --git a/adafruit_minimqtt/adafruit_minimqtt.py b/adafruit_minimqtt/adafruit_minimqtt.py index cbeb8f6..a102ef0 100644 --- a/adafruit_minimqtt/adafruit_minimqtt.py +++ b/adafruit_minimqtt/adafruit_minimqtt.py @@ -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() diff --git a/tests/test_loop.py b/tests/test_loop.py index 80ffc22..6a762fd 100644 --- a/tests/test_loop.py +++ b/tests/test_loop.py @@ -44,8 +44,13 @@ 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) @@ -53,7 +58,7 @@ def test_loop_basic(self) -> None: 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 @@ -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()