Skip to content

Commit

Permalink
Enable more Ruff rules for tests; fix issues
Browse files Browse the repository at this point in the history
  • Loading branch information
akx committed Dec 24, 2023
1 parent 933699a commit c0e5dcb
Show file tree
Hide file tree
Showing 7 changed files with 38 additions and 41 deletions.
10 changes: 9 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ ignore = []
line-length = 167

[tool.ruff.per-file-ignores]
"{test,tests,examples}/**/*.py" = [
"{examples,test}/**/*.py" = [
"B",
"E402",
"E711",
Expand All @@ -100,3 +100,11 @@ line-length = 167
"S",
"UP",
]
"tests/**/*.py" = [
"E402",
"F811",
"F841",
"S101",
"S105",
"S106",
]
11 changes: 5 additions & 6 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
import time
import unicodedata

import pytest

import paho.mqtt.client as client
import pytest

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

# Import test fixture
from testsupport.broker import fake_broker
from testsupport.broker import fake_broker # noqa: F401


@pytest.mark.parametrize("proto_ver", [
(client.MQTTv31),
(client.MQTTv311),
])
class Test_connect(object):
class Test_connect:
"""
Tests on connect/disconnect behaviour of the client
"""
Expand Down Expand Up @@ -105,14 +104,14 @@ def on_connect(mqttc, obj, flags, rc):
mqttc.loop_stop()


class TestPublishBroker2Client(object):
class TestPublishBroker2Client:

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

def on_message(client, userdata, msg):
with pytest.raises(UnicodeDecodeError):
msg.topic
assert msg.topic
client.disconnect()

mqttc.on_message = on_message
Expand Down
5 changes: 2 additions & 3 deletions tests/test_matcher.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import pytest

import paho.mqtt.client as client
import pytest


class Test_client_function(object):
class Test_client_function:
"""
Tests on topic_matches_sub function in the client module
"""
Expand Down
21 changes: 8 additions & 13 deletions tests/test_mqttv5.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,16 @@
*******************************************************************
"""

import getopt
import logging
import sys
import threading
import time
import traceback
import unittest

import paho.mqtt
import paho.mqtt.client
from paho.mqtt.packettypes import PacketTypes
from paho.mqtt.properties import Properties
from paho.mqtt.reasoncodes import ReasonCodes
from paho.mqtt.subscribeoptions import SubscribeOptions


Expand Down Expand Up @@ -118,7 +115,7 @@ def register(self, client):

def cleanRetained(port):
callback = Callbacks()
curclient = paho.mqtt.client.Client("clean retained".encode("utf-8"),
curclient = paho.mqtt.client.Client(b"clean retained",
protocol=paho.mqtt.client.MQTTv5)
curclient.loop_start()
callback.register(curclient)
Expand Down Expand Up @@ -164,8 +161,8 @@ def setUpClass(cls):
sys.path.append("paho.mqtt.testing/interoperability/")
try:
import mqtt.brokers
except ImportError:
raise unittest.SkipTest("paho.mqtt.testing not present.")
except ImportError as ie:
raise unittest.SkipTest("paho.mqtt.testing not present.") from ie

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

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

bclient = paho.mqtt.client.Client("bclient".encode(
"utf-8"), protocol=paho.mqtt.client.MQTTv5)
bclient = paho.mqtt.client.Client(b"bclient", protocol=paho.mqtt.client.MQTTv5)
callback2.register(bclient)

@classmethod
Expand Down Expand Up @@ -368,7 +363,7 @@ def test_offline_message_queueing(self):
# message queueing for offline clients
cleanRetained(self._test_broker_port)
ocallback = Callbacks()
clientid = "offline message queueing".encode("utf-8")
clientid = b"offline message queueing"

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

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

ocallback = Callbacks()
clientid = "subscribe failure".encode("utf-8")
clientid = b"subscribe failure"
oclient = paho.mqtt.client.Client(
clientid, protocol=paho.mqtt.client.MQTTv5)
ocallback.register(oclient)
Expand Down
23 changes: 11 additions & 12 deletions tests/test_websocket_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@
import socketserver
from collections import OrderedDict

import pytest
from testsupport.broker import fake_websocket_broker

import paho.mqtt.client as client
import pytest
from paho.mqtt.client import WebsocketConnectionError
from testsupport.broker import fake_websocket_broker # noqa: F401


@pytest.fixture
Expand All @@ -32,7 +31,7 @@ def get_websocket_response(response_headers):
"""
response = "\r\n".join([
"HTTP/1.1 101 Switching Protocols",
"\r\n".join("{}: {}".format(i, j) for i, j in response_headers.items()),
"\r\n".join(f"{i}: {j}" for i, j in response_headers.items()),
"\r\n",
]).encode("utf8")

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

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

with fake_websocket_broker.serve(WebsocketHandler):
with pytest.raises(WebsocketConnectionError) as exc:
Expand All @@ -69,7 +68,7 @@ def handle(_self):
(client.MQTTv31, "MQIsdp"),
(client.MQTTv311, "MQTT"),
])
class TestBadWebsocketHeaders(object):
class TestBadWebsocketHeaders:
""" Testing for basic functionality in checking for headers """

def _get_basic_handler(self, response_headers):
Expand Down Expand Up @@ -130,7 +129,7 @@ def test_bad_secret_key(self, proto_ver, proto_name, fake_websocket_broker,
(client.MQTTv31, "MQIsdp"),
(client.MQTTv311, "MQTT"),
])
class TestValidHeaders(object):
class TestValidHeaders:
""" Testing for functionality in request/response headers """

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

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

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

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

response = self._get_callback_handler(
init_response_headers,
Expand Down
7 changes: 2 additions & 5 deletions tests/test_websockets.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import socket
import sys

from unittest.mock import Mock

import pytest

from paho.mqtt.client import WebsocketConnectionError, WebsocketWrapper


class TestHeaders(object):
class TestHeaders:
""" Make sure headers are used correctly """

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

for i in "\r\n".encode("utf8"):
for i in b"\r\n":
yield i

it = iter_response()
Expand Down
2 changes: 1 addition & 1 deletion tests/testsupport/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):

class FakeWebsocketBroker(threading.Thread):
def __init__(self):
super(FakeWebsocketBroker, self).__init__()
super().__init__()

self.host = "localhost"
self.port = 1888
Expand Down

0 comments on commit c0e5dcb

Please sign in to comment.