Skip to content

Commit

Permalink
Replace Flake8 by Ruff 🚀
Browse files Browse the repository at this point in the history
  • Loading branch information
JonathanPlasse committed Nov 26, 2022
1 parent 11de810 commit cb9fa25
Show file tree
Hide file tree
Showing 9 changed files with 89 additions and 63 deletions.
3 changes: 0 additions & 3 deletions .flake8

This file was deleted.

23 changes: 8 additions & 15 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
repos:
- repo: https://github.com/asottile/pyupgrade
rev: v3.2.2
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.139
hooks:
- id: pyupgrade
args: ["--py37-plus"]

- repo: https://github.com/pycqa/isort
rev: 5.10.1
hooks:
- id: isort
- id: ruff
args:
- --fix
- --target-version
- py37

- repo: https://github.com/psf/black
rev: 22.10.0
hooks:
- id: black

- repo: https://github.com/pycqa/flake8
rev: 5.0.4
hooks:
- id: flake8

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.991
hooks:
Expand All @@ -43,7 +36,7 @@ repos:
- "~MD002,~MD007,~MD013,~MD024,~MD026,~MD029,~MD033,~MD036"

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.3.0
rev: v4.4.0
hooks:
- id: check-added-large-files
- id: check-yaml
Expand Down
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ pre-commit install
If you are using VSCode, here are the settings to activate on save,

- `black` and `isort` to format.
- `flake8` and `mypy` to lint.
- `mypy` to lint.
- Install [charliermarsh.ruff](https://marketplace.visualstudio.com/items?itemName=charliermarsh.ruff) extension to lint (`ruff` is a fast equivalent to `flake8`)

```json
{
Expand All @@ -51,7 +52,6 @@ If you are using VSCode, here are the settings to activate on save,
}
},
"python.formatting.provider": "black",
"python.linting.flake8Enabled": true,
"python.linting.mypyEnabled": true
}
```
Expand Down
51 changes: 18 additions & 33 deletions asyncio_mqtt/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,16 @@
Awaitable,
Callable,
Coroutine,
Dict,
Generator,
Iterable,
Iterator,
List,
Tuple,
Union,
cast,
)

if sys.version_info >= (3, 10):
from typing import Concatenate, ParamSpec
from typing import Concatenate, ParamSpec, TypeAlias
else:
from typing_extensions import Concatenate, ParamSpec
from typing_extensions import Concatenate, ParamSpec, TypeAlias

from contextlib import asynccontextmanager

Expand All @@ -43,18 +39,15 @@
MQTT_LOGGER = logging.getLogger("mqtt")
MQTT_LOGGER.setLevel(logging.WARNING)

_PahoSocket = Union[socket.socket, ssl.SSLSocket, mqtt.WebsocketWrapper, Any]
_PahoSocket: TypeAlias = "socket.socket | ssl.SSLSocket | mqtt.WebsocketWrapper | Any"

WebSocketHeaders = Union[
Dict[str, str],
Callable[[Dict[str, str]], Dict[str, str]],
]
WebSocketHeaders: TypeAlias = (
"dict[str, str] | Callable[[dict[str, str]], dict[str, str]]"
)


class ProtocolVersion(IntEnum):
"""
A mapping of Paho MQTT protocol version constants to an Enum for use in type hints.
"""
"""A mapping of Paho MQTT protocol version constants to an Enum for use in type hints."""

