File: test_predicates.py

package info (click to toggle)
litestar 2.19.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,500 kB
  • sloc: python: 70,169; makefile: 254; javascript: 105; sh: 60
file content (295 lines) | stat: -rw-r--r-- 7,229 bytes parent folder | download
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
from collections import defaultdict, deque
from dataclasses import MISSING, dataclass
from functools import partial
from inspect import Signature
from typing import (
    Any,
    AsyncGenerator,
    Callable,
    ClassVar,
    DefaultDict,
    Deque,
    Dict,
    FrozenSet,
    Generic,
    Iterable,
    List,
    Mapping,
    MutableMapping,
    Optional,
    Sequence,
    Set,
    Tuple,
    TypeVar,
    Union,
    cast,
)

import pytest
from typing_extensions import Annotated

from litestar import Response, get
from litestar.pagination import CursorPagination
from litestar.types import Empty
from litestar.utils import is_any, is_async_callable, is_class_and_subclass, is_optional_union, is_union
from litestar.utils.predicates import (
    is_class_var,
    is_dataclass_class,
    is_generic,
    is_mapping,
    is_non_string_iterable,
    is_non_string_sequence,
    is_undefined_sentinel,
)


class C:
    pass


@get("/", sync_to_thread=False)
def naive_handler() -> Dict[str, int]:
    return {}


@get("/", sync_to_thread=False)
def response_handler() -> Response[Any]:
    return Response(content=b"")


class Sub(C): ...


@pytest.mark.parametrize(
    "args, expected",
    (
        ((Sub, C), True),
        ((Signature.from_callable(cast("Any", naive_handler.fn)).return_annotation, C), False),
        ((Signature.from_callable(cast("Any", response_handler.fn)).return_annotation, Response), True),
        ((Dict[str, Any], C), False),
        ((C(), C), False),
    ),
)
def test_is_class_and_subclass(args: Tuple[Any, Any], expected: bool) -> None:
    assert is_class_and_subclass(*args) is expected


@pytest.mark.parametrize(
    "value, expected",
    (
        (
            (Tuple[int, ...], True),
            (Tuple[int], True),
            (List[str], True),
            (Set[str], True),
            (FrozenSet[str], True),
            (Deque[str], True),
            (Sequence[str], True),
            (Iterable[str], True),
            (list, True),
            (tuple, True),
            (deque, True),
            (set, True),
            (frozenset, True),
            (str, False),
            (bytes, False),
            (dict, True),
            (Dict[str, Any], True),
            (Union[str, int], False),
            (1, False),
        )
    ),
)
def test_is_non_string_iterable(value: Any, expected: bool) -> None:
    assert is_non_string_iterable(value) is expected


@pytest.mark.parametrize(
    "value, expected",
    (
        (
            (Tuple[int, ...], True),
            (Tuple[int], True),
            (List[str], True),
            (Set[str], True),
            (FrozenSet[str], True),
            (Deque[str], True),
            (Sequence[str], True),
            (Iterable[str], False),
            (list, True),
            (tuple, True),
            (deque, True),
            (set, True),
            (frozenset, True),
            (str, False),
            (bytes, False),
            (dict, False),
            (Dict[str, Any], False),
            (Union[str, int], False),
            (1, False),
        )
    ),
)
def test_is_non_string_sequence(value: Any, expected: bool) -> None:
    assert is_non_string_sequence(value) is expected


@pytest.mark.parametrize(
    "value, expected",
    ((CursorPagination[str, str], True), (dict, False)),
)
def test_is_generic(value: Any, expected: bool) -> None:
    assert is_generic(value) is expected


@pytest.mark.parametrize(
    "value, expected",
    (
        (Dict, True),
        (dict, True),
        (defaultdict, True),
        (DefaultDict, True),
        (Mapping, True),
        (MutableMapping, True),
        (list, False),
        (Iterable, False),
    ),
)
def test_is_mapping(value: Any, expected: bool) -> None:
    assert is_mapping(value) is expected


@pytest.mark.parametrize(
    "value, expected",
    ((Any, True), (Union[Any, str], True), (int, False), (dict, False), (Dict[str, Any], False), (None, False)),
)
def test_is_any(value: Any, expected: bool) -> None:
    assert is_any(value) is expected


@pytest.mark.parametrize(
    "value, expected",
    (
        (Optional[int], True),
        (Optional[Union[int, str]], True),
        (Union[str, None], True),
        (None, False),
        (int, False),
        (Union[int, str], True),
    ),
)
def test_is_union(value: Any, expected: bool) -> None:
    assert is_union(value) is expected


@pytest.mark.parametrize(
    "value, expected",
    (
        (Optional[int], True),
        (Optional[Union[int, str]], True),
        (Union[str, None], True),
        (None, False),
        (int, False),
        (Union[int, str], False),
    ),
)
def test_is_optional_union(value: Any, expected: bool) -> None:
    assert is_optional_union(value) is expected


@pytest.mark.parametrize(
    "value, expected",
    (
        (ClassVar[int], True),
        (Annotated[ClassVar[int], "abc"], True),
        (Dict[str, int], False),
        (None, False),
    ),
)
def test_is_class_var(value: Any, expected: bool) -> None:
    assert is_class_var(value) is expected


class AsyncTestCallable:
    async def __call__(self, param1: int, param2: int) -> None: ...

    async def method(self, param1: int, param2: int) -> None: ...


async def async_generator() -> AsyncGenerator[int, None]:
    yield 1


class SyncTestCallable:
    def __call__(self, param1: int, param2: int) -> None: ...

    def method(self, param1: int, param2: int) -> None: ...


async def async_func(param1: int, param2: int) -> None: ...


def sync_func(param1: int, param2: int) -> None: ...


async_callable = AsyncTestCallable()
sync_callable = SyncTestCallable()


@pytest.mark.parametrize(
    "c, exp",
    [
        (async_callable, True),
        (sync_callable, False),
        (async_callable.method, True),
        (sync_callable.method, False),
        (async_func, True),
        (sync_func, False),
        (lambda: ..., False),
        (AsyncTestCallable, True),
        (SyncTestCallable, False),
        (async_generator, False),
    ],
)
def test_is_async_callable(c: Callable[[int, int], None], exp: bool) -> None:
    assert is_async_callable(c) is exp
    partial_1 = partial(c, 1)
    assert is_async_callable(partial_1) is exp
    partial_2 = partial(partial_1, 2)
    assert is_async_callable(partial_2) is exp


def test_not_undefined_sentinel() -> None:
    assert is_undefined_sentinel(Signature.empty) is True
    assert is_undefined_sentinel(Empty) is True
    assert is_undefined_sentinel(Ellipsis) is True
    assert is_undefined_sentinel(MISSING) is True
    assert is_undefined_sentinel(1) is False
    assert is_undefined_sentinel("") is False
    assert is_undefined_sentinel([]) is False
    assert is_undefined_sentinel({}) is False
    assert is_undefined_sentinel(None) is False


T = TypeVar("T")


@dataclass
class NonGenericDataclass:
    foo: int


@dataclass
class GenericDataclass(Generic[T]):
    foo: T


class NonDataclass: ...


@pytest.mark.parametrize(
    ("cls", "expected"),
    ((NonGenericDataclass, True), (GenericDataclass, True), (GenericDataclass[int], True), (NonDataclass, False)),
)
def test_is_dataclass_class(cls: Any, expected: bool) -> None:
    assert is_dataclass_class(cls) is expected