Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Begin mypy type-checking #229

Merged
merged 21 commits into from
May 8, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,17 @@ lint-python:
flake8 --ignore=E501,E731,W503 --exclude=.git,compat.py --per-file-ignores='mocket/async_mocket.py:E999' mocket
@echo ""

types:
@echo "Type checking Python files"
mypy --pretty
@echo ""

setup: develop
pre-commit install

develop: install-dev-requirements install-test-requirements

test: lint-python test-python
test: lint-python types test-python

safetest:
export SKIP_TRUE_REDIS=1; export SKIP_TRUE_HTTP=1; make test
Expand Down
11 changes: 7 additions & 4 deletions mocket/compat.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,30 @@
from __future__ import annotations

import codecs
import os
import shlex
from typing import Any, Final

ENCODING = os.getenv("MOCKET_ENCODING", "utf-8")
ENCODING: Final[str] = os.getenv("MOCKET_ENCODING", "utf-8")

text_type = str
byte_type = bytes
basestring = (str,)


def encode_to_bytes(s, encoding=ENCODING):
def encode_to_bytes(s: str | bytes, encoding: str = ENCODING) -> bytes:
if isinstance(s, text_type):
s = s.encode(encoding)
return byte_type(s)


def decode_from_bytes(s, encoding=ENCODING):
def decode_from_bytes(s: str | bytes, encoding: str = ENCODING) -> str:
if isinstance(s, byte_type):
s = codecs.decode(s, encoding, "ignore")
return text_type(s)


def shsplit(s):
def shsplit(s: str | bytes) -> list[str]:
s = decode_from_bytes(s)
return shlex.split(s)

Expand Down
38 changes: 25 additions & 13 deletions mocket/utils.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
from __future__ import annotations

import binascii
import io
import os
import ssl
from typing import Tuple, Union
from typing import TYPE_CHECKING, Any, Callable, ClassVar

from .compat import decode_from_bytes, encode_to_bytes
from .exceptions import StrictMocketException

if TYPE_CHECKING:
from _typeshed import ReadableBuffer
from typing_extensions import NoReturn

SSL_PROTOCOL = ssl.PROTOCOL_TLSv1_2


class MocketSocketCore(io.BytesIO):
def write(self, content):
def write( # type: ignore[override] # BytesIO returns int
self,
content: ReadableBuffer,
) -> None:
super(MocketSocketCore, self).write(content)

from mocket import Mocket
Expand All @@ -20,7 +29,7 @@ def write(self, content):
os.write(Mocket.w_fd, content)


def hexdump(binary_string):
def hexdump(binary_string: bytes) -> str:
r"""
>>> hexdump(b"bar foobar foo") == decode_from_bytes(encode_to_bytes("62 61 72 20 66 6F 6F 62 61 72 20 66 6F 6F"))
True
Expand All @@ -29,7 +38,7 @@ def hexdump(binary_string):
return " ".join(a + b for a, b in zip(bs[::2], bs[1::2]))


def hexload(string):
def hexload(string: str) -> bytes:
r"""
>>> hexload("62 61 72 20 66 6F 6F 62 61 72 20 66 6F 6F") == encode_to_bytes("bar foobar foo")
True
Expand All @@ -38,23 +47,26 @@ def hexload(string):
return encode_to_bytes(binascii.unhexlify(string_no_spaces))


def get_mocketize(wrapper_):
def get_mocketize(wrapper_: Callable) -> Callable:
import decorator

if decorator.__version__ < "5": # pragma: no cover
if decorator.__version__ < "5": # type: ignore[attr-defined] # pragma: no cover
return decorator.decorator(wrapper_)
return decorator.decorator(wrapper_, kwsyntax=True)
return decorator.decorator( # type: ignore[call-arg] # kwsyntax
wrapper_,
kwsyntax=True,
)


class MocketMode:
__shared_state = {}
STRICT = None
STRICT_ALLOWED = None
__shared_state: ClassVar[dict[str, Any]] = {}
STRICT: ClassVar = None
STRICT_ALLOWED: ClassVar = None

def __init__(self):
def __init__(self) -> None:
self.__dict__ = self.__shared_state

def is_allowed(self, location: Union[str, Tuple[str, int]]) -> bool:
def is_allowed(self, location: str | tuple[str, int]) -> bool:
mindflayer marked this conversation as resolved.
Show resolved Hide resolved
"""
Checks if (`host`, `port`) or at least `host`
are allowed locations to perform real `socket` calls
Expand All @@ -70,7 +82,7 @@ def is_allowed(self, location: Union[str, Tuple[str, int]]) -> bool:
)

@staticmethod
def raise_not_allowed():
def raise_not_allowed() -> NoReturn:
from .mocket import Mocket

current_entries = [
Expand Down
26 changes: 26 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ test = [
"twine",
"fastapi",
"wait-for-it",
"mypy",
"types-decorator",
]
speedups = [
"xxhash;platform_python_implementation=='CPython'",
Expand All @@ -81,3 +83,27 @@ include = [
exclude = [
".*",
]

[tool.mypy]
python_version = "3.8"
mindflayer marked this conversation as resolved.
Show resolved Hide resolved
files = [
"mocket/exceptions.py",
"mocket/compat.py",
"mocket/utils.py",
# "tests/"
]
strict = true
warn_unused_configs = true
ignore_missing_imports = true
warn_redundant_casts = true
warn_unused_ignores = true
show_error_codes = true
implicit_reexport = true
disallow_any_generics = false
follow_imports = "silent" # enable this once majority is typed
enable_error_code = ['ignore-without-code']
disable_error_code = ["no-untyped-def"] # enable this once full type-coverage is reached

[[tool.mypy.overrides]]
module = "tests.*"
disable_error_code = ['type-arg', 'no-untyped-def']