Skip to content

Commit fbc9fe8

Browse files
authored
Merge pull request #1 from puddly/mdw/mypy-extra-flake8
Make tests pass and fix remaining instances of `type:ignore` Great!
2 parents 69081b1 + 823dcd9 commit fbc9fe8

File tree

10 files changed

+41
-42
lines changed

10 files changed

+41
-42
lines changed

tests/conftest.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,9 @@ def write(self, data):
6969
assert self._is_connected
7070
self.protocol.data_received(data)
7171

72-
def close(self, *, error=ValueError("Connection was closed")): # noqa:
72+
def close(self, *, error=ValueError("Connection was closed")): # noqa: B008
7373
LOGGER.debug("Closing %s", self)
74+
7475
if not self._is_connected:
7576
return
7677

tests/test_commands.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def test_commands_schema():
137137

138138
commands_by_id[cmd.Req.header].append(cmd.Req)
139139
else:
140-
assert False, "Command is empty"
140+
assert False, "Command is empty" # noqa: B011
141141
elif cmd.type == t.CommandType.SRSP:
142142
# The one command like this is RPCError
143143
assert cmd is c.RPCError.CommandNotRecognized
@@ -153,7 +153,7 @@ def test_commands_schema():
153153

154154
commands_by_id[cmd.Rsp.header].append(cmd.Rsp)
155155
else:
156-
assert False, "Command has unknown type"
156+
assert False, "Command has unknown type" # noqa: B011
157157

158158
duplicate_commands = {
159159
cmd: commands for cmd, commands in commands_by_id.items() if len(commands) > 1

tests/test_types_cstruct.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
1+
import typing
2+
13
import pytest
24

35
import zigpy_znp.types as t
46

7+
if typing.TYPE_CHECKING:
8+
import typing_extensions
9+
510

611
def test_struct_fields():
712
class TestStruct(t.CStruct):
@@ -266,7 +271,7 @@ class TestStruct(t.CStruct):
266271

267272

268273
def test_old_nib_deserialize():
269-
PaddingByte = t.uint8_t
274+
PaddingByte: typing_extensions.TypeAlias = t.uint8_t
270275

271276
class NwkState16(t.enum_uint16):
272277
NWK_INIT = 0
@@ -296,15 +301,15 @@ class OldNIB(t.CStruct):
296301
SecurityLevel: t.uint8_t
297302
SymLink: t.uint8_t
298303
CapabilityFlags: t.uint8_t
299-
PaddingByte0: PaddingByte # type:ignore[valid-type]
304+
PaddingByte0: PaddingByte
300305
TransactionPersistenceTime: t.uint16_t
301306
nwkProtocolVersion: t.uint8_t
302307
RouteDiscoveryTime: t.uint8_t
303308
RouteExpiryTime: t.uint8_t
304-
PaddingByte1: PaddingByte # type:ignore[valid-type]
309+
PaddingByte1: PaddingByte
305310
nwkDevAddress: t.NWK
306311
nwkLogicalChannel: t.uint8_t
307-
PaddingByte2: PaddingByte # type:ignore[valid-type]
312+
PaddingByte2: PaddingByte
308313
nwkCoordAddress: t.NWK
309314
nwkCoordExtAddress: t.EUI64
310315
nwkPanId: t.uint16_t

tests/test_uart.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ def test_uart_frame_received_error(connected_uart, mocker):
218218
uart.data_received(test_frame_bytes * 3)
219219

220220
# We should have received all three frames
221-
znp.frame_received.call_count == 3
221+
assert znp.frame_received.call_count == 3
222222

223223

224224
async def test_connection_lost(dummy_serial_conn, mocker, event_loop):

zigpy_znp/api.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,17 @@
22

33
import os
44
import time
5+
import typing
56
import asyncio
67
import logging
78
import itertools
89
import contextlib
910
import dataclasses
10-
from typing import Union, overload
1111
from collections import Counter, defaultdict
1212

1313
import zigpy.state
1414
import async_timeout
1515
import zigpy.zdo.types as zdo_t
16-
from typing_extensions import Literal
1716

1817
import zigpy_znp.const as const
1918
import zigpy_znp.types as t
@@ -32,6 +31,9 @@
3231
from zigpy_znp.exceptions import CommandNotRecognized, InvalidCommandResponse
3332
from zigpy_znp.types.nvids import ExNvIds, OsalNvIds
3433

34+
if typing.TYPE_CHECKING:
35+
import typing_extensions
36+
3537
LOGGER = logging.getLogger(__name__)
3638

3739

@@ -762,21 +764,21 @@ def callback_for_response(
762764

763765
return self.callback_for_responses([response], callback)
764766

765-
@overload
767+
@typing.overload
766768
def wait_for_responses(
767-
self, responses, *, context: Literal[False] = ...
769+
self, responses, *, context: typing_extensions.Literal[False] = ...
768770
) -> asyncio.Future:
769771
...
770772

771-
@overload
773+
@typing.overload
772774
def wait_for_responses(
773-
self, responses, *, context: Literal[True]
775+
self, responses, *, context: typing_extensions.Literal[True]
774776
) -> tuple[asyncio.Future, OneShotResponseListener]:
775777
...
776778

777779
def wait_for_responses(
778780
self, responses, *, context: bool = False
779-
) -> Union[asyncio.Future | tuple[asyncio.Future, OneShotResponseListener]]:
781+
) -> asyncio.Future | tuple[asyncio.Future, OneShotResponseListener]:
780782
"""
781783
Creates a one-shot listener that matches any *one* of the given responses.
782784
"""

zigpy_znp/tools/common.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from __future__ import annotations
22

33
import sys
4+
import typing
45
import logging
56
import argparse
6-
from typing import Optional, Sequence
77

88
import jsonschema
99
import coloredlogs
@@ -117,9 +117,7 @@ def validate_backup_json(backup: t.JSONType) -> None:
117117

118118

119119
class CustomArgumentParser(argparse.ArgumentParser):
120-
def parse_args(
121-
self, args: Optional[Sequence[str]] = None, namespace=None
122-
): # type:ignore[override]
120+
def parse_args(self, args: typing.Sequence[str] | None = None, namespace=None):
123121
args = super().parse_args(args, namespace)
124122

125123
# Since we're running as a CLI tool, install our own log level and color logger

zigpy_znp/types/basic.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import enum
4+
import typing
45

56
from zigpy_znp.types.cstruct import CStruct
67

@@ -36,20 +37,18 @@ def serialize_list(objects) -> Bytes:
3637

3738

3839
class FixedIntType(int):
39-
_signed = None
40-
_size = None # type:int
40+
_signed: bool
41+
_size: int
4142

42-
@classmethod
4343
def __new__(cls, *args, **kwargs):
44-
if cls._signed is None or cls._size is None:
44+
if getattr(cls, "_signed", None) is None or getattr(cls, "_size", None) is None:
4545
raise TypeError(f"{cls} is abstract and cannot be created")
4646

4747
instance = super().__new__(cls, *args, **kwargs)
4848
instance.serialize()
4949

5050
return instance
5151

52-
@classmethod
5352
def __init_subclass__(cls, signed=None, size=None, hex_repr=None) -> None:
5453
super().__init_subclass__()
5554

@@ -79,15 +78,13 @@ def serialize(self) -> bytes:
7978
raise ValueError(str(e)) from e
8079

8180
@classmethod
82-
def deserialize(
83-
cls, data: bytes
84-
) -> tuple[FixedIntType, bytes]: # type:ignore[return-value]
85-
if len(data) < cls._size: # type:ignore[operator]
81+
def deserialize(cls, data: bytes) -> tuple[FixedIntType, bytes]:
82+
if len(data) < cls._size:
8683
raise ValueError(f"Data is too short to contain {cls._size} bytes")
8784

8885
r = cls.from_bytes(data[: cls._size], "little", signed=cls._signed)
8986
data = data[cls._size :]
90-
return r, data # type:ignore[return-value]
87+
return typing.cast(FixedIntType, r), data
9188

9289

9390
class uint_t(FixedIntType, signed=False):

zigpy_znp/types/cstruct.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,7 @@ def __post_init__(self) -> None:
2525

2626
def get_size_and_alignment(self, align=False) -> tuple[int, int]:
2727
if issubclass(self.type, (zigpy_t.FixedIntType, t.FixedIntType)):
28-
return ( # type: ignore[return-value]
29-
self.type._size,
30-
self.type._size if align else 1,
31-
1,
32-
)
28+
return self.type._size, (self.type._size if align else 1)
3329
elif issubclass(self.type, zigpy_t.EUI64):
3430
return 8, 1
3531
elif issubclass(self.type, zigpy_t.KeyData):

zigpy_znp/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import logging
77
import functools
88
import dataclasses
9-
from typing import CoroutineFunction
109

1110
import zigpy_znp.types as t
1211

@@ -136,6 +135,7 @@ class CallbackResponseListener(BaseResponseListener):
136135

137136
def _resolve(self, response: t.CommandBase) -> bool:
138137
try:
138+
# https://github.com/python/mypy/issues/5485
139139
result = self.callback(response) # type:ignore[misc]
140140

141141
# Run coroutines in the background
@@ -166,8 +166,8 @@ def matches(self, other) -> bool:
166166

167167

168168
def combine_concurrent_calls(
169-
function: CoroutineFunction,
170-
) -> CoroutineFunction:
169+
function: typing.CoroutineFunction,
170+
) -> typing.CoroutineFunction:
171171
"""
172172
Decorator that allows concurrent calls to expensive coroutines to share a result.
173173
"""

