Skip to content

Commit 71f9f9d

Browse files
committed
add unit test for recv timeout
1 parent 07239ac commit 71f9f9d

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

tests/test_recv_timeout.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# SPDX-FileCopyrightText: 2024 Vladimír Kotal
2+
#
3+
# SPDX-License-Identifier: Unlicense
4+
5+
"""receive timeout tests"""
6+
7+
import socket
8+
import time
9+
from unittest import TestCase, main
10+
from unittest.mock import Mock
11+
12+
import adafruit_minimqtt.adafruit_minimqtt as MQTT
13+
14+
15+
class RecvTimeout(TestCase):
16+
"""This class contains tests for receive timeout handling."""
17+
18+
def test_recv_timeout_vs_keepalive(self) -> None:
19+
"""verify that receive timeout as used via ping() is different to keep alive timeout"""
20+
host = "127.0.0.1"
21+
22+
recv_timeout = 4
23+
keep_alive = recv_timeout * 2
24+
mqtt_client = MQTT.MQTT(
25+
broker=host,
26+
socket_pool=socket,
27+
connect_retries=1,
28+
socket_timeout=recv_timeout // 2,
29+
recv_timeout=recv_timeout,
30+
keep_alive=keep_alive,
31+
)
32+
33+
# Create a mock socket that will accept anything and return nothing.
34+
socket_mock = Mock()
35+
socket_mock.recv_into = Mock(side_effect=lambda ret_buf, buf_size: 0)
36+
# pylint: disable=protected-access
37+
mqtt_client._sock = socket_mock
38+
39+
mqtt_client._connected = lambda: True
40+
start = time.monotonic()
41+
with self.assertRaises(MQTT.MMQTTException):
42+
mqtt_client.ping()
43+
44+
# Verify the mock interactions.
45+
socket_mock.send.assert_called_once()
46+
socket_mock.recv_into.assert_called()
47+
48+
now = time.monotonic()
49+
assert recv_timeout <= (now - start) < keep_alive
50+
51+
52+
if __name__ == "__main__":
53+
main()

0 commit comments

Comments
 (0)