Skip to content
This repository has been archived by the owner on Aug 10, 2024. It is now read-only.

Commit

Permalink
Fix type error in @implements.overriding + mypy on tests
Browse files Browse the repository at this point in the history
Fixes #52
  • Loading branch information
Finistere committed May 25, 2022
1 parent f014219 commit f89f817
Show file tree
Hide file tree
Showing 11 changed files with 43 additions and 37 deletions.
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ reportUnnecessaryCast = "warning"
[tool.mypy]
files = [
"src",
"tests/lib/interface",
"tests/lib/injectable",
"tests/lib/lazy"
]
python_version = "3.7"
strict = true
Expand Down
3 changes: 1 addition & 2 deletions src/antidote/core/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,8 +376,7 @@ def clone(
p_clone = p.clone(keep_singletons_cache=keep_singletons)
if p_clone is p or getattr(p_clone, _CONTAINER_REF_ATTR, None) is not None:
raise RuntimeError(
"A Provider should always return a new "
"instance when copy() is called."
"A Provider should always return a new " "instance when copy() is called."
)

setattr(p_clone, _CONTAINER_REF_ATTR, ref(clone))
Expand Down
2 changes: 1 addition & 1 deletion src/antidote/lib/interface/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ def register(__klass: C) -> C:

return register

def overriding(self, __existing_implementation: Type[Itf]) -> Callable[[C], C]:
def overriding(self, __existing_implementation: Itf) -> Callable[[C], C]:
"""
.. versionadded: 1.4
Expand Down
2 changes: 1 addition & 1 deletion tests/lib/injectable/test_injectable.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ def static_method() -> Dummy:
def test_invalid_arguments(arg: str) -> None:
with pytest.raises(TypeError, match=".*" + arg + ".*"):

@injectable(**{arg: object()})
@injectable(**{arg: object()}) # type: ignore
class Dummy:
...

Expand Down
9 changes: 4 additions & 5 deletions tests/lib/interface/test_custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Iterator, List, Optional, TypeVar
from typing import Any, cast, Iterator, List, Optional, Type, TypeVar

import pytest
from typing_extensions import Protocol
Expand Down Expand Up @@ -330,18 +330,17 @@ def process_initialization(
process_initialization(event)
assert sub.called_with == [event]

tpe = cast(Type[EventSubscriber[InitializationEvent]], EventSubscriber[InitializationEvent])
process_initialization(
event,
# Explicitly retrieving the subscribers
subscribers=world.get[EventSubscriber[InitializationEvent]].all(
qualified_by=InitializationEvent
),
subscribers=world.get[tpe].all(qualified_by=InitializationEvent),
)
assert sub.called_with == [event, event]

process_initialization(
event,
# Explicitly retrieving the subscribers
subscribers=world.get[EventSubscriber[InitializationEvent]].all(qualified_by=object()),
subscribers=world.get[tpe].all(qualified_by=object()),
)
assert sub.called_with == [event, event]
11 changes: 6 additions & 5 deletions tests/lib/interface/test_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from __future__ import annotations

import sys
from typing import Any, Generic, Iterable, Iterator, List, Optional, Sequence, TypeVar
from typing import Any, cast, Generic, Iterable, Iterator, List, Optional, Sequence, Type, TypeVar

import pytest
from typing_extensions import Protocol, runtime_checkable
Expand Down Expand Up @@ -256,7 +256,7 @@ def test_invalid_interface() -> None:
interface(object()) # type: ignore

with pytest.raises(TypeError, match="(?i).*class.*"):
ImplementationsOf(object())
ImplementationsOf(object()) # type: ignore

with pytest.raises(ValueError, match="(?i).*decorated.*@interface.*"):
ImplementationsOf(Qualifier)
Expand Down Expand Up @@ -410,9 +410,10 @@ class Dummy:
pass

dummy = world.get(Dummy)
assert world.get(GenericProtocolBase) is dummy
assert world.get[GenericProtocolBase].single() is dummy
assert world.get[GenericProtocolBase].all() == [dummy]
tpe = cast(Type[GenericProtocolBase[int]], GenericProtocolBase)
assert world.get(tpe) is dummy
assert world.get[tpe].single() is dummy
assert world.get[tpe].all() == [dummy]

@inject
def f(x: GenericProtocolBase[int] = inject.me()) -> GenericProtocolBase[int]:
Expand Down
2 changes: 1 addition & 1 deletion tests/lib/interface/test_internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def evaluate(self, *args: object, **kwargs: object) -> None:
)
def test_create_constraint_invalid_type_hint(type_hint: Any) -> None:
class InvalidTypeHint:
def evaluate(self, predicate: type_hint) -> None:
def evaluate(self, predicate: type_hint) -> None: # type: ignore
...

with pytest.raises(TypeError, match="(?i).*Optional.*Predicate.*"):
Expand Down
2 changes: 1 addition & 1 deletion tests/lib/interface/test_predicate.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def if_only(condition: bool, dummy: Dummy) -> bool:
class Base:
...

@_(implements(Base).when(if_only(True)))
@_(implements(Base).when(if_only(True))) # type: ignore
class Yes(Base):
...

Expand Down
40 changes: 21 additions & 19 deletions tests/lib/lazy/test_const.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def setup_tests(monkeypatch: Any) -> Iterator[None]:
yield


def test_static():
def test_static() -> None:
class Conf:
HOST = const("host")
PORT = const(80)
Expand Down Expand Up @@ -112,11 +112,11 @@ def check(

def env_converter(value: str, tpe: Type[T]) -> T:
if issubclass(tpe, (int, str, float, Enum)):
return tpe(value)
return cast(T, tpe(value))
raise TypeError()


def test_env():
def test_env() -> None:
class Conf:
HOST = const.env()
HOSTNAME = const.env("HOST")
Expand All @@ -127,10 +127,10 @@ class Conf:
MISSING = const.env()
MISSING_WITH_DEFAULT = const.env(default="default")

check_conf(Conf)
check_conf(cast(Type[ConfProtocol], Conf))


def test_factory_env_external():
def test_factory_env_external() -> None:
@const.provider
def env(name: str, arg: Optional[str]) -> str:
return os.environ[arg or name]
Expand Down Expand Up @@ -166,11 +166,12 @@ class ConfVariable:
MISSING = env2.const()
MISSING_WITH_DEFAULT = env2.const(default="default")

check_conf(Conf)
check_conf(ConfVariable)
# for Mypy
check_conf(cast(Type[ConfProtocol], Conf))
check_conf(cast(Type[ConfProtocol], ConfVariable))


def test_factory_env_method():
def test_factory_env_method() -> None:
@injectable
class Conf:
@const.provider
Expand All @@ -189,14 +190,15 @@ def env(self, name: str, arg: Optional[str]) -> str:
MISSING = env.const()
MISSING_WITH_DEFAULT = env.const(default="default")

check_conf(Conf)
# for mypy
check_conf(cast(Type[ConfProtocol], Conf))

conf = Conf()
assert conf.env(name="HOST", arg=None) == "localhost"
assert conf.env(name="XXX", arg="HOST") == "localhost"


def test_invalid_factory():
def test_invalid_factory() -> None:
with pytest.raises(TypeError, match="provider.*function"):
const.provider(object()) # type: ignore

Expand All @@ -213,7 +215,7 @@ def f2(name: str) -> None:
...


def test_type_enforcement():
def test_type_enforcement() -> None:
@const.provider
def f(name: str, arg: Optional[object]) -> int:
if arg is None:
Expand Down Expand Up @@ -252,7 +254,7 @@ class Conf:
assert world.get[str](Conf.TYPED_VALID_DEFAULT) == "1"


def test_unchecked_type():
def test_unchecked_type() -> None:
@const.provider
def f(name: str, arg: Optional[object]) -> Union[str, int]:
if arg is None:
Expand All @@ -264,7 +266,7 @@ def f(name: str, arg: Optional[object]) -> Union[str, int]:
class Conf:
VALID_UNCHECKED = f.const(x)
VALID_DEFAULT_UNCHECKED = f.const(default=x) # type: ignore
TYPED_VALID_UNCHECKED = f.const[Union[int, float]](x)
TYPED_VALID_UNCHECKED = f.const[Union[int, float]](x) # type: ignore
TYPED_VALID_DEFAULT_UNCHECKED = f.const[Union[int, float]](default=x) # type: ignore

assert Conf().VALID_UNCHECKED is x
Expand All @@ -278,7 +280,7 @@ class Conf:
assert world.get[object](Conf.TYPED_VALID_DEFAULT_UNCHECKED) is x


def test_converter():
def test_converter() -> None:
@const.provider
def f(name: str, arg: Optional[object]) -> Union[str, int]:
if arg is None:
Expand All @@ -288,7 +290,7 @@ def f(name: str, arg: Optional[object]) -> Union[str, int]:
@f.converter
def f_converter(value: Union[str, int], tpe: Type[T]) -> T:
if issubclass(tpe, str):
return tpe(value)
return cast(T, tpe(value))
return cast(T, value)

x = object()
Expand All @@ -299,7 +301,7 @@ class Conf:
TYPED_CAST = f.const[str](1)
TYPED_NO_CAST = f.const[int](1)
TYPED_INVALID_NO_CAST = f.const[int]("1")
UNSUPPORTED = f.const[Union[str, int]](1)
UNSUPPORTED = f.const[Union[str, int]](1) # type: ignore

with pytest.raises(TypeError, match="class"):
_ = Conf().UNSUPPORTED
Expand All @@ -318,7 +320,7 @@ class Conf:
assert world.get[int](Conf.TYPED_NO_CAST) == 1


def test_invalid_converter():
def test_invalid_converter() -> None:
@const.provider
def get(name: str, arg: object) -> object:
...
Expand Down Expand Up @@ -349,7 +351,7 @@ def f4(value: object, tpe: Type[T]) -> T:
...


def test_const_repr():
def test_const_repr() -> None:
class Conf:
TEST = const("random-value")

Expand All @@ -358,7 +360,7 @@ class Conf:
assert "random-value" in repr(const("random-value"))


def test_singleton_dependency():
def test_singleton_dependency() -> None:
class Conf:
@const.provider
def env(self, name: str, arg: Optional[object]) -> str:
Expand Down
2 changes: 1 addition & 1 deletion tests/lib/lazy/test_lazy.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ def injected_bag(d: Dummy) -> Bag:
return Bag(dummy=d)

@inject
def f2(bag: Bag = injected_bag()) -> Bag:
def f2(bag: Bag = injected_bag()) -> Bag: # type: ignore
return bag

assert f2() == Bag(dummy=Dummy(name="dummy"))
4 changes: 3 additions & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ commands =
[testenv:mypy]
changedir = {toxinidir}
deps =
; executing mypy on some tests
-r requirements/tests.txt
mypy==0.950
mypy-extensions==0.4.3
commands =
Expand All @@ -43,7 +45,7 @@ changedir = {toxinidir}
deps =
; executing pyright on some tests
-r requirements/tests.txt
pyright==1.1.248
pyright==1.1.249
commands =
pyright

Expand Down

0 comments on commit f89f817

Please sign in to comment.