zigpy_znp/znp/security.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ def replace(self, **kwargs) -> StoredDevice:
2424
return dataclasses.replace(self, **kwargs)
2525

2626

27-
def rotate(lst: typing.Sequence, n: int) -> typing.Sequence:
28-
return lst[n:] + lst[:n] # type:ignore[operator]
27+
def rotate(lst: list, n: int) -> list:
28+
return lst[n:] + lst[:n]
2929

3030

3131
def compute_key(ieee: t.EUI64, tclk_seed: t.KeyData, shift: int) -> t.KeyData:
@@ -174,7 +174,7 @@ async def read_addr_manager_entries(znp: ZNP) -> typing.Sequence[t.AddrMgrEntry]
174174

175175
async def read_hashed_link_keys( # type:ignore[misc]
176176
znp: ZNP, tclk_seed: t.KeyData
177-
) -> typing.Iterable[zigpy.state.Key]:
177+
) -> typing.AsyncGenerator[zigpy.state.Key, None]:
178178
if znp.version >= 3.30:
179179
entries = znp.nvram.read_table(
180180
item_id=ExNvIds.TCLK_TABLE,
@@ -204,9 +204,9 @@ async def read_hashed_link_keys( # type:ignore[misc]
204204
)
205205

206206

207-
async def read_unhashed_link_keys( # type:ignore[misc]
207+
async def read_unhashed_link_keys(
208208
znp: ZNP, addr_mgr_entries: typing.Sequence[t.AddrMgrEntry]
209-
) -> typing.Iterable[zigpy.state.Key]:
209+
) -> typing.AsyncGenerator[zigpy.state.Key, None]:
210210
if znp.version == 3.30:
211211
link_key_offset_base = 0x0000
212212
table = znp.nvram.read_table(

0 commit comments

Comments
 (0)