forked from ask/mode
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathtest_objects.py
More file actions
391 lines (312 loc) · 9.16 KB
/
test_objects.py
File metadata and controls
391 lines (312 loc) · 9.16 KB
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import abc
import collections.abc
import pickle
import typing
from typing import (
AbstractSet,
ClassVar,
Dict,
FrozenSet,
Generic,
List,
Mapping,
MutableMapping,
MutableSet,
Optional,
Sequence,
Set,
Tuple,
Union,
)
from unittest.mock import ANY, Mock
import pytest
from mode import Service, ServiceT
from mode.services import ServiceBase, ServiceCallbacks
from mode.utils.mocks import IN
from mode.utils.objects import (
InvalidAnnotation,
KeywordReduce,
Unordered,
_remove_optional,
_restore_from_keywords,
annotations,
canoname,
canonshortname,
eval_type,
guess_polymorphic_type,
is_optional,
is_union,
iter_mro_reversed,
label,
qualname,
remove_optional,
shortname,
)
EXTRA_GENERIC_INHERITS_FROM = [abc.ABC]
class D(Service): ...
class C(D): ...
class B(C): ...
class A(B): ...
@pytest.mark.parametrize(
"cls,stop,expected_mro",
[
(A, Service, [D, C, B, A]),
(B, Service, [D, C, B]),
(C, Service, [D, C]),
(D, Service, [D]),
(
A,
object,
(
[
ServiceCallbacks,
Generic,
*EXTRA_GENERIC_INHERITS_FROM,
ANY,
ServiceT,
ServiceBase,
Service,
D,
C,
B,
A,
]
),
),
(A, B, [A]),
(A, C, [B, A]),
(A, D, [C, B, A]),
],
)
def test_iter_mro_reversed(cls, stop, expected_mro):
assert list(iter_mro_reversed(cls, stop=stop)) == expected_mro
def test_Unordered():
assert Unordered(1) < Unordered(10)
x = set()
x.add(Unordered({"foo": "bar"}))
x.add(Unordered({"foo": "bar"}))
assert len(x) == 2
assert repr(x)
def test__restore_from_keywords():
m = Mock()
_restore_from_keywords(m, {"foo": 1, "bar": 20})
m.assert_called_once_with(foo=1, bar=20)
class X(KeywordReduce):
def __init__(self, name, age):
self.name = name
self.age = age
def __reduce_keywords__(self):
return {"name": self.name, "age": self.age}
def test_KeywordReduce():
with pytest.raises(NotImplementedError):
KeywordReduce().__reduce_keywords__()
x = X("foo", 10)
y = pickle.loads(pickle.dumps(x))
assert y.name == x.name
assert y.age == x.age
def test_qualname_object():
class X: ...
assert qualname("foo") == "builtins.str"
assert qualname(str) == "builtins.str"
assert qualname(X).endswith("test_qualname_object.<locals>.X")
assert qualname(X()).endswith("test_qualname_object.<locals>.X")
def test_shortname_object():
class X: ...
assert shortname("foo") == "builtins.str"
assert shortname(str) == "builtins.str"
assert shortname(X) == __name__ + ".X"
assert shortname(X()) == __name__ + ".X"
def test_canoname():
class X: ...
X.__module__ = "__main__"
x = X()
class Y: ...
y = Y()
assert canoname(X, main_name="faust") == "faust.test_canoname.<locals>.X"
assert canoname(x, main_name="faust") == "faust.test_canoname.<locals>.X"
assert canoname(Y, main_name="faust") == ".".join(
[__name__, "test_canoname.<locals>.Y"]
)
assert canoname(y, main_name="faust") == ".".join(
[__name__, "test_canoname.<locals>.Y"]
)
def test_canonshortname():
class X: ...
X.__module__ = "__main__"
x = X()
class Y: ...
y = Y()
assert canonshortname(X, main_name="faust") == "faust.X"
assert canonshortname(x, main_name="faust") == "faust.X"
assert canonshortname(Y, main_name="faust") == ".".join([__name__, "Y"])
assert canonshortname(y, main_name="faust") == ".".join([__name__, "Y"])
@pytest.mark.skip(reason="Needs fixing, typing.List eval does not work")
def test_eval_type():
assert eval_type("list") is list
assert eval_type("typing.List") is typing.List
def test_annotations():
class X:
Foo: ClassVar[int] = 3
foo: "int"
bar: List["X"]
baz: Union[List["X"], str]
mas: int = 3
fields, defaults = annotations(X, globalns=globals(), localns=locals())
assert fields == {
"Foo": ClassVar[int],
"foo": int,
"bar": List[X],
"baz": Union[List[X], str],
"mas": int,
}
assert defaults["mas"] == 3
def test_annotations__skip_classvar():
class X:
Foo: ClassVar[int] = 3
foo: "int"
bar: List["X"]
baz: Union[List["X"], str]
mas: int = 3
fields, defaults = annotations(
X, globalns=globals(), localns=locals(), skip_classvar=True
)
assert fields == {
"foo": int,
"bar": List[X],
"baz": Union[List[X], str],
"mas": int,
}
assert defaults["mas"] == 3
def test_annotations__invalid_type():
class X:
foo: List
with pytest.raises(InvalidAnnotation):
annotations(
X,
globalns=globals(),
localns=locals(),
invalid_types={List},
skip_classvar=True,
)
def test_annotations__no_local_ns_raises():
class Bar: ...
class X:
bar: "Bar"
with pytest.raises(NameError):
annotations(X, globalns=None, localns=None)
# Union[type(None)] actually returns None
# so we have to construct this object to test condition in code.
WeirdNoneUnion = Union[str, int]
WeirdNoneUnion.__args__ = (type(None), type(None))
@pytest.mark.parametrize(
"input,expected",
[
(Optional[str], str),
(Union[str, None], str),
(Union[str, type(None)], str),
(Optional[List[str]], List[str]),
(Optional[Mapping[int, str]], Mapping[int, str]),
(Optional[AbstractSet[int]], AbstractSet[int]),
(Optional[Set[int]], Set[int]),
(Optional[Tuple[int, ...]], Tuple[int, ...]),
(Optional[Dict[int, str]], Dict[int, str]),
(Optional[List[int]], List[int]),
(str, str),
(List[str], List[str]),
(Union[str, int, float], Union[str, int, float]),
(WeirdNoneUnion, WeirdNoneUnion),
],
)
def test_remove_optional(input, expected):
assert remove_optional(input) == expected
@pytest.mark.parametrize(
"input,expected",
[
(Optional[str], ((), str)),
(Union[str, None], ((), str)),
(Union[str, type(None)], ((), str)),
(Optional[List[str]], ((str,), list)),
(
Optional[Mapping[int, str]],
((int, str), IN(dict, collections.abc.Mapping, typing.Mapping)),
),
(
Optional[AbstractSet[int]],
((int,), IN(set, collections.abc.Set, typing.AbstractSet)),
),
(
Optional[Set[int]],
((int,), IN(set, collections.abc.Set, typing.AbstractSet)),
),
(Optional[Tuple[int, ...]], ((int, ...), IN(tuple, typing.Tuple))),
(Optional[Dict[int, str]], ((int, str), dict)),
(Optional[List[int]], ((int,), list)),
(str, ((), str)),
(List[str], ((str,), list)),
(WeirdNoneUnion, ((type(None), type(None)), Union)),
],
)
def test__remove_optional__find_origin(input, expected):
assert _remove_optional(input, find_origin=True) == expected
def test__remove_optional_edgecase():
input = Union[str, int, float]
expected = (str, int, float)
res = _remove_optional(input, find_origin=True)
assert res[0] == expected
# must use `is` here on Python 3.6
assert res[1] is typing.Union
@pytest.mark.parametrize(
"input,expected",
[
(Optional[str], True),
(Union[str, None], True),
(Union[str, type(None)], True),
(str, False),
(List[str], False),
(Union[str, int, float], False),
],
)
def test_is_optional(input, expected):
assert is_optional(input) == expected
@pytest.mark.parametrize(
"input,expected",
[
(Tuple[int, ...], (tuple, int)),
(List[int], (list, int)),
(Mapping[str, int], (dict, int)),
(Dict[str, int], (dict, int)),
(MutableMapping[str, int], (dict, int)),
(Set[str], (set, str)),
(FrozenSet[str], (set, str)),
(MutableSet[str], (set, str)),
(AbstractSet[str], (set, str)),
(Sequence[str], (list, str)),
],
)
def test_guess_polymorphic_type(input, expected):
assert guess_polymorphic_type(input) == expected
assert guess_polymorphic_type(Optional[input]) == expected
assert guess_polymorphic_type(Union[input, None]) == expected
def test_guess_polymorphic_type__not_generic():
class X: ...
with pytest.raises(TypeError):
guess_polymorphic_type(str)
with pytest.raises(TypeError):
guess_polymorphic_type(bytes)
with pytest.raises(TypeError):
guess_polymorphic_type(X)
def test_label_pass():
s = "foo"
assert label(s) is s
@pytest.mark.parametrize(
"input,expected",
[
(str, False),
(int, False),
(Union[int, bytes], True),
(Optional[str], True),
(int | None, True),
],
)
def test_is_union(input, expected):
assert is_union(input) == expected