Skip to content

Commit

Permalink
Make mypy pass
Browse files Browse the repository at this point in the history
  • Loading branch information
anschweitzer committed Aug 6, 2024
1 parent ecae7a1 commit 7a83c12
Show file tree
Hide file tree
Showing 10 changed files with 44 additions and 31 deletions.
5 changes: 2 additions & 3 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,14 @@ jobs:
fail-fast: false
matrix:
include:
# - { python: "3.12", os: "ubuntu-latest", session: "pre-commit" }
# - { python: "3.12", os: "ubuntu-latest", session: "safety" }
- { python: "3.12", os: "ubuntu-latest", session: "pre-commit" }
# - { python: "3.12", os: "ubuntu-latest", session: "mypy" }
- { python: "3.11", os: "ubuntu-latest", session: "tests" }
- { python: "3.12", os: "ubuntu-latest", session: "tests" }
# - { python: "3.12", os: "windows-latest", session: "tests" }
# - { python: "3.12", os: "macos-latest", session: "tests" }
# - { python: "3.12", os: "ubuntu-latest", session: "typeguard" }
# - { python: "3.12", os: "ubuntu-latest", session: "xdoctest" }

# - { python: "3.12", os: "ubuntu-latest", session: "docs-build" }

env:
Expand Down
5 changes: 3 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,11 @@ lines_after_imports = 2
[tool.mypy]
strict = true
warn_unreachable = true
pretty = true
pretty = false
show_column_numbers = true
show_error_codes = true
show_error_context = true
show_error_context = false
show_absolute_path = true

[build-system]
requires = ["poetry-core>=1.0.0"]
Expand Down
8 changes: 6 additions & 2 deletions src/gw/enums/gw_str_enum.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import enum
from typing import Any
from typing import Sequence


class GwStrEnum(str, enum.Enum):
Expand All @@ -16,5 +18,7 @@ class Foo(GwStrEnum):
"""

@staticmethod
def _generate_next_value_(name, start, count, last_values):
return name
def _generate_next_value_(
name: Any, start: int, count: int, last_values: Sequence[Any]
) -> str:
return str(name)
5 changes: 2 additions & 3 deletions src/gw/property_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ def check_is_market_name(v: str) -> None:
x = v.split(".")
except AttributeError as e:
raise ValueError(f"{v} failed to split on '.'") from e
if not x[0] in MarketTypeName.values():
if x[0] not in MarketTypeName.values():
raise ValueError(f"{v} not recognized MarketType")
g_node_alias = ".".join(x[1:])
check_is_left_right_dot(g_node_alias)
Expand All @@ -34,9 +34,8 @@ def check_is_market_slot_name_lrd_format(v: str) -> None:
x = v.split(".")
except AttributeError as e:
raise ValueError(f"{v} failed to split on '.'") from e
slot_start = x[-1]
try:
slot_start = int(slot_start)
slot_start = int(x[-1])
except ValueError as e:
raise ValueError(f"slot start {slot_start} not an int") from e
check_is_reasonable_unix_time_s(slot_start)
Expand Down
4 changes: 2 additions & 2 deletions src/gw/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class RestfulResponse(BaseModel):
snake_add_underscore_to_camel_pattern = re.compile(r"(?<!^)(?=[A-Z])")


def is_pascal_case(s):
def is_pascal_case(s: str) -> bool:
return re.match(r"^[A-Z][a-zA-Z0-9]*$", s) is not None


Expand Down Expand Up @@ -97,7 +97,7 @@ def format(
actor_alias: str,
topic: str,
payload_object: Any = None,
broker_flag=" ",
broker_flag: str = " ",
timestamp: Optional[datetime.datetime] = None,
) -> str:
"""
Expand Down
Empty file added src/gw_test/py.typed
Empty file.
29 changes: 19 additions & 10 deletions src/gw_test/wait.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@
from inspect import getframeinfo
from inspect import stack
from pathlib import Path
from types import TracebackType
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import Optional
from typing import Type
from typing import Union


