|
| 1 | +# SPDX-FileCopyrightText: 2023 Vladimír Kotal |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Unlicense |
| 4 | + |
| 5 | +"""loop() tests""" |
| 6 | + |
| 7 | +import random |
| 8 | +import socket |
| 9 | +import ssl |
| 10 | +import time |
| 11 | +from unittest import TestCase, main |
| 12 | +from unittest.mock import patch |
| 13 | + |
| 14 | +import adafruit_minimqtt.adafruit_minimqtt as MQTT |
| 15 | + |
| 16 | + |
| 17 | +class Loop(TestCase): |
| 18 | + """basic loop() test""" |
| 19 | + |
| 20 | + connect_times = [] |
| 21 | + INITIAL_RCS_VAL = 42 |
| 22 | + rcs_val = INITIAL_RCS_VAL |
| 23 | + |
| 24 | + def fake_wait_for_msg(self): |
| 25 | + """_wait_for_msg() replacement. Sleeps for 1 second and returns an integer.""" |
| 26 | + time.sleep(1) |
| 27 | + retval = self.rcs_val |
| 28 | + self.rcs_val += 1 |
| 29 | + return retval |
| 30 | + |
| 31 | + def test_loop_basic(self) -> None: |
| 32 | + """ |
| 33 | + test that loop() returns only after the specified timeout, regardless whether |
| 34 | + _wait_for_msg() returned repeatedly within that timeout. |
| 35 | + """ |
| 36 | + |
| 37 | + host = "172.40.0.3" |
| 38 | + port = 1883 |
| 39 | + |
| 40 | + mqtt_client = MQTT.MQTT( |
| 41 | + broker=host, |
| 42 | + port=port, |
| 43 | + socket_pool=socket, |
| 44 | + ssl_context=ssl.create_default_context(), |
| 45 | + ) |
| 46 | + |
| 47 | + with patch.object(mqtt_client, "_wait_for_msg") as mock_method: |
| 48 | + mock_method.side_effect = self.fake_wait_for_msg |
| 49 | + |
| 50 | + time_before = time.monotonic() |
| 51 | + timeout = random.randint(3, 8) |
| 52 | + rcs = mqtt_client.loop(timeout=timeout) |
| 53 | + time_after = time.monotonic() |
| 54 | + |
| 55 | + assert time_after - time_before >= timeout |
| 56 | + mock_method.assert_called() |
| 57 | + |
| 58 | + # Check the return value. |
| 59 | + assert rcs is not None |
| 60 | + assert len(rcs) > 1 |
| 61 | + expected_rc = self.INITIAL_RCS_VAL |
| 62 | + for ret_code in rcs: |
| 63 | + assert ret_code == expected_rc |
| 64 | + expected_rc += 1 |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + main() |
0 commit comments