diff --git a/tests/test_typeclass/test_typing_type.py b/tests/test_typeclass/test_typing_type.py new file mode 100644 index 0000000..a46cbc9 --- /dev/null +++ b/tests/test_typeclass/test_typing_type.py @@ -0,0 +1,48 @@ +from typing import Type + +import pytest + +from classes import typeclass + + +class _MyClass(object): + """We use this class to test `Type[MyClass]`.""" + + +class _MyClassTypeMeta(type): + def __instancecheck__(cls, typ) -> bool: + return typ is _MyClass + + +class _MyClassType(Type[_MyClass], metaclass=_MyClassTypeMeta): # type: ignore + """Delegate class.""" + + +@typeclass +def class_type(typ) -> Type: + """Returns the type representation.""" + + +@class_type.instance(delegate=_MyClassType) +def _my_class_type(typ: Type[_MyClass]) -> Type: + return typ + + +def test_correct_class_type(): + """Ensures `Type[T]` works correctly with delegate.""" + assert class_type(_MyClass) is _MyClass + + +@pytest.mark.parametrize('typ', [ + int, float, type, dict, list, +]) +def test_wrong_class_type(typ): + """Ensures other types doesn't works with our delegate.""" + with pytest.raises(NotImplementedError): + class_type(typ) + + +def test_passing_class_type_instance(): + """Ensures passing a instance of the expected type doesn't work.""" + with pytest.raises(NotImplementedError): + class_type(_MyClass()) # type: ignore[arg-type] diff --git a/typesafety/test_typing_type.yml b/typesafety/test_typing_type.yml new file mode 100644 index 0000000..7fd35c6 --- /dev/null +++ b/typesafety/test_typing_type.yml @@ -0,0 +1,26 @@ +- case: typing_type_correct + disable_cache: true + main: | + from typing import Type + from classes import typeclass + + class _MyClass(object): + ... + + class _MyClassType(Type[_MyClass]): + ... + + + @typeclass + def class_type(typ) -> Type: + ... + + @class_type.instance(delegate=_MyClassType) + def _my_class_type(typ: Type[_MyClass]) -> Type: + return typ + + class_type(_MyClass) + class_type(int) + out: | + main:7: error: Invalid base class "Type" + main:20: error: Argument 1 to "class_type" has incompatible type "Type[int]"; expected "Type[_MyClass]"