Expand All @@ -24,10 +27,16 @@ class StopWatch:
end: float = 0
elapsed: float = 0

def __enter__(self):
def __enter__(self) -> "StopWatch":
self.start = time.time()
return self

def __exit__(self, type_, value, traceback):
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
self.end = time.time()
self.elapsed = self.end - self.start

Expand All @@ -39,8 +48,8 @@ async def await_for( # noqa: C901
raise_timeout: bool = True,
retry_duration: float = 0.1,
err_str_f: Optional[ErrorStringFunction] = None,
logger: Optional[logging.Logger | logging.LoggerAdapter] = None,
error_dict: Optional[dict] = None,
logger: Optional[logging.Logger | logging.LoggerAdapter[Any]] = None,
error_dict: Optional[dict[Any, Any]] = None,
) -> bool:
"""Similar to wait_for(), but awaitable. Instead of sleeping after a False resoinse from function f, await_for
will asyncio.sleep(), allowing the event loop to continue. Additionally, f may be either a function or a coroutine.
Expand Down Expand Up @@ -68,14 +77,14 @@ def err_str_f_() -> str:
result = False
if now >= until:
if f_is_async:
result = await f()
result = await f() # type: ignore
else:
result = f()
result = f() # type: ignore
while now < until and not result:
if f_is_async:
result = await f()
result = await f() # type: ignore
else:
result = f()
result = f() # type: ignore
if not result:
now = time.time()
if now < until:
Expand All @@ -84,9 +93,9 @@ def err_str_f_() -> str:
# oops! we overslept
if now >= until:
if f_is_async:
result = await f()
result = await f() # type: ignore
else:
result = f()
result = f() # type: ignore
if result:
return True
else:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_property_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from gw import check_is_market_slot_name_lrd_format


def test_property_format():
def test_property_format() -> None:

good_market_name = "rt60gate5.d1.isone"
bad_market_name_1 = "not_a_market_type.d1.isone"
Expand Down
9 changes: 5 additions & 4 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,25 @@
from gw.enums import MessageCategorySymbol


def test_pascal_camel():
def test_pascal_camel() -> None:
snake = "peaches_cat"
camel = "PeachesCat"
assert gw.utils.snake_to_pascal(snake) == camel
assert gw.utils.pascal_to_snake(camel) == snake


def test_is_pascal():
def test_is_pascal() -> None:
assert not gw.utils.is_pascal_case("not_pascal")
assert not gw.utils.is_pascal_case("notPascal")
assert gw.utils.is_pascal_case("IsPascal")


def test_message_category_from_symbol():
def test_message_category_from_symbol() -> None:
"""
Bijection between shorthand and longhand enums
"""
for s in MessageCategorySymbol.values():
for s in MessageCategorySymbol:
assert isinstance(s, MessageCategorySymbol)
if s == MessageCategorySymbol.unknown:
assert gw.utils.message_category_from_symbol(s) == MessageCategory.Unknown
else:
Expand Down
8 changes: 4 additions & 4 deletions tests/test_wait.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ def __init__(
self.sleep_duration = duration
self.restart(delay)

def restart(self, delay: float):
def restart(self, delay: float) -> None:
self.until = time.time() + delay

def __call__(self):
def __call__(self) -> bool:
if self.sleep_duration is not None:
time.sleep(self.sleep_duration)
if time.time() >= self.until:
Expand All @@ -34,7 +34,7 @@ def __call__(self):


def async_delay(delay: Delay) -> AwaitablePredicate:
async def async_function():
async def async_function() -> bool:
if delay.sleep_duration is not None:
await asyncio.sleep(delay.sleep_duration)
if time.time() >= delay.until:
Expand All @@ -46,7 +46,7 @@ async def async_function():


@pytest.mark.asyncio
async def test_await_for():
async def test_await_for() -> None:
delay_time = 0.01
timeout = delay_time * 2
retry_duration = delay_time / 4
Expand Down

0 comments on commit 7a83c12

Please sign in to comment.