-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathtest_supports.py
73 lines (51 loc) · 1.99 KB
/
test_supports.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from typing import List, Sized
import pytest
from classes import typeclass
class _ListOfStrMeta(type):
def __instancecheck__(cls, other) -> bool:
return (
isinstance(other, list) and
bool(other) and
all(isinstance(list_item, str) for list_item in other)
)
class _ListOfStr(List[str], metaclass=_ListOfStrMeta):
"""We use this for testing concrete type calls."""
class _MyList(list): # noqa: WPS600
"""We use it to test mro."""
@typeclass
def my_len(instance) -> int:
"""Returns a length of an object."""
@my_len.instance(protocol=Sized)
def _my_len_sized(instance: Sized) -> int:
return 0
@my_len.instance(list)
def _my_len_list(instance: list) -> int:
return 1
@my_len.instance(delegate=_ListOfStr)
def _my_len_list_str(instance: List[str]) -> int:
return 2
@pytest.mark.parametrize(('data_type', 'expected'), [
([], True), # direct list call
('', True), # sized protocol
(1, False), # default impl
(_MyList(), True), # mro fallback
(_ListOfStr(), True), # mro fallback
(_ListOfStr(['a']), True), # mro fallback
])
def test_supports(data_type, expected: bool, clear_cache) -> None:
"""Ensures that ``.supports`` works correctly."""
with clear_cache(my_len):
assert my_len.supports(data_type) is expected
def test_supports_twice_regular(clear_cache) -> None:
"""Ensures that calling ``supports`` twice for regular type is cached."""
with clear_cache(my_len):
assert list not in my_len._dispatch_cache # noqa: WPS437
assert my_len.supports([]) is True
assert list in my_len._dispatch_cache # noqa: WPS437
assert my_len.supports([]) is True
def test_supports_twice_concrete(clear_cache) -> None:
"""Ensures that calling ``supports`` twice for concrete type is ignored."""
with clear_cache(my_len):
for _ in range(2):
assert not my_len._dispatch_cache # noqa: WPS437
assert my_len.supports(['a', 'b']) is True