Skip to content

Commit c0e5dcb

Browse files
committed
Enable more Ruff rules for tests; fix issues
1 parent 933699a commit c0e5dcb

File tree

7 files changed

+38
-41
lines changed

7 files changed

+38
-41
lines changed

pyproject.toml

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ ignore = []
8888
line-length = 167
8989

9090
[tool.ruff.per-file-ignores]
91-
"{test,tests,examples}/**/*.py" = [
91+
"{examples,test}/**/*.py" = [
9292
"B",
9393
"E402",
9494
"E711",
@@ -100,3 +100,11 @@ line-length = 167
100100
"S",
101101
"UP",
102102
]
103+
"tests/**/*.py" = [
104+
"E402",
105+
"F811",
106+
"F841",
107+
"S101",
108+
"S105",
109+
"S106",
110+
]

tests/test_client.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,8 @@
44
import time
55
import unicodedata
66

7-
import pytest
8-
97
import paho.mqtt.client as client
8+
import pytest
109

1110
# From http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder
1211
cmd_subfolder = os.path.realpath(
@@ -20,14 +19,14 @@
2019
import paho_test
2120

2221
# Import test fixture
23-
from testsupport.broker import fake_broker
22+
from testsupport.broker import fake_broker # noqa: F401
2423

2524

2625
@pytest.mark.parametrize("proto_ver", [
2726
(client.MQTTv31),
2827
(client.MQTTv311),
2928
])
30-
class Test_connect(object):
29+
class Test_connect:
3130
"""
3231
Tests on connect/disconnect behaviour of the client
3332
"""
@@ -105,14 +104,14 @@ def on_connect(mqttc, obj, flags, rc):
105104
mqttc.loop_stop()
106105

107106

108-
class TestPublishBroker2Client(object):
107+
class TestPublishBroker2Client:
109108

110109
def test_invalid_utf8_topic(self, fake_broker):
111110
mqttc = client.Client("client-id")
112111

113112
def on_message(client, userdata, msg):
114113
with pytest.raises(UnicodeDecodeError):
115-
msg.topic
114+
assert msg.topic
116115
client.disconnect()
117116

118117
mqttc.on_message = on_message

tests/test_matcher.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
import pytest
2-
31
import paho.mqtt.client as client
2+
import pytest
43

54

6-
class Test_client_function(object):
5+
class Test_client_function:
76
"""
87
Tests on topic_matches_sub function in the client module
98
"""

tests/test_mqttv5.py

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,16 @@
1616
*******************************************************************
1717
"""
1818

19-
import getopt
2019
import logging
2120
import sys
2221
import threading
2322
import time
24-
import traceback
2523
import unittest
2624

2725
import paho.mqtt
2826
import paho.mqtt.client
2927
from paho.mqtt.packettypes import PacketTypes
3028
from paho.mqtt.properties import Properties
31-
from paho.mqtt.reasoncodes import ReasonCodes
3229
from paho.mqtt.subscribeoptions import SubscribeOptions
3330

3431

@@ -118,7 +115,7 @@ def register(self, client):
118115

119116
def cleanRetained(port):
120117
callback = Callbacks()
121-
curclient = paho.mqtt.client.Client("clean retained".encode("utf-8"),
118+
curclient = paho.mqtt.client.Client(b"clean retained",
122119
protocol=paho.mqtt.client.MQTTv5)
123120
curclient.loop_start()
124121
callback.register(curclient)
@@ -164,8 +161,8 @@ def setUpClass(cls):
164161
sys.path.append("paho.mqtt.testing/interoperability/")
165162
try:
166163
import mqtt.brokers
167-
except ImportError:
168-
raise unittest.SkipTest("paho.mqtt.testing not present.")
164+
except ImportError as ie:
165+
raise unittest.SkipTest("paho.mqtt.testing not present.") from ie
169166

170167
cls._test_broker = threading.Thread(
171168
target=mqtt.brokers.run,
@@ -187,12 +184,10 @@ def setUpClass(cls):
187184

188185
#aclient = mqtt_client.Client(b"\xEF\xBB\xBF" + "myclientid".encode("utf-8"))
189186
#aclient = mqtt_client.Client("myclientid".encode("utf-8"))
190-
aclient = paho.mqtt.client.Client("aclient".encode(
191-
"utf-8"), protocol=paho.mqtt.client.MQTTv5)
187+
aclient = paho.mqtt.client.Client(b"aclient", protocol=paho.mqtt.client.MQTTv5)
192188
callback.register(aclient)
193189

194-
bclient = paho.mqtt.client.Client("bclient".encode(
195-
"utf-8"), protocol=paho.mqtt.client.MQTTv5)
190+
bclient = paho.mqtt.client.Client(b"bclient", protocol=paho.mqtt.client.MQTTv5)
196191
callback2.register(bclient)
197192

198193
@classmethod
@@ -368,7 +363,7 @@ def test_offline_message_queueing(self):
368363
# message queueing for offline clients
369364
cleanRetained(self._test_broker_port)
370365
ocallback = Callbacks()
371-
clientid = "offline message queueing".encode("utf-8")
366+
clientid = b"offline message queueing"
372367

373368
oclient = paho.mqtt.client.Client(
374369
clientid, protocol=paho.mqtt.client.MQTTv5)
@@ -413,7 +408,7 @@ def test_overlapping_subscriptions(self):
413408
# the server may send back one message with the highest QoS of any matching subscription, or one message for
414409
# each subscription with a matching QoS.
415410
ocallback = Callbacks()
416-
clientid = "overlapping subscriptions".encode("utf-8")
411+
clientid = b"overlapping subscriptions"
417412

418413
oclient = paho.mqtt.client.Client(
419414
clientid, protocol=paho.mqtt.client.MQTTv5)
@@ -449,7 +444,7 @@ def test_subscribe_failure(self):
449444
logging.info("Subscribe failure test starting")
450445

451446
ocallback = Callbacks()
452-
clientid = "subscribe failure".encode("utf-8")
447+
clientid = b"subscribe failure"
453448
oclient = paho.mqtt.client.Client(
454449
clientid, protocol=paho.mqtt.client.MQTTv5)
455450
ocallback.register(oclient)

tests/test_websocket_integration.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,10 @@
44
import socketserver
55
from collections import OrderedDict
66

7-
import pytest
8-
from testsupport.broker import fake_websocket_broker
9-
107
import paho.mqtt.client as client
8+
import pytest
119
from paho.mqtt.client import WebsocketConnectionError
10+
from testsupport.broker import fake_websocket_broker # noqa: F401
1211

1312

1413
@pytest.fixture
@@ -32,7 +31,7 @@ def get_websocket_response(response_headers):
3231
"""
3332
response = "\r\n".join([
3433
"HTTP/1.1 101 Switching Protocols",
35-
"\r\n".join("{}: {}".format(i, j) for i, j in response_headers.items()),
34+
"\r\n".join(f"{i}: {j}" for i, j in response_headers.items()),
3635
"\r\n",
3736
]).encode("utf8")
3837

@@ -43,7 +42,7 @@ def get_websocket_response(response_headers):
4342
(client.MQTTv31, "MQIsdp"),
4443
(client.MQTTv311, "MQTT"),
4544
])
46-
class TestInvalidWebsocketResponse(object):
45+
class TestInvalidWebsocketResponse:
4746
def test_unexpected_response(self, proto_ver, proto_name, fake_websocket_broker):
4847
""" Server responds with a valid code, but it's not what the client expected """
4948