V31 = mqtt.MQTTv31
V311 = mqtt.MQTTv311
Expand Down Expand Up @@ -103,17 +96,9 @@ def __init__(


# See the overloads of `socket.setsockopt` for details.
SocketOption = Union[
Tuple[int, int, Union[int, bytes]],
Tuple[int, int, None, int],
]

SubscribeTopic = Union[
str,
Tuple[str, mqtt.SubscribeOptions],
List[Tuple[str, mqtt.SubscribeOptions]],
List[Tuple[str, int]],
]
SocketOption: TypeAlias = "tuple[int, int, int | bytes] | tuple[int, int, None, int]"

SubscribeTopic: TypeAlias = "str | tuple[str, mqtt.SubscribeOptions] | list[tuple[str, mqtt.SubscribeOptions]] | list[tuple[str, int]]"

P = ParamSpec("P")

Expand All @@ -135,7 +120,7 @@ async def decorated(self: Client, *args: P.args, **kwargs: P.kwargs) -> T:


class Client:
def __init__(
def __init__( # noqa: C901
self,
hostname: str,
port: int = 1883,
Expand Down Expand Up @@ -249,7 +234,9 @@ def __init__(
self._socket_options = tuple(socket_options)

@property
def id(self) -> str:
def id( # noqa: A003 # TODO: When doing BREAKING CHANGES rename to avoid shadowing builtin id
self,
) -> str:
"""Return the client ID.
Note that paho-mqtt stores the client ID as `bytes` internally.
Expand All @@ -260,9 +247,7 @@ def id(self) -> str:

@property
def _pending_calls(self) -> Generator[int, None, None]:
"""
Yield all message IDs with pending calls.
"""
"""Yield all message IDs with pending calls."""
yield from self._pending_subscribes.keys()
yield from self._pending_unsubscribes.keys()
yield from self._pending_publishes.keys()
Expand Down Expand Up @@ -290,7 +275,7 @@ async def connect(self, *, timeout: int = 10) -> None:
# We convert all of them to the common MqttError for user convenience.
# See: https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L1770
except (OSError, mqtt.WebsocketConnectionError) as error:
raise MqttError(str(error))
raise MqttError(str(error)) from None
await self._wait_for(self._connected, timeout=timeout)

async def disconnect(self, *, timeout: int = 10) -> None:
Expand Down Expand Up @@ -479,7 +464,7 @@ async def _wait_for(
try:
return await asyncio.wait_for(fut, timeout=timeout, **kwargs)
except asyncio.TimeoutError:
raise MqttError("Operation timed out")
raise MqttError("Operation timed out") from None

@contextmanager
def _pending_call(
Expand Down Expand Up @@ -579,7 +564,7 @@ def _on_unsubscribe(
userdata: Any,
mid: int,
properties: mqtt.Properties | None = None,
reasonCodes: list[mqtt.ReasonCodes] | mqtt.ReasonCodes | None = None,
reason_codes: list[mqtt.ReasonCodes] | mqtt.ReasonCodes | None = None,
) -> None:
try:
self._pending_unsubscribes.pop(mid).set()
Expand Down
10 changes: 8 additions & 2 deletions asyncio_mqtt/types.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
from typing import Optional, TypeVar, Union
import sys
from typing import TypeVar

if sys.version_info >= (3, 10):
from typing import TypeAlias
else:
from typing_extensions import TypeAlias

T = TypeVar("T")

PayloadType = Optional[Union[str, bytes, bytearray, int, float]]
PayloadType: TypeAlias = "str | bytes | bytearray | int | float | None"
45 changes: 44 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ dynamic = ["version"]
"Issue tracker" = "https://github.com/sbtinstruments/asyncio-mqtt/issues"

[project.optional-dependencies]
lint = ["mypy>=0.982", "flake8>=5.0.4", "types-paho-mqtt>=1.6.0.1"]
lint = ["mypy>=0.982", "ruff>=0.0.124", "types-paho-mqtt>=1.6.0.1"]
format = ["black>=22.10.0", "isort>=5.10.1"]
tests = ["pytest>=7.2.0", "pytest-cov>=4.0.0", "anyio>=3.6.2"]

Expand All @@ -54,6 +54,49 @@ write_to = "asyncio_mqtt/_version.py"
[tool.isort]
profile = "black"

[tool.ruff]
select = [
"A", # builtins
"B", # bugbear
"C4", # comprehensions
"C90", # mccabe
"D", # docstring
"E", # style errors
"F", # flakes
"I", # import sorting
"M", # meta
"N", # naming
"Q", # quotes
"RUF", # ruff
"S", # bandit
"T", # print
"U", # upgrade
"W", # style warnings
"YTT", # sys.version
]
ignore = [
"D10", # Missing docstring
"D203", # PEP8 docstring convention
"D212",
"D213",
"D214",
"D215",
"D404",
"D405",
"D406",
"D407",
"D408",
"D409",
"D410",
"D411",
"D413",
"D415",
"D416",
"D417",
"E501", # Line too long
"S101", # Use of `assert` detected
]

[tool.mypy]
strict = true
show_error_codes = true
Expand Down
Empty file added tests/__init__.py
Empty file.
4 changes: 3 additions & 1 deletion tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,9 @@ async def handle_messages(tg: anyio.abc.TaskGroup) -> None:
assert message.topic == topic
tg.cancel_scope.cancel()

async with Client(HOSTNAME, username="asyncio-mqtt", password="012") as client:
async with Client(
HOSTNAME, username="asyncio-mqtt", password="012" # noqa: S106
) as client:
async with anyio.create_task_group() as tg:
await client.subscribe(topic)
tg.start_soon(handle_messages, tg)
Expand Down
12 changes: 6 additions & 6 deletions tests/test_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@ def test_mqtt_code_error_int(rc: int) -> None:


@pytest.mark.parametrize(
"packetType, aName",
"packet_type, a_name",
(
(PacketTypes.CONNACK, "Success"),
(PacketTypes.PUBACK, "Success"),
(PacketTypes.SUBACK, "Granted QoS 1"),
),
)
def test_mqtt_code_error_reason_codes(packetType: int, aName: str) -> None:
rc = mqtt.ReasonCodes(packetType, aName)
def test_mqtt_code_error_reason_codes(packet_type: int, a_name: str) -> None:
rc = mqtt.ReasonCodes(packet_type, a_name)
assert str(MqttCodeError(rc)) == f"[code:{rc.value}] {str(rc)}"


Expand All @@ -60,13 +60,13 @@ def test_mqtt_connect_error_int(rc: int, message: str) -> None:


@pytest.mark.parametrize(
"packetType, aName",
"packet_type, a_name",
(
(PacketTypes.CONNACK, "Success"),
(PacketTypes.PUBACK, "Success"),
(PacketTypes.SUBACK, "Granted QoS 1"),
),
)
def test_mqtt_connect_error_reason_codes(packetType: int, aName: str) -> None:
rc = mqtt.ReasonCodes(packetType, aName)
def test_mqtt_connect_error_reason_codes(packet_type: int, a_name: str) -> None:
rc = mqtt.ReasonCodes(packet_type, a_name)
assert str(MqttConnectError(rc)) == f"[code:{rc.value}] {str(rc)}"

0 comments on commit cb9fa25

Please sign in to comment.