Skip to content

Commit 89c6885

Browse files
Creates tests to ensures the correctly behavior with Type[T]
1 parent c327090 commit 89c6885

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
from typing import Type
2+
3+
import pytest
4+
5+
from classes import typeclass
6+
7+
8+
class _MyClass(object):
9+
"""We use this class to test `Type[MyClass]`."""
10+
11+
12+
class _MyClassTypeMeta(type):
13+
def __instancecheck__(cls, typ) -> bool:
14+
return typ is _MyClass
15+
16+
17+
class _MyClassType(Type[_MyClass], metaclass=_MyClassTypeMeta): # type: ignore
18+
"""Delegate class."""
19+
20+
21+
@typeclass
22+
def class_type(typ) -> Type:
23+
"""Returns the type representation."""
24+
25+
26+
@class_type.instance(delegate=_MyClassType)
27+
def _my_class_type(typ: Type[_MyClass]) -> Type:
28+
return typ
29+
30+
31+
def test_correct_class_type():
32+
"""Ensures `Type[T]` works correctly with delegate."""
33+
assert class_type(_MyClass) is _MyClass
34+
35+
36+
@pytest.mark.parametrize('typ', [
37+
int, float, type, dict, list,
38+
])
39+
def test_wrong_class_type(typ):
40+
"""Ensures other types doesn't works with our delegate."""
41+
with pytest.raises(NotImplementedError):
42+
class_type(typ)
43+
44+
45+
def test_passing_class_type_instance():
46+
"""Ensures passing a instance of the expected type doesn't work."""
47+
with pytest.raises(NotImplementedError):
48+
class_type(_MyClass()) # type: ignore[arg-type]

typesafety/test_typing_type.yml

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
- case: typing_type_correct
2+
disable_cache: true
3+
main: |
4+
from typing import Type, TypeVar
5+
from classes import typeclass
6+
7+
class _MyClass(object):
8+
...
9+
10+
class _MyClassType(Type[_MyClass]):
11+
...
12+
13+
14+
@typeclass
15+
def class_type(typ) -> Type:
16+
...
17+
18+
@class_type.instance(delegate=_MyClassType)
19+
def _my_class_type(typ: Type[_MyClass]) -> Type:
20+
return typ
21+
22+
class_type(_MyClass)
23+
class_type(int)
24+
out: |
25+
main:7: error: Invalid base class "Type"
26+
main:20: error: Argument 1 to "class_type" has incompatible type "Type[int]"; expected "Type[_MyClass]"

0 commit comments

Comments
 (0)