@@ -56,7 +55,7 @@ def test_unexpected_response(self, proto_ver, proto_name, fake_websocket_broker)
5655
class WebsocketHandler(socketserver.BaseRequestHandler):
5756
def handle(_self):
5857
# Respond with data passed in to serve()
59-
_self.request.sendall("200 OK".encode("utf8"))
58+
_self.request.sendall(b"200 OK")
6059

6160
with fake_websocket_broker.serve(WebsocketHandler):
6261
with pytest.raises(WebsocketConnectionError) as exc:
@@ -69,7 +68,7 @@ def handle(_self):
6968
(client.MQTTv31, "MQIsdp"),
7069
(client.MQTTv311, "MQTT"),
7170
])
72-
class TestBadWebsocketHeaders(object):
71+
class TestBadWebsocketHeaders:
7372
""" Testing for basic functionality in checking for headers """
7473

7574
def _get_basic_handler(self, response_headers):
@@ -130,7 +129,7 @@ def test_bad_secret_key(self, proto_ver, proto_name, fake_websocket_broker,
130129
(client.MQTTv31, "MQIsdp"),
131130
(client.MQTTv311, "MQTT"),
132131
])
133-
class TestValidHeaders(object):
132+
class TestValidHeaders:
134133
""" Testing for functionality in request/response headers """
135134

