|
| 1 | +import io |
| 2 | +import logging |
| 3 | +import queue |
1 | 4 | import re |
| 5 | +from collections.abc import Callable, Generator |
| 6 | +from typing import Any |
| 7 | +from unittest.mock import Mock, patch |
2 | 8 |
|
3 | 9 | import pytest |
4 | 10 | from aioresponses import aioresponses |
|
8 | 14 | from roborock.version_1_apis.roborock_mqtt_client_v1 import RoborockMqttClientV1 |
9 | 15 | from tests.mock_data import HOME_DATA_RAW, USER_DATA |
10 | 16 |
|
| 17 | +_LOGGER = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +# Used by fixtures to handle incoming requests and prepare responses |
| 21 | +RequestHandler = Callable[[bytes], bytes | None] |
| 22 | + |
| 23 | + |
| 24 | +class FakeSocketHandler: |
| 25 | + """Fake socket used by the test to simulate a connection to the broker. |
| 26 | +
|
| 27 | + The socket handler is used to intercept the socket send and recv calls and |
| 28 | + populate the response buffer with data to be sent back to the client. The |
| 29 | + handle request callback handles the incoming requests and prepares the responses. |
| 30 | + """ |
| 31 | + |
| 32 | + def __init__(self, handle_request: RequestHandler) -> None: |
| 33 | + self.response_buf = io.BytesIO() |
| 34 | + self.handle_request = handle_request |
| 35 | + |
| 36 | + def pending(self) -> int: |
| 37 | + """Return the number of bytes in the response buffer.""" |
| 38 | + return len(self.response_buf.getvalue()) |
| 39 | + |
| 40 | + def handle_socket_recv(self, read_size: int) -> bytes: |
| 41 | + """Intercept a client recv() and populate the buffer.""" |
| 42 | + if self.pending() == 0: |
| 43 | + raise BlockingIOError("No response queued") |
| 44 | + |
| 45 | + self.response_buf.seek(0) |
| 46 | + data = self.response_buf.read(read_size) |
| 47 | + _LOGGER.debug("Response: 0x%s", data.hex()) |
| 48 | + # Consume the rest of the data in the buffer |
| 49 | + remaining_data = self.response_buf.read() |
| 50 | + self.response_buf = io.BytesIO(remaining_data) |
| 51 | + return data |
| 52 | + |
| 53 | + def handle_socket_send(self, client_request: bytes) -> int: |
| 54 | + """Receive an incoming request from the client.""" |
| 55 | + _LOGGER.debug("Request: 0x%s", client_request.hex()) |
| 56 | + if (response := self.handle_request(client_request)) is not None: |
| 57 | + # Enqueue a response to be sent back to the client in the buffer. |
| 58 | + # The buffer will be emptied when the client calls recv() on the socket |
| 59 | + _LOGGER.debug("Queued: 0x%s", response.hex()) |
| 60 | + self.response_buf.write(response) |
| 61 | + |
| 62 | + return len(client_request) |
| 63 | + |
| 64 | + |
| 65 | +@pytest.fixture(name="received_requests") |
| 66 | +def received_requests_fixture() -> queue.Queue[bytes]: |
| 67 | + """Fixture that provides access to the received requests.""" |
| 68 | + return queue.Queue() |
| 69 | + |
| 70 | + |
| 71 | +@pytest.fixture(name="response_queue") |
| 72 | +def response_queue_fixture() -> queue.Queue[bytes]: |
| 73 | + """Fixture that provides access to the received requests.""" |
| 74 | + return queue.Queue() |
| 75 | + |
| 76 | + |
| 77 | +@pytest.fixture(name="request_handler") |
| 78 | +def request_handler_fixture( |
| 79 | + received_requests: queue.Queue[bytes], response_queue: queue.Queue[bytes] |
| 80 | +) -> RequestHandler: |
| 81 | + """Fixture records incoming requests and replies with responses from the queue.""" |
| 82 | + |
| 83 | + def handle_request(client_request: bytes) -> bytes | None: |
| 84 | + """Handle an incoming request from the client.""" |
| 85 | + received_requests.put(client_request) |
| 86 | + |
| 87 | + # Insert a prepared response into the response buffer |
| 88 | + if response_queue.qsize() > 0: |
| 89 | + return response_queue.get() |
| 90 | + return None |
| 91 | + |
| 92 | + return handle_request |
| 93 | + |
| 94 | + |
| 95 | +@pytest.fixture(name="fake_socket_handler") |
| 96 | +def fake_socket_handler_fixture(request_handler: RequestHandler) -> FakeSocketHandler: |
| 97 | + """Fixture that creates a fake MQTT broker.""" |
| 98 | + return FakeSocketHandler(request_handler) |
| 99 | + |
| 100 | + |
| 101 | +@pytest.fixture(name="mock_sock") |
| 102 | +def mock_sock_fixture(fake_socket_handler: FakeSocketHandler) -> Mock: |
| 103 | + """Fixture that creates a mock socket connection and wires it to the handler.""" |
| 104 | + mock_sock = Mock() |
| 105 | + mock_sock.recv = fake_socket_handler.handle_socket_recv |
| 106 | + mock_sock.send = fake_socket_handler.handle_socket_send |
| 107 | + mock_sock.pending = fake_socket_handler.pending |
| 108 | + return mock_sock |
| 109 | + |
| 110 | + |
| 111 | +@pytest.fixture(name="mock_create_connection") |
| 112 | +def create_connection_fixture(mock_sock: Mock) -> Generator[None, None, None]: |
| 113 | + """Fixture that overrides the MQTT socket creation to wire it up to the mock socket.""" |
| 114 | + with patch("paho.mqtt.client.socket.create_connection", return_value=mock_sock): |
| 115 | + yield |
| 116 | + |
| 117 | + |
| 118 | +@pytest.fixture(name="mock_select") |
| 119 | +def select_fixture(mock_sock: Mock, fake_socket_handler: FakeSocketHandler) -> Generator[None, None, None]: |
| 120 | + """Fixture that overrides the MQTT client select calls to make select work on the mock socket. |
| 121 | +
|
| 122 | + This patch select to activate our mock socket when ready with data. Internal mqtt sockets are |
| 123 | + always ready since they are used internally to wake the select loop. Ours is ready if there |
| 124 | + is data in the buffer. |
| 125 | + """ |
| 126 | + |
| 127 | + def is_ready(sock: Any) -> bool: |
| 128 | + return sock is not mock_sock or (fake_socket_handler.pending() > 0) |
| 129 | + |
| 130 | + def handle_select(rlist: list, wlist: list, *args: Any) -> list: |
| 131 | + return [list(filter(is_ready, rlist)), list(filter(is_ready, wlist))] |
| 132 | + |
| 133 | + with patch("paho.mqtt.client.select.select", side_effect=handle_select): |
| 134 | + yield |
| 135 | + |
11 | 136 |
|
12 | 137 | @pytest.fixture(name="mqtt_client") |
13 | | -def mqtt_client(): |
| 138 | +def mqtt_client(mock_create_connection: None, mock_select: None) -> Generator[RoborockMqttClientV1, None, None]: |
14 | 139 | user_data = UserData.from_dict(USER_DATA) |
15 | 140 | home_data = HomeData.from_dict(HOME_DATA_RAW) |
16 | 141 | device_info = DeviceData( |
|
0 commit comments