Skip to content

Commit 1bb729b

Browse files
committed
refactor Mocket into separate module
1 parent f016d34 commit 1bb729b

File tree

2 files changed

+42
-35
lines changed

2 files changed

+42
-35
lines changed

tests/mocket.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# SPDX-FileCopyrightText: 2023 Vladimír Kotal
2+
#
3+
# SPDX-License-Identifier: Unlicense
4+
5+
"""fake socket class for protocol level testing"""
6+
7+
from unittest import mock
8+
9+
10+
class Mocket:
11+
"""
12+
Mock Socket tailored for MiniMQTT testing. Records sent data,
13+
hands out pre-recorded reply.
14+
15+
Inspired by the Mocket class from Adafruit_CircuitPython_Requests
16+
"""
17+
18+
def __init__(self, to_send):
19+
self._to_send = to_send
20+
21+
self.sent = bytearray()
22+
23+
self.timeout = mock.Mock()
24+
self.connect = mock.Mock()
25+
self.close = mock.Mock()
26+
27+
def send(self, bytes_to_send):
28+
"""merely record the bytes. return the length of this bytearray."""
29+
self.sent.extend(bytes_to_send)
30+
return len(bytes_to_send)
31+
32+
# MiniMQTT checks for the presence of "recv_into" and switches behavior based on that.
33+
def recv_into(self, retbuf, bufsize):
34+
"""return data from internal buffer"""
35+
size = min(bufsize, len(self._to_send))
36+
if size == 0:
37+
return size
38+
chop = self._to_send[0:size]
39+
retbuf[0:] = chop
40+
self._to_send = self._to_send[size:]
41+
return size

tests/test_subscribe.py

Lines changed: 1 addition & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -6,47 +6,13 @@
66

77
import logging
88
import ssl
9-
from unittest import mock
109

1110
import pytest
11+
from mocket import Mocket
1212

1313
import adafruit_minimqtt.adafruit_minimqtt as MQTT
1414

1515

16-
class Mocket:
17-
"""
18-
Mock Socket tailored for MiniMQTT testing. Records sent data,
19-
hands out pre-recorded reply.
20-
21-
Inspired by the Mocket class from Adafruit_CircuitPython_Requests
22-
"""
23-
24-
def __init__(self, to_send):
25-
self._to_send = to_send
26-
27-
self.sent = bytearray()
28-
29-
self.timeout = mock.Mock()
30-
self.connect = mock.Mock()
31-
self.close = mock.Mock()
32-
33-
def send(self, bytes_to_send):
34-
"""merely record the bytes. return the length of this bytearray."""
35-
self.sent.extend(bytes_to_send)
36-
return len(bytes_to_send)
37-
38-
# MiniMQTT checks for the presence of "recv_into" and switches behavior based on that.
39-
def recv_into(self, retbuf, bufsize):
40-
"""return data from internal buffer"""
41-
size = min(bufsize, len(self._to_send))
42-
if size == 0:
43-
return size
44-
chop = self._to_send[0:size]
45-
retbuf[0:] = chop
46-
self._to_send = self._to_send[size:]
47-
return size
48-
49-
5016
# pylint: disable=unused-argument
5117
def handle_subscribe(client, user_data, topic, qos):
5218
"""

0 commit comments

Comments
 (0)