136135
def _get_callback_handler(self, response_headers, check_request=None):
@@ -152,8 +151,8 @@ def handle(_self):
152151
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
153152
key = re.search("sec-websocket-key: ([A-Za-z0-9+/=]*)", decoded, re.IGNORECASE).group(1)
154153

155-
to_hash = "{:s}{:s}".format(key, GUID)
156-
hashed = hashlib.sha1(to_hash.encode("utf8"))
154+
to_hash = f"{key:s}{GUID:s}"
155+
hashed = hashlib.sha1(to_hash.encode("utf8")) # noqa: S324
157156
encoded = base64.b64encode(hashed.digest()).decode("utf8")
158157

159158
response_headers["Sec-WebSocket-Accept"] = encoded
@@ -205,7 +204,7 @@ def test_correct_path(self, proto_ver, proto_name, fake_websocket_broker,
205204
def check_path_correct(decoded):
206205
# Make sure it connects to the right path
207206
if mqtt_path:
208-
assert re.search("GET {:s} HTTP/1.1".format(mqtt_path), decoded, re.IGNORECASE) is not None
207+
assert re.search(f"GET {mqtt_path:s} HTTP/1.1", decoded, re.IGNORECASE) is not None
209208

210209
response = self._get_callback_handler(
211210
init_response_headers,
@@ -241,7 +240,7 @@ def check_headers_used(decoded):
241240
# Make sure it connects to the right path
242241
if auth_headers:
243242
for h in auth_headers:
244-
assert re.search("{:s}: {:s}".format(h, auth_headers[h]), decoded, re.IGNORECASE) is not None
243+
assert re.search(f"{h:s}: {auth_headers[h]:s}", decoded, re.IGNORECASE) is not None
245244

246245
response = self._get_callback_handler(
247246
init_response_headers,

tests/test_websockets.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
11
import socket
2-
import sys
3-
42
from unittest.mock import Mock
53

64
import pytest
7-
85
from paho.mqtt.client import WebsocketConnectionError, WebsocketWrapper
96

107

11-
class TestHeaders(object):
8+
class TestHeaders:
129
""" Make sure headers are used correctly """
1310

1411
def test_normal_headers(self):
@@ -27,7 +24,7 @@ def iter_response():
2724
for i in "\r\n".join(response).encode("utf8"):
2825
yield i
2926

30-
for i in "\r\n".encode("utf8"):
27+
for i in b"\r\n":
3128
yield i
3229

3330
it = iter_response()

tests/testsupport/broker.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
6868

6969
class FakeWebsocketBroker(threading.Thread):
7070
def __init__(self):
71-
super(FakeWebsocketBroker, self).__init__()
71+
super().__init__()
7272

7373
self.host = "localhost"
7474
self.port = 1888

0 commit comments

Comments
 (0)