1 | n/a | import contextlib |
---|
2 | n/a | import collections |
---|
3 | n/a | import pickle |
---|
4 | n/a | import re |
---|
5 | n/a | import sys |
---|
6 | n/a | from unittest import TestCase, main, skipUnless, SkipTest |
---|
7 | n/a | from copy import copy, deepcopy |
---|
8 | n/a | |
---|
9 | n/a | from typing import Any |
---|
10 | n/a | from typing import TypeVar, AnyStr |
---|
11 | n/a | from typing import T, KT, VT # Not in __all__. |
---|
12 | n/a | from typing import Union, Optional |
---|
13 | n/a | from typing import Tuple, List, MutableMapping |
---|
14 | n/a | from typing import Callable |
---|
15 | n/a | from typing import Generic, ClassVar, GenericMeta |
---|
16 | n/a | from typing import cast |
---|
17 | n/a | from typing import get_type_hints |
---|
18 | n/a | from typing import no_type_check, no_type_check_decorator |
---|
19 | n/a | from typing import Type |
---|
20 | n/a | from typing import NewType |
---|
21 | n/a | from typing import NamedTuple |
---|
22 | n/a | from typing import IO, TextIO, BinaryIO |
---|
23 | n/a | from typing import Pattern, Match |
---|
24 | n/a | import abc |
---|
25 | n/a | import typing |
---|
26 | n/a | import weakref |
---|
27 | n/a | try: |
---|
28 | n/a | import collections.abc as collections_abc |
---|
29 | n/a | except ImportError: |
---|
30 | n/a | import collections as collections_abc # Fallback for PY3.2. |
---|
31 | n/a | |
---|
32 | n/a | |
---|
33 | n/a | class BaseTestCase(TestCase): |
---|
34 | n/a | |
---|
35 | n/a | def assertIsSubclass(self, cls, class_or_tuple, msg=None): |
---|
36 | n/a | if not issubclass(cls, class_or_tuple): |
---|
37 | n/a | message = '%r is not a subclass of %r' % (cls, class_or_tuple) |
---|
38 | n/a | if msg is not None: |
---|
39 | n/a | message += ' : %s' % msg |
---|
40 | n/a | raise self.failureException(message) |
---|
41 | n/a | |
---|
42 | n/a | def assertNotIsSubclass(self, cls, class_or_tuple, msg=None): |
---|
43 | n/a | if issubclass(cls, class_or_tuple): |
---|
44 | n/a | message = '%r is a subclass of %r' % (cls, class_or_tuple) |
---|
45 | n/a | if msg is not None: |
---|
46 | n/a | message += ' : %s' % msg |
---|
47 | n/a | raise self.failureException(message) |
---|
48 | n/a | |
---|
49 | n/a | def clear_caches(self): |
---|
50 | n/a | for f in typing._cleanups: |
---|
51 | n/a | f() |
---|
52 | n/a | |
---|
53 | n/a | |
---|
54 | n/a | class Employee: |
---|
55 | n/a | pass |
---|
56 | n/a | |
---|
57 | n/a | |
---|
58 | n/a | class Manager(Employee): |
---|
59 | n/a | pass |
---|
60 | n/a | |
---|
61 | n/a | |
---|
62 | n/a | class Founder(Employee): |
---|
63 | n/a | pass |
---|
64 | n/a | |
---|
65 | n/a | |
---|
66 | n/a | class ManagingFounder(Manager, Founder): |
---|
67 | n/a | pass |
---|
68 | n/a | |
---|
69 | n/a | |
---|
70 | n/a | class AnyTests(BaseTestCase): |
---|
71 | n/a | |
---|
72 | n/a | def test_any_instance_type_error(self): |
---|
73 | n/a | with self.assertRaises(TypeError): |
---|
74 | n/a | isinstance(42, Any) |
---|
75 | n/a | |
---|
76 | n/a | def test_any_subclass_type_error(self): |
---|
77 | n/a | with self.assertRaises(TypeError): |
---|
78 | n/a | issubclass(Employee, Any) |
---|
79 | n/a | with self.assertRaises(TypeError): |
---|
80 | n/a | issubclass(Any, Employee) |
---|
81 | n/a | |
---|
82 | n/a | def test_repr(self): |
---|
83 | n/a | self.assertEqual(repr(Any), 'typing.Any') |
---|
84 | n/a | |
---|
85 | n/a | def test_errors(self): |
---|
86 | n/a | with self.assertRaises(TypeError): |
---|
87 | n/a | issubclass(42, Any) |
---|
88 | n/a | with self.assertRaises(TypeError): |
---|
89 | n/a | Any[int] # Any is not a generic type. |
---|
90 | n/a | |
---|
91 | n/a | def test_cannot_subclass(self): |
---|
92 | n/a | with self.assertRaises(TypeError): |
---|
93 | n/a | class A(Any): |
---|
94 | n/a | pass |
---|
95 | n/a | with self.assertRaises(TypeError): |
---|
96 | n/a | class A(type(Any)): |
---|
97 | n/a | pass |
---|
98 | n/a | |
---|
99 | n/a | def test_cannot_instantiate(self): |
---|
100 | n/a | with self.assertRaises(TypeError): |
---|
101 | n/a | Any() |
---|
102 | n/a | with self.assertRaises(TypeError): |
---|
103 | n/a | type(Any)() |
---|
104 | n/a | |
---|
105 | n/a | def test_cannot_subscript(self): |
---|
106 | n/a | with self.assertRaises(TypeError): |
---|
107 | n/a | Any[int] |
---|
108 | n/a | |
---|
109 | n/a | def test_any_works_with_alias(self): |
---|
110 | n/a | # These expressions must simply not fail. |
---|
111 | n/a | typing.Match[Any] |
---|
112 | n/a | typing.Pattern[Any] |
---|
113 | n/a | typing.IO[Any] |
---|
114 | n/a | |
---|
115 | n/a | |
---|
116 | n/a | class TypeVarTests(BaseTestCase): |
---|
117 | n/a | |
---|
118 | n/a | def test_basic_plain(self): |
---|
119 | n/a | T = TypeVar('T') |
---|
120 | n/a | # T equals itself. |
---|
121 | n/a | self.assertEqual(T, T) |
---|
122 | n/a | # T is an instance of TypeVar |
---|
123 | n/a | self.assertIsInstance(T, TypeVar) |
---|
124 | n/a | |
---|
125 | n/a | def test_typevar_instance_type_error(self): |
---|
126 | n/a | T = TypeVar('T') |
---|
127 | n/a | with self.assertRaises(TypeError): |
---|
128 | n/a | isinstance(42, T) |
---|
129 | n/a | |
---|
130 | n/a | def test_typevar_subclass_type_error(self): |
---|
131 | n/a | T = TypeVar('T') |
---|
132 | n/a | with self.assertRaises(TypeError): |
---|
133 | n/a | issubclass(int, T) |
---|
134 | n/a | with self.assertRaises(TypeError): |
---|
135 | n/a | issubclass(T, int) |
---|
136 | n/a | |
---|
137 | n/a | def test_constrained_error(self): |
---|
138 | n/a | with self.assertRaises(TypeError): |
---|
139 | n/a | X = TypeVar('X', int) |
---|
140 | n/a | X |
---|
141 | n/a | |
---|
142 | n/a | def test_union_unique(self): |
---|
143 | n/a | X = TypeVar('X') |
---|
144 | n/a | Y = TypeVar('Y') |
---|
145 | n/a | self.assertNotEqual(X, Y) |
---|
146 | n/a | self.assertEqual(Union[X], X) |
---|
147 | n/a | self.assertNotEqual(Union[X], Union[X, Y]) |
---|
148 | n/a | self.assertEqual(Union[X, X], X) |
---|
149 | n/a | self.assertNotEqual(Union[X, int], Union[X]) |
---|
150 | n/a | self.assertNotEqual(Union[X, int], Union[int]) |
---|
151 | n/a | self.assertEqual(Union[X, int].__args__, (X, int)) |
---|
152 | n/a | self.assertEqual(Union[X, int].__parameters__, (X,)) |
---|
153 | n/a | self.assertIs(Union[X, int].__origin__, Union) |
---|
154 | n/a | |
---|
155 | n/a | def test_union_constrained(self): |
---|
156 | n/a | A = TypeVar('A', str, bytes) |
---|
157 | n/a | self.assertNotEqual(Union[A, str], Union[A]) |
---|
158 | n/a | |
---|
159 | n/a | def test_repr(self): |
---|
160 | n/a | self.assertEqual(repr(T), '~T') |
---|
161 | n/a | self.assertEqual(repr(KT), '~KT') |
---|
162 | n/a | self.assertEqual(repr(VT), '~VT') |
---|
163 | n/a | self.assertEqual(repr(AnyStr), '~AnyStr') |
---|
164 | n/a | T_co = TypeVar('T_co', covariant=True) |
---|
165 | n/a | self.assertEqual(repr(T_co), '+T_co') |
---|
166 | n/a | T_contra = TypeVar('T_contra', contravariant=True) |
---|
167 | n/a | self.assertEqual(repr(T_contra), '-T_contra') |
---|
168 | n/a | |
---|
169 | n/a | def test_no_redefinition(self): |
---|
170 | n/a | self.assertNotEqual(TypeVar('T'), TypeVar('T')) |
---|
171 | n/a | self.assertNotEqual(TypeVar('T', int, str), TypeVar('T', int, str)) |
---|
172 | n/a | |
---|
173 | n/a | def test_cannot_subclass_vars(self): |
---|
174 | n/a | with self.assertRaises(TypeError): |
---|
175 | n/a | class V(TypeVar('T')): |
---|
176 | n/a | pass |
---|
177 | n/a | |
---|
178 | n/a | def test_cannot_subclass_var_itself(self): |
---|
179 | n/a | with self.assertRaises(TypeError): |
---|
180 | n/a | class V(TypeVar): |
---|
181 | n/a | pass |
---|
182 | n/a | |
---|
183 | n/a | def test_cannot_instantiate_vars(self): |
---|
184 | n/a | with self.assertRaises(TypeError): |
---|
185 | n/a | TypeVar('A')() |
---|
186 | n/a | |
---|
187 | n/a | def test_bound_errors(self): |
---|
188 | n/a | with self.assertRaises(TypeError): |
---|
189 | n/a | TypeVar('X', bound=42) |
---|
190 | n/a | with self.assertRaises(TypeError): |
---|
191 | n/a | TypeVar('X', str, float, bound=Employee) |
---|
192 | n/a | |
---|
193 | n/a | |
---|
194 | n/a | class UnionTests(BaseTestCase): |
---|
195 | n/a | |
---|
196 | n/a | def test_basics(self): |
---|
197 | n/a | u = Union[int, float] |
---|
198 | n/a | self.assertNotEqual(u, Union) |
---|
199 | n/a | |
---|
200 | n/a | def test_subclass_error(self): |
---|
201 | n/a | with self.assertRaises(TypeError): |
---|
202 | n/a | issubclass(int, Union) |
---|
203 | n/a | with self.assertRaises(TypeError): |
---|
204 | n/a | issubclass(Union, int) |
---|
205 | n/a | with self.assertRaises(TypeError): |
---|
206 | n/a | issubclass(int, Union[int, str]) |
---|
207 | n/a | with self.assertRaises(TypeError): |
---|
208 | n/a | issubclass(Union[int, str], int) |
---|
209 | n/a | |
---|
210 | n/a | def test_union_any(self): |
---|
211 | n/a | u = Union[Any] |
---|
212 | n/a | self.assertEqual(u, Any) |
---|
213 | n/a | u1 = Union[int, Any] |
---|
214 | n/a | u2 = Union[Any, int] |
---|
215 | n/a | u3 = Union[Any, object] |
---|
216 | n/a | self.assertEqual(u1, u2) |
---|
217 | n/a | self.assertNotEqual(u1, Any) |
---|
218 | n/a | self.assertNotEqual(u2, Any) |
---|
219 | n/a | self.assertNotEqual(u3, Any) |
---|
220 | n/a | |
---|
221 | n/a | def test_union_object(self): |
---|
222 | n/a | u = Union[object] |
---|
223 | n/a | self.assertEqual(u, object) |
---|
224 | n/a | u = Union[int, object] |
---|
225 | n/a | self.assertEqual(u, object) |
---|
226 | n/a | u = Union[object, int] |
---|
227 | n/a | self.assertEqual(u, object) |
---|
228 | n/a | |
---|
229 | n/a | def test_unordered(self): |
---|
230 | n/a | u1 = Union[int, float] |
---|
231 | n/a | u2 = Union[float, int] |
---|
232 | n/a | self.assertEqual(u1, u2) |
---|
233 | n/a | |
---|
234 | n/a | def test_single_class_disappears(self): |
---|
235 | n/a | t = Union[Employee] |
---|
236 | n/a | self.assertIs(t, Employee) |
---|
237 | n/a | |
---|
238 | n/a | def test_base_class_disappears(self): |
---|
239 | n/a | u = Union[Employee, Manager, int] |
---|
240 | n/a | self.assertEqual(u, Union[int, Employee]) |
---|
241 | n/a | u = Union[Manager, int, Employee] |
---|
242 | n/a | self.assertEqual(u, Union[int, Employee]) |
---|
243 | n/a | u = Union[Employee, Manager] |
---|
244 | n/a | self.assertIs(u, Employee) |
---|
245 | n/a | |
---|
246 | n/a | def test_union_union(self): |
---|
247 | n/a | u = Union[int, float] |
---|
248 | n/a | v = Union[u, Employee] |
---|
249 | n/a | self.assertEqual(v, Union[int, float, Employee]) |
---|
250 | n/a | |
---|
251 | n/a | def test_repr(self): |
---|
252 | n/a | self.assertEqual(repr(Union), 'typing.Union') |
---|
253 | n/a | u = Union[Employee, int] |
---|
254 | n/a | self.assertEqual(repr(u), 'typing.Union[%s.Employee, int]' % __name__) |
---|
255 | n/a | u = Union[int, Employee] |
---|
256 | n/a | self.assertEqual(repr(u), 'typing.Union[int, %s.Employee]' % __name__) |
---|
257 | n/a | |
---|
258 | n/a | def test_cannot_subclass(self): |
---|
259 | n/a | with self.assertRaises(TypeError): |
---|
260 | n/a | class C(Union): |
---|
261 | n/a | pass |
---|
262 | n/a | with self.assertRaises(TypeError): |
---|
263 | n/a | class C(type(Union)): |
---|
264 | n/a | pass |
---|
265 | n/a | with self.assertRaises(TypeError): |
---|
266 | n/a | class C(Union[int, str]): |
---|
267 | n/a | pass |
---|
268 | n/a | |
---|
269 | n/a | def test_cannot_instantiate(self): |
---|
270 | n/a | with self.assertRaises(TypeError): |
---|
271 | n/a | Union() |
---|
272 | n/a | with self.assertRaises(TypeError): |
---|
273 | n/a | type(Union)() |
---|
274 | n/a | u = Union[int, float] |
---|
275 | n/a | with self.assertRaises(TypeError): |
---|
276 | n/a | u() |
---|
277 | n/a | with self.assertRaises(TypeError): |
---|
278 | n/a | type(u)() |
---|
279 | n/a | |
---|
280 | n/a | def test_union_generalization(self): |
---|
281 | n/a | self.assertFalse(Union[str, typing.Iterable[int]] == str) |
---|
282 | n/a | self.assertFalse(Union[str, typing.Iterable[int]] == typing.Iterable[int]) |
---|
283 | n/a | self.assertTrue(Union[str, typing.Iterable] == typing.Iterable) |
---|
284 | n/a | |
---|
285 | n/a | def test_union_compare_other(self): |
---|
286 | n/a | self.assertNotEqual(Union, object) |
---|
287 | n/a | self.assertNotEqual(Union, Any) |
---|
288 | n/a | self.assertNotEqual(ClassVar, Union) |
---|
289 | n/a | self.assertNotEqual(Optional, Union) |
---|
290 | n/a | self.assertNotEqual([None], Optional) |
---|
291 | n/a | self.assertNotEqual(Optional, typing.Mapping) |
---|
292 | n/a | self.assertNotEqual(Optional[typing.MutableMapping], Union) |
---|
293 | n/a | |
---|
294 | n/a | def test_optional(self): |
---|
295 | n/a | o = Optional[int] |
---|
296 | n/a | u = Union[int, None] |
---|
297 | n/a | self.assertEqual(o, u) |
---|
298 | n/a | |
---|
299 | n/a | def test_empty(self): |
---|
300 | n/a | with self.assertRaises(TypeError): |
---|
301 | n/a | Union[()] |
---|
302 | n/a | |
---|
303 | n/a | def test_union_instance_type_error(self): |
---|
304 | n/a | with self.assertRaises(TypeError): |
---|
305 | n/a | isinstance(42, Union[int, str]) |
---|
306 | n/a | |
---|
307 | n/a | def test_union_str_pattern(self): |
---|
308 | n/a | # Shouldn't crash; see http://bugs.python.org/issue25390 |
---|
309 | n/a | A = Union[str, Pattern] |
---|
310 | n/a | A |
---|
311 | n/a | |
---|
312 | n/a | def test_etree(self): |
---|
313 | n/a | # See https://github.com/python/typing/issues/229 |
---|
314 | n/a | # (Only relevant for Python 2.) |
---|
315 | n/a | try: |
---|
316 | n/a | from xml.etree.cElementTree import Element |
---|
317 | n/a | except ImportError: |
---|
318 | n/a | raise SkipTest("cElementTree not found") |
---|
319 | n/a | Union[Element, str] # Shouldn't crash |
---|
320 | n/a | |
---|
321 | n/a | def Elem(*args): |
---|
322 | n/a | return Element(*args) |
---|
323 | n/a | |
---|
324 | n/a | Union[Elem, str] # Nor should this |
---|
325 | n/a | |
---|
326 | n/a | |
---|
327 | n/a | class TupleTests(BaseTestCase): |
---|
328 | n/a | |
---|
329 | n/a | def test_basics(self): |
---|
330 | n/a | with self.assertRaises(TypeError): |
---|
331 | n/a | issubclass(Tuple, Tuple[int, str]) |
---|
332 | n/a | with self.assertRaises(TypeError): |
---|
333 | n/a | issubclass(tuple, Tuple[int, str]) |
---|
334 | n/a | |
---|
335 | n/a | class TP(tuple): ... |
---|
336 | n/a | self.assertTrue(issubclass(tuple, Tuple)) |
---|
337 | n/a | self.assertTrue(issubclass(TP, Tuple)) |
---|
338 | n/a | |
---|
339 | n/a | def test_equality(self): |
---|
340 | n/a | self.assertEqual(Tuple[int], Tuple[int]) |
---|
341 | n/a | self.assertEqual(Tuple[int, ...], Tuple[int, ...]) |
---|
342 | n/a | self.assertNotEqual(Tuple[int], Tuple[int, int]) |
---|
343 | n/a | self.assertNotEqual(Tuple[int], Tuple[int, ...]) |
---|
344 | n/a | |
---|
345 | n/a | def test_tuple_subclass(self): |
---|
346 | n/a | class MyTuple(tuple): |
---|
347 | n/a | pass |
---|
348 | n/a | self.assertTrue(issubclass(MyTuple, Tuple)) |
---|
349 | n/a | |
---|
350 | n/a | def test_tuple_instance_type_error(self): |
---|
351 | n/a | with self.assertRaises(TypeError): |
---|
352 | n/a | isinstance((0, 0), Tuple[int, int]) |
---|
353 | n/a | self.assertIsInstance((0, 0), Tuple) |
---|
354 | n/a | |
---|
355 | n/a | def test_repr(self): |
---|
356 | n/a | self.assertEqual(repr(Tuple), 'typing.Tuple') |
---|
357 | n/a | self.assertEqual(repr(Tuple[()]), 'typing.Tuple[()]') |
---|
358 | n/a | self.assertEqual(repr(Tuple[int, float]), 'typing.Tuple[int, float]') |
---|
359 | n/a | self.assertEqual(repr(Tuple[int, ...]), 'typing.Tuple[int, ...]') |
---|
360 | n/a | |
---|
361 | n/a | def test_errors(self): |
---|
362 | n/a | with self.assertRaises(TypeError): |
---|
363 | n/a | issubclass(42, Tuple) |
---|
364 | n/a | with self.assertRaises(TypeError): |
---|
365 | n/a | issubclass(42, Tuple[int]) |
---|
366 | n/a | |
---|
367 | n/a | |
---|
368 | n/a | class CallableTests(BaseTestCase): |
---|
369 | n/a | |
---|
370 | n/a | def test_self_subclass(self): |
---|
371 | n/a | with self.assertRaises(TypeError): |
---|
372 | n/a | self.assertTrue(issubclass(type(lambda x: x), Callable[[int], int])) |
---|
373 | n/a | self.assertTrue(issubclass(type(lambda x: x), Callable)) |
---|
374 | n/a | |
---|
375 | n/a | def test_eq_hash(self): |
---|
376 | n/a | self.assertEqual(Callable[[int], int], Callable[[int], int]) |
---|
377 | n/a | self.assertEqual(len({Callable[[int], int], Callable[[int], int]}), 1) |
---|
378 | n/a | self.assertNotEqual(Callable[[int], int], Callable[[int], str]) |
---|
379 | n/a | self.assertNotEqual(Callable[[int], int], Callable[[str], int]) |
---|
380 | n/a | self.assertNotEqual(Callable[[int], int], Callable[[int, int], int]) |
---|
381 | n/a | self.assertNotEqual(Callable[[int], int], Callable[[], int]) |
---|
382 | n/a | self.assertNotEqual(Callable[[int], int], Callable) |
---|
383 | n/a | |
---|
384 | n/a | def test_cannot_instantiate(self): |
---|
385 | n/a | with self.assertRaises(TypeError): |
---|
386 | n/a | Callable() |
---|
387 | n/a | with self.assertRaises(TypeError): |
---|
388 | n/a | type(Callable)() |
---|
389 | n/a | c = Callable[[int], str] |
---|
390 | n/a | with self.assertRaises(TypeError): |
---|
391 | n/a | c() |
---|
392 | n/a | with self.assertRaises(TypeError): |
---|
393 | n/a | type(c)() |
---|
394 | n/a | |
---|
395 | n/a | def test_callable_wrong_forms(self): |
---|
396 | n/a | with self.assertRaises(TypeError): |
---|
397 | n/a | Callable[[...], int] |
---|
398 | n/a | with self.assertRaises(TypeError): |
---|
399 | n/a | Callable[(), int] |
---|
400 | n/a | with self.assertRaises(TypeError): |
---|
401 | n/a | Callable[[()], int] |
---|
402 | n/a | with self.assertRaises(TypeError): |
---|
403 | n/a | Callable[[int, 1], 2] |
---|
404 | n/a | |
---|
405 | n/a | def test_callable_instance_works(self): |
---|
406 | n/a | def f(): |
---|
407 | n/a | pass |
---|
408 | n/a | self.assertIsInstance(f, Callable) |
---|
409 | n/a | self.assertNotIsInstance(None, Callable) |
---|
410 | n/a | |
---|
411 | n/a | def test_callable_instance_type_error(self): |
---|
412 | n/a | def f(): |
---|
413 | n/a | pass |
---|
414 | n/a | with self.assertRaises(TypeError): |
---|
415 | n/a | self.assertIsInstance(f, Callable[[], None]) |
---|
416 | n/a | with self.assertRaises(TypeError): |
---|
417 | n/a | self.assertIsInstance(f, Callable[[], Any]) |
---|
418 | n/a | with self.assertRaises(TypeError): |
---|
419 | n/a | self.assertNotIsInstance(None, Callable[[], None]) |
---|
420 | n/a | with self.assertRaises(TypeError): |
---|
421 | n/a | self.assertNotIsInstance(None, Callable[[], Any]) |
---|
422 | n/a | |
---|
423 | n/a | def test_repr(self): |
---|
424 | n/a | ct0 = Callable[[], bool] |
---|
425 | n/a | self.assertEqual(repr(ct0), 'typing.Callable[[], bool]') |
---|
426 | n/a | ct2 = Callable[[str, float], int] |
---|
427 | n/a | self.assertEqual(repr(ct2), 'typing.Callable[[str, float], int]') |
---|
428 | n/a | ctv = Callable[..., str] |
---|
429 | n/a | self.assertEqual(repr(ctv), 'typing.Callable[..., str]') |
---|
430 | n/a | |
---|
431 | n/a | def test_callable_with_ellipsis(self): |
---|
432 | n/a | |
---|
433 | n/a | def foo(a: Callable[..., T]): |
---|
434 | n/a | pass |
---|
435 | n/a | |
---|
436 | n/a | self.assertEqual(get_type_hints(foo, globals(), locals()), |
---|
437 | n/a | {'a': Callable[..., T]}) |
---|
438 | n/a | |
---|
439 | n/a | def test_ellipsis_in_generic(self): |
---|
440 | n/a | # Shouldn't crash; see https://github.com/python/typing/issues/259 |
---|
441 | n/a | typing.List[Callable[..., str]] |
---|
442 | n/a | |
---|
443 | n/a | |
---|
444 | n/a | XK = TypeVar('XK', str, bytes) |
---|
445 | n/a | XV = TypeVar('XV') |
---|
446 | n/a | |
---|
447 | n/a | |
---|
448 | n/a | class SimpleMapping(Generic[XK, XV]): |
---|
449 | n/a | |
---|
450 | n/a | def __getitem__(self, key: XK) -> XV: |
---|
451 | n/a | ... |
---|
452 | n/a | |
---|
453 | n/a | def __setitem__(self, key: XK, value: XV): |
---|
454 | n/a | ... |
---|
455 | n/a | |
---|
456 | n/a | def get(self, key: XK, default: XV = None) -> XV: |
---|
457 | n/a | ... |
---|
458 | n/a | |
---|
459 | n/a | |
---|
460 | n/a | class MySimpleMapping(SimpleMapping[XK, XV]): |
---|
461 | n/a | |
---|
462 | n/a | def __init__(self): |
---|
463 | n/a | self.store = {} |
---|
464 | n/a | |
---|
465 | n/a | def __getitem__(self, key: str): |
---|
466 | n/a | return self.store[key] |
---|
467 | n/a | |
---|
468 | n/a | def __setitem__(self, key: str, value): |
---|
469 | n/a | self.store[key] = value |
---|
470 | n/a | |
---|
471 | n/a | def get(self, key: str, default=None): |
---|
472 | n/a | try: |
---|
473 | n/a | return self.store[key] |
---|
474 | n/a | except KeyError: |
---|
475 | n/a | return default |
---|
476 | n/a | |
---|
477 | n/a | |
---|
478 | n/a | class ProtocolTests(BaseTestCase): |
---|
479 | n/a | |
---|
480 | n/a | def test_supports_int(self): |
---|
481 | n/a | self.assertIsSubclass(int, typing.SupportsInt) |
---|
482 | n/a | self.assertNotIsSubclass(str, typing.SupportsInt) |
---|
483 | n/a | |
---|
484 | n/a | def test_supports_float(self): |
---|
485 | n/a | self.assertIsSubclass(float, typing.SupportsFloat) |
---|
486 | n/a | self.assertNotIsSubclass(str, typing.SupportsFloat) |
---|
487 | n/a | |
---|
488 | n/a | def test_supports_complex(self): |
---|
489 | n/a | |
---|
490 | n/a | # Note: complex itself doesn't have __complex__. |
---|
491 | n/a | class C: |
---|
492 | n/a | def __complex__(self): |
---|
493 | n/a | return 0j |
---|
494 | n/a | |
---|
495 | n/a | self.assertIsSubclass(C, typing.SupportsComplex) |
---|
496 | n/a | self.assertNotIsSubclass(str, typing.SupportsComplex) |
---|
497 | n/a | |
---|
498 | n/a | def test_supports_bytes(self): |
---|
499 | n/a | |
---|
500 | n/a | # Note: bytes itself doesn't have __bytes__. |
---|
501 | n/a | class B: |
---|
502 | n/a | def __bytes__(self): |
---|
503 | n/a | return b'' |
---|
504 | n/a | |
---|
505 | n/a | self.assertIsSubclass(B, typing.SupportsBytes) |
---|
506 | n/a | self.assertNotIsSubclass(str, typing.SupportsBytes) |
---|
507 | n/a | |
---|
508 | n/a | def test_supports_abs(self): |
---|
509 | n/a | self.assertIsSubclass(float, typing.SupportsAbs) |
---|
510 | n/a | self.assertIsSubclass(int, typing.SupportsAbs) |
---|
511 | n/a | self.assertNotIsSubclass(str, typing.SupportsAbs) |
---|
512 | n/a | |
---|
513 | n/a | def test_supports_round(self): |
---|
514 | n/a | issubclass(float, typing.SupportsRound) |
---|
515 | n/a | self.assertIsSubclass(float, typing.SupportsRound) |
---|
516 | n/a | self.assertIsSubclass(int, typing.SupportsRound) |
---|
517 | n/a | self.assertNotIsSubclass(str, typing.SupportsRound) |
---|
518 | n/a | |
---|
519 | n/a | def test_reversible(self): |
---|
520 | n/a | self.assertIsSubclass(list, typing.Reversible) |
---|
521 | n/a | self.assertNotIsSubclass(int, typing.Reversible) |
---|
522 | n/a | |
---|
523 | n/a | def test_protocol_instance_type_error(self): |
---|
524 | n/a | with self.assertRaises(TypeError): |
---|
525 | n/a | isinstance(0, typing.SupportsAbs) |
---|
526 | n/a | class C1(typing.SupportsInt): |
---|
527 | n/a | def __int__(self) -> int: |
---|
528 | n/a | return 42 |
---|
529 | n/a | class C2(C1): |
---|
530 | n/a | pass |
---|
531 | n/a | c = C2() |
---|
532 | n/a | self.assertIsInstance(c, C1) |
---|
533 | n/a | |
---|
534 | n/a | |
---|
535 | n/a | class GenericTests(BaseTestCase): |
---|
536 | n/a | |
---|
537 | n/a | def test_basics(self): |
---|
538 | n/a | X = SimpleMapping[str, Any] |
---|
539 | n/a | self.assertEqual(X.__parameters__, ()) |
---|
540 | n/a | with self.assertRaises(TypeError): |
---|
541 | n/a | X[str] |
---|
542 | n/a | with self.assertRaises(TypeError): |
---|
543 | n/a | X[str, str] |
---|
544 | n/a | Y = SimpleMapping[XK, str] |
---|
545 | n/a | self.assertEqual(Y.__parameters__, (XK,)) |
---|
546 | n/a | Y[str] |
---|
547 | n/a | with self.assertRaises(TypeError): |
---|
548 | n/a | Y[str, str] |
---|
549 | n/a | |
---|
550 | n/a | def test_generic_errors(self): |
---|
551 | n/a | T = TypeVar('T') |
---|
552 | n/a | with self.assertRaises(TypeError): |
---|
553 | n/a | Generic[T]() |
---|
554 | n/a | with self.assertRaises(TypeError): |
---|
555 | n/a | isinstance([], List[int]) |
---|
556 | n/a | with self.assertRaises(TypeError): |
---|
557 | n/a | issubclass(list, List[int]) |
---|
558 | n/a | |
---|
559 | n/a | def test_init(self): |
---|
560 | n/a | T = TypeVar('T') |
---|
561 | n/a | S = TypeVar('S') |
---|
562 | n/a | with self.assertRaises(TypeError): |
---|
563 | n/a | Generic[T, T] |
---|
564 | n/a | with self.assertRaises(TypeError): |
---|
565 | n/a | Generic[T, S, T] |
---|
566 | n/a | |
---|
567 | n/a | def test_repr(self): |
---|
568 | n/a | self.assertEqual(repr(SimpleMapping), |
---|
569 | n/a | __name__ + '.' + 'SimpleMapping') |
---|
570 | n/a | self.assertEqual(repr(MySimpleMapping), |
---|
571 | n/a | __name__ + '.' + 'MySimpleMapping') |
---|
572 | n/a | |
---|
573 | n/a | def test_chain_repr(self): |
---|
574 | n/a | T = TypeVar('T') |
---|
575 | n/a | S = TypeVar('S') |
---|
576 | n/a | |
---|
577 | n/a | class C(Generic[T]): |
---|
578 | n/a | pass |
---|
579 | n/a | |
---|
580 | n/a | X = C[Tuple[S, T]] |
---|
581 | n/a | self.assertEqual(X, C[Tuple[S, T]]) |
---|
582 | n/a | self.assertNotEqual(X, C[Tuple[T, S]]) |
---|
583 | n/a | |
---|
584 | n/a | Y = X[T, int] |
---|
585 | n/a | self.assertEqual(Y, X[T, int]) |
---|
586 | n/a | self.assertNotEqual(Y, X[S, int]) |
---|
587 | n/a | self.assertNotEqual(Y, X[T, str]) |
---|
588 | n/a | |
---|
589 | n/a | Z = Y[str] |
---|
590 | n/a | self.assertEqual(Z, Y[str]) |
---|
591 | n/a | self.assertNotEqual(Z, Y[int]) |
---|
592 | n/a | self.assertNotEqual(Z, Y[T]) |
---|
593 | n/a | |
---|
594 | n/a | self.assertTrue(str(Z).endswith( |
---|
595 | n/a | '.C[typing.Tuple[str, int]]')) |
---|
596 | n/a | |
---|
597 | n/a | def test_new_repr(self): |
---|
598 | n/a | T = TypeVar('T') |
---|
599 | n/a | U = TypeVar('U', covariant=True) |
---|
600 | n/a | S = TypeVar('S') |
---|
601 | n/a | |
---|
602 | n/a | self.assertEqual(repr(List), 'typing.List') |
---|
603 | n/a | self.assertEqual(repr(List[T]), 'typing.List[~T]') |
---|
604 | n/a | self.assertEqual(repr(List[U]), 'typing.List[+U]') |
---|
605 | n/a | self.assertEqual(repr(List[S][T][int]), 'typing.List[int]') |
---|
606 | n/a | self.assertEqual(repr(List[int]), 'typing.List[int]') |
---|
607 | n/a | |
---|
608 | n/a | def test_new_repr_complex(self): |
---|
609 | n/a | T = TypeVar('T') |
---|
610 | n/a | TS = TypeVar('TS') |
---|
611 | n/a | |
---|
612 | n/a | self.assertEqual(repr(typing.Mapping[T, TS][TS, T]), 'typing.Mapping[~TS, ~T]') |
---|
613 | n/a | self.assertEqual(repr(List[Tuple[T, TS]][int, T]), |
---|
614 | n/a | 'typing.List[typing.Tuple[int, ~T]]') |
---|
615 | n/a | self.assertEqual( |
---|
616 | n/a | repr(List[Tuple[T, T]][List[int]]), |
---|
617 | n/a | 'typing.List[typing.Tuple[typing.List[int], typing.List[int]]]' |
---|
618 | n/a | ) |
---|
619 | n/a | |
---|
620 | n/a | def test_new_repr_bare(self): |
---|
621 | n/a | T = TypeVar('T') |
---|
622 | n/a | self.assertEqual(repr(Generic[T]), 'typing.Generic[~T]') |
---|
623 | n/a | self.assertEqual(repr(typing._Protocol[T]), 'typing.Protocol[~T]') |
---|
624 | n/a | class C(typing.Dict[Any, Any]): ... |
---|
625 | n/a | # this line should just work |
---|
626 | n/a | repr(C.__mro__) |
---|
627 | n/a | |
---|
628 | n/a | def test_dict(self): |
---|
629 | n/a | T = TypeVar('T') |
---|
630 | n/a | |
---|
631 | n/a | class B(Generic[T]): |
---|
632 | n/a | pass |
---|
633 | n/a | |
---|
634 | n/a | b = B() |
---|
635 | n/a | b.foo = 42 |
---|
636 | n/a | self.assertEqual(b.__dict__, {'foo': 42}) |
---|
637 | n/a | |
---|
638 | n/a | class C(B[int]): |
---|
639 | n/a | pass |
---|
640 | n/a | |
---|
641 | n/a | c = C() |
---|
642 | n/a | c.bar = 'abc' |
---|
643 | n/a | self.assertEqual(c.__dict__, {'bar': 'abc'}) |
---|
644 | n/a | |
---|
645 | n/a | def test_false_subclasses(self): |
---|
646 | n/a | class MyMapping(MutableMapping[str, str]): pass |
---|
647 | n/a | self.assertNotIsInstance({}, MyMapping) |
---|
648 | n/a | self.assertNotIsSubclass(dict, MyMapping) |
---|
649 | n/a | |
---|
650 | n/a | def test_abc_bases(self): |
---|
651 | n/a | class MM(MutableMapping[str, str]): |
---|
652 | n/a | def __getitem__(self, k): |
---|
653 | n/a | return None |
---|
654 | n/a | def __setitem__(self, k, v): |
---|
655 | n/a | pass |
---|
656 | n/a | def __delitem__(self, k): |
---|
657 | n/a | pass |
---|
658 | n/a | def __iter__(self): |
---|
659 | n/a | return iter(()) |
---|
660 | n/a | def __len__(self): |
---|
661 | n/a | return 0 |
---|
662 | n/a | # this should just work |
---|
663 | n/a | MM().update() |
---|
664 | n/a | self.assertIsInstance(MM(), collections_abc.MutableMapping) |
---|
665 | n/a | self.assertIsInstance(MM(), MutableMapping) |
---|
666 | n/a | self.assertNotIsInstance(MM(), List) |
---|
667 | n/a | self.assertNotIsInstance({}, MM) |
---|
668 | n/a | |
---|
669 | n/a | def test_multiple_bases(self): |
---|
670 | n/a | class MM1(MutableMapping[str, str], collections_abc.MutableMapping): |
---|
671 | n/a | pass |
---|
672 | n/a | with self.assertRaises(TypeError): |
---|
673 | n/a | # consistent MRO not possible |
---|
674 | n/a | class MM2(collections_abc.MutableMapping, MutableMapping[str, str]): |
---|
675 | n/a | pass |
---|
676 | n/a | |
---|
677 | n/a | def test_orig_bases(self): |
---|
678 | n/a | T = TypeVar('T') |
---|
679 | n/a | class C(typing.Dict[str, T]): ... |
---|
680 | n/a | self.assertEqual(C.__orig_bases__, (typing.Dict[str, T],)) |
---|
681 | n/a | |
---|
682 | n/a | def test_naive_runtime_checks(self): |
---|
683 | n/a | def naive_dict_check(obj, tp): |
---|
684 | n/a | # Check if a dictionary conforms to Dict type |
---|
685 | n/a | if len(tp.__parameters__) > 0: |
---|
686 | n/a | raise NotImplementedError |
---|
687 | n/a | if tp.__args__: |
---|
688 | n/a | KT, VT = tp.__args__ |
---|
689 | n/a | return all( |
---|
690 | n/a | isinstance(k, KT) and isinstance(v, VT) |
---|
691 | n/a | for k, v in obj.items() |
---|
692 | n/a | ) |
---|
693 | n/a | self.assertTrue(naive_dict_check({'x': 1}, typing.Dict[str, int])) |
---|
694 | n/a | self.assertFalse(naive_dict_check({1: 'x'}, typing.Dict[str, int])) |
---|
695 | n/a | with self.assertRaises(NotImplementedError): |
---|
696 | n/a | naive_dict_check({1: 'x'}, typing.Dict[str, T]) |
---|
697 | n/a | |
---|
698 | n/a | def naive_generic_check(obj, tp): |
---|
699 | n/a | # Check if an instance conforms to the generic class |
---|
700 | n/a | if not hasattr(obj, '__orig_class__'): |
---|
701 | n/a | raise NotImplementedError |
---|
702 | n/a | return obj.__orig_class__ == tp |
---|
703 | n/a | class Node(Generic[T]): ... |
---|
704 | n/a | self.assertTrue(naive_generic_check(Node[int](), Node[int])) |
---|
705 | n/a | self.assertFalse(naive_generic_check(Node[str](), Node[int])) |
---|
706 | n/a | self.assertFalse(naive_generic_check(Node[str](), List)) |
---|
707 | n/a | with self.assertRaises(NotImplementedError): |
---|
708 | n/a | naive_generic_check([1, 2, 3], Node[int]) |
---|
709 | n/a | |
---|
710 | n/a | def naive_list_base_check(obj, tp): |
---|
711 | n/a | # Check if list conforms to a List subclass |
---|
712 | n/a | return all(isinstance(x, tp.__orig_bases__[0].__args__[0]) |
---|
713 | n/a | for x in obj) |
---|
714 | n/a | class C(List[int]): ... |
---|
715 | n/a | self.assertTrue(naive_list_base_check([1, 2, 3], C)) |
---|
716 | n/a | self.assertFalse(naive_list_base_check(['a', 'b'], C)) |
---|
717 | n/a | |
---|
718 | n/a | def test_multi_subscr_base(self): |
---|
719 | n/a | T = TypeVar('T') |
---|
720 | n/a | U = TypeVar('U') |
---|
721 | n/a | V = TypeVar('V') |
---|
722 | n/a | class C(List[T][U][V]): ... |
---|
723 | n/a | class D(C, List[T][U][V]): ... |
---|
724 | n/a | self.assertEqual(C.__parameters__, (V,)) |
---|
725 | n/a | self.assertEqual(D.__parameters__, (V,)) |
---|
726 | n/a | self.assertEqual(C[int].__parameters__, ()) |
---|
727 | n/a | self.assertEqual(D[int].__parameters__, ()) |
---|
728 | n/a | self.assertEqual(C[int].__args__, (int,)) |
---|
729 | n/a | self.assertEqual(D[int].__args__, (int,)) |
---|
730 | n/a | self.assertEqual(C.__bases__, (List,)) |
---|
731 | n/a | self.assertEqual(D.__bases__, (C, List)) |
---|
732 | n/a | self.assertEqual(C.__orig_bases__, (List[T][U][V],)) |
---|
733 | n/a | self.assertEqual(D.__orig_bases__, (C, List[T][U][V])) |
---|
734 | n/a | |
---|
735 | n/a | def test_subscript_meta(self): |
---|
736 | n/a | T = TypeVar('T') |
---|
737 | n/a | self.assertEqual(Type[GenericMeta], Type[GenericMeta]) |
---|
738 | n/a | self.assertEqual(Union[T, int][GenericMeta], Union[GenericMeta, int]) |
---|
739 | n/a | self.assertEqual(Callable[..., GenericMeta].__args__, (Ellipsis, GenericMeta)) |
---|
740 | n/a | |
---|
741 | n/a | def test_extended_generic_rules_eq(self): |
---|
742 | n/a | T = TypeVar('T') |
---|
743 | n/a | U = TypeVar('U') |
---|
744 | n/a | self.assertEqual(Tuple[T, T][int], Tuple[int, int]) |
---|
745 | n/a | self.assertEqual(typing.Iterable[Tuple[T, T]][T], typing.Iterable[Tuple[T, T]]) |
---|
746 | n/a | with self.assertRaises(TypeError): |
---|
747 | n/a | Tuple[T, int][()] |
---|
748 | n/a | with self.assertRaises(TypeError): |
---|
749 | n/a | Tuple[T, U][T, ...] |
---|
750 | n/a | |
---|
751 | n/a | self.assertEqual(Union[T, int][int], int) |
---|
752 | n/a | self.assertEqual(Union[T, U][int, Union[int, str]], Union[int, str]) |
---|
753 | n/a | class Base: ... |
---|
754 | n/a | class Derived(Base): ... |
---|
755 | n/a | self.assertEqual(Union[T, Base][Derived], Base) |
---|
756 | n/a | with self.assertRaises(TypeError): |
---|
757 | n/a | Union[T, int][1] |
---|
758 | n/a | |
---|
759 | n/a | self.assertEqual(Callable[[T], T][KT], Callable[[KT], KT]) |
---|
760 | n/a | self.assertEqual(Callable[..., List[T]][int], Callable[..., List[int]]) |
---|
761 | n/a | with self.assertRaises(TypeError): |
---|
762 | n/a | Callable[[T], U][..., int] |
---|
763 | n/a | with self.assertRaises(TypeError): |
---|
764 | n/a | Callable[[T], U][[], int] |
---|
765 | n/a | |
---|
766 | n/a | def test_extended_generic_rules_repr(self): |
---|
767 | n/a | T = TypeVar('T') |
---|
768 | n/a | self.assertEqual(repr(Union[Tuple, Callable]).replace('typing.', ''), |
---|
769 | n/a | 'Union[Tuple, Callable]') |
---|
770 | n/a | self.assertEqual(repr(Union[Tuple, Tuple[int]]).replace('typing.', ''), |
---|
771 | n/a | 'Tuple') |
---|
772 | n/a | self.assertEqual(repr(Callable[..., Optional[T]][int]).replace('typing.', ''), |
---|
773 | n/a | 'Callable[..., Union[int, NoneType]]') |
---|
774 | n/a | self.assertEqual(repr(Callable[[], List[T]][int]).replace('typing.', ''), |
---|
775 | n/a | 'Callable[[], List[int]]') |
---|
776 | n/a | |
---|
777 | n/a | def test_generic_forward_ref(self): |
---|
778 | n/a | def foobar(x: List[List['CC']]): ... |
---|
779 | n/a | class CC: ... |
---|
780 | n/a | self.assertEqual( |
---|
781 | n/a | get_type_hints(foobar, globals(), locals()), |
---|
782 | n/a | {'x': List[List[CC]]} |
---|
783 | n/a | ) |
---|
784 | n/a | T = TypeVar('T') |
---|
785 | n/a | AT = Tuple[T, ...] |
---|
786 | n/a | def barfoo(x: AT): ... |
---|
787 | n/a | self.assertIs(get_type_hints(barfoo, globals(), locals())['x'], AT) |
---|
788 | n/a | CT = Callable[..., List[T]] |
---|
789 | n/a | def barfoo2(x: CT): ... |
---|
790 | n/a | self.assertIs(get_type_hints(barfoo2, globals(), locals())['x'], CT) |
---|
791 | n/a | |
---|
792 | n/a | def test_extended_generic_rules_subclassing(self): |
---|
793 | n/a | class T1(Tuple[T, KT]): ... |
---|
794 | n/a | class T2(Tuple[T, ...]): ... |
---|
795 | n/a | class C1(Callable[[T], T]): ... |
---|
796 | n/a | class C2(Callable[..., int]): |
---|
797 | n/a | def __call__(self): |
---|
798 | n/a | return None |
---|
799 | n/a | |
---|
800 | n/a | self.assertEqual(T1.__parameters__, (T, KT)) |
---|
801 | n/a | self.assertEqual(T1[int, str].__args__, (int, str)) |
---|
802 | n/a | self.assertEqual(T1[int, T].__origin__, T1) |
---|
803 | n/a | |
---|
804 | n/a | self.assertEqual(T2.__parameters__, (T,)) |
---|
805 | n/a | with self.assertRaises(TypeError): |
---|
806 | n/a | T1[int] |
---|
807 | n/a | with self.assertRaises(TypeError): |
---|
808 | n/a | T2[int, str] |
---|
809 | n/a | |
---|
810 | n/a | self.assertEqual(repr(C1[int]).split('.')[-1], 'C1[int]') |
---|
811 | n/a | self.assertEqual(C2.__parameters__, ()) |
---|
812 | n/a | self.assertIsInstance(C2(), collections_abc.Callable) |
---|
813 | n/a | self.assertIsSubclass(C2, collections_abc.Callable) |
---|
814 | n/a | self.assertIsSubclass(C1, collections_abc.Callable) |
---|
815 | n/a | self.assertIsInstance(T1(), tuple) |
---|
816 | n/a | self.assertIsSubclass(T2, tuple) |
---|
817 | n/a | self.assertIsSubclass(Tuple[int, ...], typing.Sequence) |
---|
818 | n/a | self.assertIsSubclass(Tuple[int, ...], typing.Iterable) |
---|
819 | n/a | |
---|
820 | n/a | def test_fail_with_bare_union(self): |
---|
821 | n/a | with self.assertRaises(TypeError): |
---|
822 | n/a | List[Union] |
---|
823 | n/a | with self.assertRaises(TypeError): |
---|
824 | n/a | Tuple[Optional] |
---|
825 | n/a | with self.assertRaises(TypeError): |
---|
826 | n/a | ClassVar[ClassVar] |
---|
827 | n/a | with self.assertRaises(TypeError): |
---|
828 | n/a | List[ClassVar[int]] |
---|
829 | n/a | |
---|
830 | n/a | def test_fail_with_bare_generic(self): |
---|
831 | n/a | T = TypeVar('T') |
---|
832 | n/a | with self.assertRaises(TypeError): |
---|
833 | n/a | List[Generic] |
---|
834 | n/a | with self.assertRaises(TypeError): |
---|
835 | n/a | Tuple[Generic[T]] |
---|
836 | n/a | with self.assertRaises(TypeError): |
---|
837 | n/a | List[typing._Protocol] |
---|
838 | n/a | |
---|
839 | n/a | def test_type_erasure_special(self): |
---|
840 | n/a | T = TypeVar('T') |
---|
841 | n/a | # this is the only test that checks type caching |
---|
842 | n/a | self.clear_caches() |
---|
843 | n/a | class MyTup(Tuple[T, T]): ... |
---|
844 | n/a | self.assertIs(MyTup[int]().__class__, MyTup) |
---|
845 | n/a | self.assertIs(MyTup[int]().__orig_class__, MyTup[int]) |
---|
846 | n/a | class MyCall(Callable[..., T]): |
---|
847 | n/a | def __call__(self): return None |
---|
848 | n/a | self.assertIs(MyCall[T]().__class__, MyCall) |
---|
849 | n/a | self.assertIs(MyCall[T]().__orig_class__, MyCall[T]) |
---|
850 | n/a | class MyDict(typing.Dict[T, T]): ... |
---|
851 | n/a | self.assertIs(MyDict[int]().__class__, MyDict) |
---|
852 | n/a | self.assertIs(MyDict[int]().__orig_class__, MyDict[int]) |
---|
853 | n/a | class MyDef(typing.DefaultDict[str, T]): ... |
---|
854 | n/a | self.assertIs(MyDef[int]().__class__, MyDef) |
---|
855 | n/a | self.assertIs(MyDef[int]().__orig_class__, MyDef[int]) |
---|
856 | n/a | |
---|
857 | n/a | def test_all_repr_eq_any(self): |
---|
858 | n/a | objs = (getattr(typing, el) for el in typing.__all__) |
---|
859 | n/a | for obj in objs: |
---|
860 | n/a | self.assertNotEqual(repr(obj), '') |
---|
861 | n/a | self.assertEqual(obj, obj) |
---|
862 | n/a | if getattr(obj, '__parameters__', None) and len(obj.__parameters__) == 1: |
---|
863 | n/a | self.assertEqual(obj[Any].__args__, (Any,)) |
---|
864 | n/a | if isinstance(obj, type): |
---|
865 | n/a | for base in obj.__mro__: |
---|
866 | n/a | self.assertNotEqual(repr(base), '') |
---|
867 | n/a | self.assertEqual(base, base) |
---|
868 | n/a | |
---|
869 | n/a | def test_substitution_helper(self): |
---|
870 | n/a | T = TypeVar('T') |
---|
871 | n/a | KT = TypeVar('KT') |
---|
872 | n/a | VT = TypeVar('VT') |
---|
873 | n/a | class Map(Generic[KT, VT]): |
---|
874 | n/a | def meth(self, k: KT, v: VT): ... |
---|
875 | n/a | StrMap = Map[str, T] |
---|
876 | n/a | obj = StrMap[int]() |
---|
877 | n/a | |
---|
878 | n/a | new_args = typing._subs_tree(obj.__orig_class__) |
---|
879 | n/a | new_annots = {k: typing._replace_arg(v, type(obj).__parameters__, new_args) |
---|
880 | n/a | for k, v in obj.meth.__annotations__.items()} |
---|
881 | n/a | |
---|
882 | n/a | self.assertEqual(new_annots, {'k': str, 'v': int}) |
---|
883 | n/a | |
---|
884 | n/a | def test_pickle(self): |
---|
885 | n/a | global C # pickle wants to reference the class by name |
---|
886 | n/a | T = TypeVar('T') |
---|
887 | n/a | |
---|
888 | n/a | class B(Generic[T]): |
---|
889 | n/a | pass |
---|
890 | n/a | |
---|
891 | n/a | class C(B[int]): |
---|
892 | n/a | pass |
---|
893 | n/a | |
---|
894 | n/a | c = C() |
---|
895 | n/a | c.foo = 42 |
---|
896 | n/a | c.bar = 'abc' |
---|
897 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
898 | n/a | z = pickle.dumps(c, proto) |
---|
899 | n/a | x = pickle.loads(z) |
---|
900 | n/a | self.assertEqual(x.foo, 42) |
---|
901 | n/a | self.assertEqual(x.bar, 'abc') |
---|
902 | n/a | self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'}) |
---|
903 | n/a | simples = [Any, Union, Tuple, Callable, ClassVar, List, typing.Iterable] |
---|
904 | n/a | for s in simples: |
---|
905 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
906 | n/a | z = pickle.dumps(s, proto) |
---|
907 | n/a | x = pickle.loads(z) |
---|
908 | n/a | self.assertEqual(s, x) |
---|
909 | n/a | |
---|
910 | n/a | def test_copy_and_deepcopy(self): |
---|
911 | n/a | T = TypeVar('T') |
---|
912 | n/a | class Node(Generic[T]): ... |
---|
913 | n/a | things = [Union[T, int], Tuple[T, int], Callable[..., T], Callable[[int], int], |
---|
914 | n/a | Tuple[Any, Any], Node[T], Node[int], Node[Any], typing.Iterable[T], |
---|
915 | n/a | typing.Iterable[Any], typing.Iterable[int], typing.Dict[int, str], |
---|
916 | n/a | typing.Dict[T, Any], ClassVar[int], ClassVar[List[T]], Tuple['T', 'T'], |
---|
917 | n/a | Union['T', int], List['T'], typing.Mapping['T', int]] |
---|
918 | n/a | for t in things + [Any]: |
---|
919 | n/a | self.assertEqual(t, copy(t)) |
---|
920 | n/a | self.assertEqual(t, deepcopy(t)) |
---|
921 | n/a | |
---|
922 | n/a | def test_weakref_all(self): |
---|
923 | n/a | T = TypeVar('T') |
---|
924 | n/a | things = [Any, Union[T, int], Callable[..., T], Tuple[Any, Any], |
---|
925 | n/a | Optional[List[int]], typing.Mapping[int, str], |
---|
926 | n/a | typing.re.Match[bytes], typing.Iterable['whatever']] |
---|
927 | n/a | for t in things: |
---|
928 | n/a | self.assertEqual(weakref.ref(t)(), t) |
---|
929 | n/a | |
---|
930 | n/a | def test_parameterized_slots(self): |
---|
931 | n/a | T = TypeVar('T') |
---|
932 | n/a | class C(Generic[T]): |
---|
933 | n/a | __slots__ = ('potato',) |
---|
934 | n/a | |
---|
935 | n/a | c = C() |
---|
936 | n/a | c_int = C[int]() |
---|
937 | n/a | self.assertEqual(C.__slots__, C[str].__slots__) |
---|
938 | n/a | |
---|
939 | n/a | c.potato = 0 |
---|
940 | n/a | c_int.potato = 0 |
---|
941 | n/a | with self.assertRaises(AttributeError): |
---|
942 | n/a | c.tomato = 0 |
---|
943 | n/a | with self.assertRaises(AttributeError): |
---|
944 | n/a | c_int.tomato = 0 |
---|
945 | n/a | |
---|
946 | n/a | def foo(x: C['C']): ... |
---|
947 | n/a | self.assertEqual(get_type_hints(foo, globals(), locals())['x'], C[C]) |
---|
948 | n/a | self.assertEqual(get_type_hints(foo, globals(), locals())['x'].__slots__, |
---|
949 | n/a | C.__slots__) |
---|
950 | n/a | self.assertEqual(copy(C[int]), deepcopy(C[int])) |
---|
951 | n/a | |
---|
952 | n/a | def test_parameterized_slots_dict(self): |
---|
953 | n/a | T = TypeVar('T') |
---|
954 | n/a | class D(Generic[T]): |
---|
955 | n/a | __slots__ = {'banana': 42} |
---|
956 | n/a | |
---|
957 | n/a | d = D() |
---|
958 | n/a | d_int = D[int]() |
---|
959 | n/a | self.assertEqual(D.__slots__, D[str].__slots__) |
---|
960 | n/a | |
---|
961 | n/a | d.banana = 'yes' |
---|
962 | n/a | d_int.banana = 'yes' |
---|
963 | n/a | with self.assertRaises(AttributeError): |
---|
964 | n/a | d.foobar = 'no' |
---|
965 | n/a | with self.assertRaises(AttributeError): |
---|
966 | n/a | d_int.foobar = 'no' |
---|
967 | n/a | |
---|
968 | n/a | def test_errors(self): |
---|
969 | n/a | with self.assertRaises(TypeError): |
---|
970 | n/a | B = SimpleMapping[XK, Any] |
---|
971 | n/a | |
---|
972 | n/a | class C(Generic[B]): |
---|
973 | n/a | pass |
---|
974 | n/a | |
---|
975 | n/a | def test_repr_2(self): |
---|
976 | n/a | PY32 = sys.version_info[:2] < (3, 3) |
---|
977 | n/a | |
---|
978 | n/a | class C(Generic[T]): |
---|
979 | n/a | pass |
---|
980 | n/a | |
---|
981 | n/a | self.assertEqual(C.__module__, __name__) |
---|
982 | n/a | if not PY32: |
---|
983 | n/a | self.assertEqual(C.__qualname__, |
---|
984 | n/a | 'GenericTests.test_repr_2.<locals>.C') |
---|
985 | n/a | self.assertEqual(repr(C).split('.')[-1], 'C') |
---|
986 | n/a | X = C[int] |
---|
987 | n/a | self.assertEqual(X.__module__, __name__) |
---|
988 | n/a | if not PY32: |
---|
989 | n/a | self.assertTrue(X.__qualname__.endswith('.<locals>.C')) |
---|
990 | n/a | self.assertEqual(repr(X).split('.')[-1], 'C[int]') |
---|
991 | n/a | |
---|
992 | n/a | class Y(C[int]): |
---|
993 | n/a | pass |
---|
994 | n/a | |
---|
995 | n/a | self.assertEqual(Y.__module__, __name__) |
---|
996 | n/a | if not PY32: |
---|
997 | n/a | self.assertEqual(Y.__qualname__, |
---|
998 | n/a | 'GenericTests.test_repr_2.<locals>.Y') |
---|
999 | n/a | self.assertEqual(repr(Y).split('.')[-1], 'Y') |
---|
1000 | n/a | |
---|
1001 | n/a | def test_eq_1(self): |
---|
1002 | n/a | self.assertEqual(Generic, Generic) |
---|
1003 | n/a | self.assertEqual(Generic[T], Generic[T]) |
---|
1004 | n/a | self.assertNotEqual(Generic[KT], Generic[VT]) |
---|
1005 | n/a | |
---|
1006 | n/a | def test_eq_2(self): |
---|
1007 | n/a | |
---|
1008 | n/a | class A(Generic[T]): |
---|
1009 | n/a | pass |
---|
1010 | n/a | |
---|
1011 | n/a | class B(Generic[T]): |
---|
1012 | n/a | pass |
---|
1013 | n/a | |
---|
1014 | n/a | self.assertEqual(A, A) |
---|
1015 | n/a | self.assertNotEqual(A, B) |
---|
1016 | n/a | self.assertEqual(A[T], A[T]) |
---|
1017 | n/a | self.assertNotEqual(A[T], B[T]) |
---|
1018 | n/a | |
---|
1019 | n/a | def test_multiple_inheritance(self): |
---|
1020 | n/a | |
---|
1021 | n/a | class A(Generic[T, VT]): |
---|
1022 | n/a | pass |
---|
1023 | n/a | |
---|
1024 | n/a | class B(Generic[KT, T]): |
---|
1025 | n/a | pass |
---|
1026 | n/a | |
---|
1027 | n/a | class C(A[T, VT], Generic[VT, T, KT], B[KT, T]): |
---|
1028 | n/a | pass |
---|
1029 | n/a | |
---|
1030 | n/a | self.assertEqual(C.__parameters__, (VT, T, KT)) |
---|
1031 | n/a | |
---|
1032 | n/a | def test_nested(self): |
---|
1033 | n/a | |
---|
1034 | n/a | G = Generic |
---|
1035 | n/a | |
---|
1036 | n/a | class Visitor(G[T]): |
---|
1037 | n/a | |
---|
1038 | n/a | a = None |
---|
1039 | n/a | |
---|
1040 | n/a | def set(self, a: T): |
---|
1041 | n/a | self.a = a |
---|
1042 | n/a | |
---|
1043 | n/a | def get(self): |
---|
1044 | n/a | return self.a |
---|
1045 | n/a | |
---|
1046 | n/a | def visit(self) -> T: |
---|
1047 | n/a | return self.a |
---|
1048 | n/a | |
---|
1049 | n/a | V = Visitor[typing.List[int]] |
---|
1050 | n/a | |
---|
1051 | n/a | class IntListVisitor(V): |
---|
1052 | n/a | |
---|
1053 | n/a | def append(self, x: int): |
---|
1054 | n/a | self.a.append(x) |
---|
1055 | n/a | |
---|
1056 | n/a | a = IntListVisitor() |
---|
1057 | n/a | a.set([]) |
---|
1058 | n/a | a.append(1) |
---|
1059 | n/a | a.append(42) |
---|
1060 | n/a | self.assertEqual(a.get(), [1, 42]) |
---|
1061 | n/a | |
---|
1062 | n/a | def test_type_erasure(self): |
---|
1063 | n/a | T = TypeVar('T') |
---|
1064 | n/a | |
---|
1065 | n/a | class Node(Generic[T]): |
---|
1066 | n/a | def __init__(self, label: T, |
---|
1067 | n/a | left: 'Node[T]' = None, |
---|
1068 | n/a | right: 'Node[T]' = None): |
---|
1069 | n/a | self.label = label # type: T |
---|
1070 | n/a | self.left = left # type: Optional[Node[T]] |
---|
1071 | n/a | self.right = right # type: Optional[Node[T]] |
---|
1072 | n/a | |
---|
1073 | n/a | def foo(x: T): |
---|
1074 | n/a | a = Node(x) |
---|
1075 | n/a | b = Node[T](x) |
---|
1076 | n/a | c = Node[Any](x) |
---|
1077 | n/a | self.assertIs(type(a), Node) |
---|
1078 | n/a | self.assertIs(type(b), Node) |
---|
1079 | n/a | self.assertIs(type(c), Node) |
---|
1080 | n/a | self.assertEqual(a.label, x) |
---|
1081 | n/a | self.assertEqual(b.label, x) |
---|
1082 | n/a | self.assertEqual(c.label, x) |
---|
1083 | n/a | |
---|
1084 | n/a | foo(42) |
---|
1085 | n/a | |
---|
1086 | n/a | def test_implicit_any(self): |
---|
1087 | n/a | T = TypeVar('T') |
---|
1088 | n/a | |
---|
1089 | n/a | class C(Generic[T]): |
---|
1090 | n/a | pass |
---|
1091 | n/a | |
---|
1092 | n/a | class D(C): |
---|
1093 | n/a | pass |
---|
1094 | n/a | |
---|
1095 | n/a | self.assertEqual(D.__parameters__, ()) |
---|
1096 | n/a | |
---|
1097 | n/a | with self.assertRaises(Exception): |
---|
1098 | n/a | D[int] |
---|
1099 | n/a | with self.assertRaises(Exception): |
---|
1100 | n/a | D[Any] |
---|
1101 | n/a | with self.assertRaises(Exception): |
---|
1102 | n/a | D[T] |
---|
1103 | n/a | |
---|
1104 | n/a | |
---|
1105 | n/a | class ClassVarTests(BaseTestCase): |
---|
1106 | n/a | |
---|
1107 | n/a | def test_basics(self): |
---|
1108 | n/a | with self.assertRaises(TypeError): |
---|
1109 | n/a | ClassVar[1] |
---|
1110 | n/a | with self.assertRaises(TypeError): |
---|
1111 | n/a | ClassVar[int, str] |
---|
1112 | n/a | with self.assertRaises(TypeError): |
---|
1113 | n/a | ClassVar[int][str] |
---|
1114 | n/a | |
---|
1115 | n/a | def test_repr(self): |
---|
1116 | n/a | self.assertEqual(repr(ClassVar), 'typing.ClassVar') |
---|
1117 | n/a | cv = ClassVar[int] |
---|
1118 | n/a | self.assertEqual(repr(cv), 'typing.ClassVar[int]') |
---|
1119 | n/a | cv = ClassVar[Employee] |
---|
1120 | n/a | self.assertEqual(repr(cv), 'typing.ClassVar[%s.Employee]' % __name__) |
---|
1121 | n/a | |
---|
1122 | n/a | def test_cannot_subclass(self): |
---|
1123 | n/a | with self.assertRaises(TypeError): |
---|
1124 | n/a | class C(type(ClassVar)): |
---|
1125 | n/a | pass |
---|
1126 | n/a | with self.assertRaises(TypeError): |
---|
1127 | n/a | class C(type(ClassVar[int])): |
---|
1128 | n/a | pass |
---|
1129 | n/a | |
---|
1130 | n/a | def test_cannot_init(self): |
---|
1131 | n/a | with self.assertRaises(TypeError): |
---|
1132 | n/a | ClassVar() |
---|
1133 | n/a | with self.assertRaises(TypeError): |
---|
1134 | n/a | type(ClassVar)() |
---|
1135 | n/a | with self.assertRaises(TypeError): |
---|
1136 | n/a | type(ClassVar[Optional[int]])() |
---|
1137 | n/a | |
---|
1138 | n/a | def test_no_isinstance(self): |
---|
1139 | n/a | with self.assertRaises(TypeError): |
---|
1140 | n/a | isinstance(1, ClassVar[int]) |
---|
1141 | n/a | with self.assertRaises(TypeError): |
---|
1142 | n/a | issubclass(int, ClassVar) |
---|
1143 | n/a | |
---|
1144 | n/a | |
---|
1145 | n/a | class CastTests(BaseTestCase): |
---|
1146 | n/a | |
---|
1147 | n/a | def test_basics(self): |
---|
1148 | n/a | self.assertEqual(cast(int, 42), 42) |
---|
1149 | n/a | self.assertEqual(cast(float, 42), 42) |
---|
1150 | n/a | self.assertIs(type(cast(float, 42)), int) |
---|
1151 | n/a | self.assertEqual(cast(Any, 42), 42) |
---|
1152 | n/a | self.assertEqual(cast(list, 42), 42) |
---|
1153 | n/a | self.assertEqual(cast(Union[str, float], 42), 42) |
---|
1154 | n/a | self.assertEqual(cast(AnyStr, 42), 42) |
---|
1155 | n/a | self.assertEqual(cast(None, 42), 42) |
---|
1156 | n/a | |
---|
1157 | n/a | def test_errors(self): |
---|
1158 | n/a | # Bogus calls are not expected to fail. |
---|
1159 | n/a | cast(42, 42) |
---|
1160 | n/a | cast('hello', 42) |
---|
1161 | n/a | |
---|
1162 | n/a | |
---|
1163 | n/a | class ForwardRefTests(BaseTestCase): |
---|
1164 | n/a | |
---|
1165 | n/a | def test_basics(self): |
---|
1166 | n/a | |
---|
1167 | n/a | class Node(Generic[T]): |
---|
1168 | n/a | |
---|
1169 | n/a | def __init__(self, label: T): |
---|
1170 | n/a | self.label = label |
---|
1171 | n/a | self.left = self.right = None |
---|
1172 | n/a | |
---|
1173 | n/a | def add_both(self, |
---|
1174 | n/a | left: 'Optional[Node[T]]', |
---|
1175 | n/a | right: 'Node[T]' = None, |
---|
1176 | n/a | stuff: int = None, |
---|
1177 | n/a | blah=None): |
---|
1178 | n/a | self.left = left |
---|
1179 | n/a | self.right = right |
---|
1180 | n/a | |
---|
1181 | n/a | def add_left(self, node: Optional['Node[T]']): |
---|
1182 | n/a | self.add_both(node, None) |
---|
1183 | n/a | |
---|
1184 | n/a | def add_right(self, node: 'Node[T]' = None): |
---|
1185 | n/a | self.add_both(None, node) |
---|
1186 | n/a | |
---|
1187 | n/a | t = Node[int] |
---|
1188 | n/a | both_hints = get_type_hints(t.add_both, globals(), locals()) |
---|
1189 | n/a | self.assertEqual(both_hints['left'], Optional[Node[T]]) |
---|
1190 | n/a | self.assertEqual(both_hints['right'], Optional[Node[T]]) |
---|
1191 | n/a | self.assertEqual(both_hints['left'], both_hints['right']) |
---|
1192 | n/a | self.assertEqual(both_hints['stuff'], Optional[int]) |
---|
1193 | n/a | self.assertNotIn('blah', both_hints) |
---|
1194 | n/a | |
---|
1195 | n/a | left_hints = get_type_hints(t.add_left, globals(), locals()) |
---|
1196 | n/a | self.assertEqual(left_hints['node'], Optional[Node[T]]) |
---|
1197 | n/a | |
---|
1198 | n/a | right_hints = get_type_hints(t.add_right, globals(), locals()) |
---|
1199 | n/a | self.assertEqual(right_hints['node'], Optional[Node[T]]) |
---|
1200 | n/a | |
---|
1201 | n/a | def test_forwardref_instance_type_error(self): |
---|
1202 | n/a | fr = typing._ForwardRef('int') |
---|
1203 | n/a | with self.assertRaises(TypeError): |
---|
1204 | n/a | isinstance(42, fr) |
---|
1205 | n/a | |
---|
1206 | n/a | def test_union_forward(self): |
---|
1207 | n/a | |
---|
1208 | n/a | def foo(a: Union['T']): |
---|
1209 | n/a | pass |
---|
1210 | n/a | |
---|
1211 | n/a | self.assertEqual(get_type_hints(foo, globals(), locals()), |
---|
1212 | n/a | {'a': Union[T]}) |
---|
1213 | n/a | |
---|
1214 | n/a | def test_tuple_forward(self): |
---|
1215 | n/a | |
---|
1216 | n/a | def foo(a: Tuple['T']): |
---|
1217 | n/a | pass |
---|
1218 | n/a | |
---|
1219 | n/a | self.assertEqual(get_type_hints(foo, globals(), locals()), |
---|
1220 | n/a | {'a': Tuple[T]}) |
---|
1221 | n/a | |
---|
1222 | n/a | def test_callable_forward(self): |
---|
1223 | n/a | |
---|
1224 | n/a | def foo(a: Callable[['T'], 'T']): |
---|
1225 | n/a | pass |
---|
1226 | n/a | |
---|
1227 | n/a | self.assertEqual(get_type_hints(foo, globals(), locals()), |
---|
1228 | n/a | {'a': Callable[[T], T]}) |
---|
1229 | n/a | |
---|
1230 | n/a | def test_callable_with_ellipsis_forward(self): |
---|
1231 | n/a | |
---|
1232 | n/a | def foo(a: 'Callable[..., T]'): |
---|
1233 | n/a | pass |
---|
1234 | n/a | |
---|
1235 | n/a | self.assertEqual(get_type_hints(foo, globals(), locals()), |
---|
1236 | n/a | {'a': Callable[..., T]}) |
---|
1237 | n/a | |
---|
1238 | n/a | def test_syntax_error(self): |
---|
1239 | n/a | |
---|
1240 | n/a | with self.assertRaises(SyntaxError): |
---|
1241 | n/a | Generic['/T'] |
---|
1242 | n/a | |
---|
1243 | n/a | def test_delayed_syntax_error(self): |
---|
1244 | n/a | |
---|
1245 | n/a | def foo(a: 'Node[T'): |
---|
1246 | n/a | pass |
---|
1247 | n/a | |
---|
1248 | n/a | with self.assertRaises(SyntaxError): |
---|
1249 | n/a | get_type_hints(foo) |
---|
1250 | n/a | |
---|
1251 | n/a | def test_type_error(self): |
---|
1252 | n/a | |
---|
1253 | n/a | def foo(a: Tuple['42']): |
---|
1254 | n/a | pass |
---|
1255 | n/a | |
---|
1256 | n/a | with self.assertRaises(TypeError): |
---|
1257 | n/a | get_type_hints(foo) |
---|
1258 | n/a | |
---|
1259 | n/a | def test_name_error(self): |
---|
1260 | n/a | |
---|
1261 | n/a | def foo(a: 'Noode[T]'): |
---|
1262 | n/a | pass |
---|
1263 | n/a | |
---|
1264 | n/a | with self.assertRaises(NameError): |
---|
1265 | n/a | get_type_hints(foo, locals()) |
---|
1266 | n/a | |
---|
1267 | n/a | def test_no_type_check(self): |
---|
1268 | n/a | |
---|
1269 | n/a | @no_type_check |
---|
1270 | n/a | def foo(a: 'whatevers') -> {}: |
---|
1271 | n/a | pass |
---|
1272 | n/a | |
---|
1273 | n/a | th = get_type_hints(foo) |
---|
1274 | n/a | self.assertEqual(th, {}) |
---|
1275 | n/a | |
---|
1276 | n/a | def test_no_type_check_class(self): |
---|
1277 | n/a | |
---|
1278 | n/a | @no_type_check |
---|
1279 | n/a | class C: |
---|
1280 | n/a | def foo(a: 'whatevers') -> {}: |
---|
1281 | n/a | pass |
---|
1282 | n/a | |
---|
1283 | n/a | cth = get_type_hints(C.foo) |
---|
1284 | n/a | self.assertEqual(cth, {}) |
---|
1285 | n/a | ith = get_type_hints(C().foo) |
---|
1286 | n/a | self.assertEqual(ith, {}) |
---|
1287 | n/a | |
---|
1288 | n/a | def test_meta_no_type_check(self): |
---|
1289 | n/a | |
---|
1290 | n/a | @no_type_check_decorator |
---|
1291 | n/a | def magic_decorator(deco): |
---|
1292 | n/a | return deco |
---|
1293 | n/a | |
---|
1294 | n/a | self.assertEqual(magic_decorator.__name__, 'magic_decorator') |
---|
1295 | n/a | |
---|
1296 | n/a | @magic_decorator |
---|
1297 | n/a | def foo(a: 'whatevers') -> {}: |
---|
1298 | n/a | pass |
---|
1299 | n/a | |
---|
1300 | n/a | @magic_decorator |
---|
1301 | n/a | class C: |
---|
1302 | n/a | def foo(a: 'whatevers') -> {}: |
---|
1303 | n/a | pass |
---|
1304 | n/a | |
---|
1305 | n/a | self.assertEqual(foo.__name__, 'foo') |
---|
1306 | n/a | th = get_type_hints(foo) |
---|
1307 | n/a | self.assertEqual(th, {}) |
---|
1308 | n/a | cth = get_type_hints(C.foo) |
---|
1309 | n/a | self.assertEqual(cth, {}) |
---|
1310 | n/a | ith = get_type_hints(C().foo) |
---|
1311 | n/a | self.assertEqual(ith, {}) |
---|
1312 | n/a | |
---|
1313 | n/a | def test_default_globals(self): |
---|
1314 | n/a | code = ("class C:\n" |
---|
1315 | n/a | " def foo(self, a: 'C') -> 'D': pass\n" |
---|
1316 | n/a | "class D:\n" |
---|
1317 | n/a | " def bar(self, b: 'D') -> C: pass\n" |
---|
1318 | n/a | ) |
---|
1319 | n/a | ns = {} |
---|
1320 | n/a | exec(code, ns) |
---|
1321 | n/a | hints = get_type_hints(ns['C'].foo) |
---|
1322 | n/a | self.assertEqual(hints, {'a': ns['C'], 'return': ns['D']}) |
---|
1323 | n/a | |
---|
1324 | n/a | |
---|
1325 | n/a | class OverloadTests(BaseTestCase): |
---|
1326 | n/a | |
---|
1327 | n/a | def test_overload_fails(self): |
---|
1328 | n/a | from typing import overload |
---|
1329 | n/a | |
---|
1330 | n/a | with self.assertRaises(RuntimeError): |
---|
1331 | n/a | |
---|
1332 | n/a | @overload |
---|
1333 | n/a | def blah(): |
---|
1334 | n/a | pass |
---|
1335 | n/a | |
---|
1336 | n/a | blah() |
---|
1337 | n/a | |
---|
1338 | n/a | def test_overload_succeeds(self): |
---|
1339 | n/a | from typing import overload |
---|
1340 | n/a | |
---|
1341 | n/a | @overload |
---|
1342 | n/a | def blah(): |
---|
1343 | n/a | pass |
---|
1344 | n/a | |
---|
1345 | n/a | def blah(): |
---|
1346 | n/a | pass |
---|
1347 | n/a | |
---|
1348 | n/a | blah() |
---|
1349 | n/a | |
---|
1350 | n/a | |
---|
1351 | n/a | ASYNCIO = sys.version_info[:2] >= (3, 5) |
---|
1352 | n/a | |
---|
1353 | n/a | ASYNCIO_TESTS = """ |
---|
1354 | n/a | import asyncio |
---|
1355 | n/a | |
---|
1356 | n/a | T_a = TypeVar('T_a') |
---|
1357 | n/a | |
---|
1358 | n/a | class AwaitableWrapper(typing.Awaitable[T_a]): |
---|
1359 | n/a | |
---|
1360 | n/a | def __init__(self, value): |
---|
1361 | n/a | self.value = value |
---|
1362 | n/a | |
---|
1363 | n/a | def __await__(self) -> typing.Iterator[T_a]: |
---|
1364 | n/a | yield |
---|
1365 | n/a | return self.value |
---|
1366 | n/a | |
---|
1367 | n/a | class AsyncIteratorWrapper(typing.AsyncIterator[T_a]): |
---|
1368 | n/a | |
---|
1369 | n/a | def __init__(self, value: typing.Iterable[T_a]): |
---|
1370 | n/a | self.value = value |
---|
1371 | n/a | |
---|
1372 | n/a | def __aiter__(self) -> typing.AsyncIterator[T_a]: |
---|
1373 | n/a | return self |
---|
1374 | n/a | |
---|
1375 | n/a | @asyncio.coroutine |
---|
1376 | n/a | def __anext__(self) -> T_a: |
---|
1377 | n/a | data = yield from self.value |
---|
1378 | n/a | if data: |
---|
1379 | n/a | return data |
---|
1380 | n/a | else: |
---|
1381 | n/a | raise StopAsyncIteration |
---|
1382 | n/a | """ |
---|
1383 | n/a | |
---|
1384 | n/a | if ASYNCIO: |
---|
1385 | n/a | try: |
---|
1386 | n/a | exec(ASYNCIO_TESTS) |
---|
1387 | n/a | except ImportError: |
---|
1388 | n/a | ASYNCIO = False |
---|
1389 | n/a | else: |
---|
1390 | n/a | # fake names for the sake of static analysis |
---|
1391 | n/a | asyncio = None |
---|
1392 | n/a | AwaitableWrapper = AsyncIteratorWrapper = object |
---|
1393 | n/a | |
---|
1394 | n/a | PY36 = sys.version_info[:2] >= (3, 6) |
---|
1395 | n/a | |
---|
1396 | n/a | PY36_TESTS = """ |
---|
1397 | n/a | from test import ann_module, ann_module2, ann_module3 |
---|
1398 | n/a | |
---|
1399 | n/a | class A: |
---|
1400 | n/a | y: float |
---|
1401 | n/a | class B(A): |
---|
1402 | n/a | x: ClassVar[Optional['B']] = None |
---|
1403 | n/a | y: int |
---|
1404 | n/a | class CSub(B): |
---|
1405 | n/a | z: ClassVar['CSub'] = B() |
---|
1406 | n/a | class G(Generic[T]): |
---|
1407 | n/a | lst: ClassVar[List[T]] = [] |
---|
1408 | n/a | |
---|
1409 | n/a | class CoolEmployee(NamedTuple): |
---|
1410 | n/a | name: str |
---|
1411 | n/a | cool: int |
---|
1412 | n/a | |
---|
1413 | n/a | class CoolEmployeeWithDefault(NamedTuple): |
---|
1414 | n/a | name: str |
---|
1415 | n/a | cool: int = 0 |
---|
1416 | n/a | |
---|
1417 | n/a | class XMeth(NamedTuple): |
---|
1418 | n/a | x: int |
---|
1419 | n/a | def double(self): |
---|
1420 | n/a | return 2 * self.x |
---|
1421 | n/a | |
---|
1422 | n/a | class XMethBad(NamedTuple): |
---|
1423 | n/a | x: int |
---|
1424 | n/a | def _fields(self): |
---|
1425 | n/a | return 'no chance for this' |
---|
1426 | n/a | """ |
---|
1427 | n/a | |
---|
1428 | n/a | if PY36: |
---|
1429 | n/a | exec(PY36_TESTS) |
---|
1430 | n/a | else: |
---|
1431 | n/a | # fake names for the sake of static analysis |
---|
1432 | n/a | ann_module = ann_module2 = ann_module3 = None |
---|
1433 | n/a | A = B = CSub = G = CoolEmployee = CoolEmployeeWithDefault = object |
---|
1434 | n/a | XMeth = XMethBad = object |
---|
1435 | n/a | |
---|
1436 | n/a | gth = get_type_hints |
---|
1437 | n/a | |
---|
1438 | n/a | |
---|
1439 | n/a | class GetTypeHintTests(BaseTestCase): |
---|
1440 | n/a | def test_get_type_hints_from_various_objects(self): |
---|
1441 | n/a | # For invalid objects should fail with TypeError (not AttributeError etc). |
---|
1442 | n/a | with self.assertRaises(TypeError): |
---|
1443 | n/a | gth(123) |
---|
1444 | n/a | with self.assertRaises(TypeError): |
---|
1445 | n/a | gth('abc') |
---|
1446 | n/a | with self.assertRaises(TypeError): |
---|
1447 | n/a | gth(None) |
---|
1448 | n/a | |
---|
1449 | n/a | @skipUnless(PY36, 'Python 3.6 required') |
---|
1450 | n/a | def test_get_type_hints_modules(self): |
---|
1451 | n/a | ann_module_type_hints = {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str} |
---|
1452 | n/a | self.assertEqual(gth(ann_module), ann_module_type_hints) |
---|
1453 | n/a | self.assertEqual(gth(ann_module2), {}) |
---|
1454 | n/a | self.assertEqual(gth(ann_module3), {}) |
---|
1455 | n/a | |
---|
1456 | n/a | @skipUnless(PY36, 'Python 3.6 required') |
---|
1457 | n/a | def test_get_type_hints_classes(self): |
---|
1458 | n/a | self.assertEqual(gth(ann_module.C, ann_module.__dict__), |
---|
1459 | n/a | {'y': Optional[ann_module.C]}) |
---|
1460 | n/a | self.assertIsInstance(gth(ann_module.j_class), dict) |
---|
1461 | n/a | self.assertEqual(gth(ann_module.M), {'123': 123, 'o': type}) |
---|
1462 | n/a | self.assertEqual(gth(ann_module.D), |
---|
1463 | n/a | {'j': str, 'k': str, 'y': Optional[ann_module.C]}) |
---|
1464 | n/a | self.assertEqual(gth(ann_module.Y), {'z': int}) |
---|
1465 | n/a | self.assertEqual(gth(ann_module.h_class), |
---|
1466 | n/a | {'y': Optional[ann_module.C]}) |
---|
1467 | n/a | self.assertEqual(gth(ann_module.S), {'x': str, 'y': str}) |
---|
1468 | n/a | self.assertEqual(gth(ann_module.foo), {'x': int}) |
---|
1469 | n/a | |
---|
1470 | n/a | @skipUnless(PY36, 'Python 3.6 required') |
---|
1471 | n/a | def test_respect_no_type_check(self): |
---|
1472 | n/a | @no_type_check |
---|
1473 | n/a | class NoTpCheck: |
---|
1474 | n/a | class Inn: |
---|
1475 | n/a | def __init__(self, x: 'not a type'): ... |
---|
1476 | n/a | self.assertTrue(NoTpCheck.__no_type_check__) |
---|
1477 | n/a | self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__) |
---|
1478 | n/a | self.assertEqual(gth(ann_module2.NTC.meth), {}) |
---|
1479 | n/a | class ABase(Generic[T]): |
---|
1480 | n/a | def meth(x: int): ... |
---|
1481 | n/a | @no_type_check |
---|
1482 | n/a | class Der(ABase): ... |
---|
1483 | n/a | self.assertEqual(gth(ABase.meth), {'x': int}) |
---|
1484 | n/a | |
---|
1485 | n/a | def test_get_type_hints_for_builins(self): |
---|
1486 | n/a | # Should not fail for built-in classes and functions. |
---|
1487 | n/a | self.assertEqual(gth(int), {}) |
---|
1488 | n/a | self.assertEqual(gth(type), {}) |
---|
1489 | n/a | self.assertEqual(gth(dir), {}) |
---|
1490 | n/a | self.assertEqual(gth(len), {}) |
---|
1491 | n/a | |
---|
1492 | n/a | def test_previous_behavior(self): |
---|
1493 | n/a | def testf(x, y): ... |
---|
1494 | n/a | testf.__annotations__['x'] = 'int' |
---|
1495 | n/a | self.assertEqual(gth(testf), {'x': int}) |
---|
1496 | n/a | |
---|
1497 | n/a | def test_get_type_hints_for_object_with_annotations(self): |
---|
1498 | n/a | class A: ... |
---|
1499 | n/a | class B: ... |
---|
1500 | n/a | b = B() |
---|
1501 | n/a | b.__annotations__ = {'x': 'A'} |
---|
1502 | n/a | self.assertEqual(gth(b, locals()), {'x': A}) |
---|
1503 | n/a | |
---|
1504 | n/a | @skipUnless(PY36, 'Python 3.6 required') |
---|
1505 | n/a | def test_get_type_hints_ClassVar(self): |
---|
1506 | n/a | self.assertEqual(gth(ann_module2.CV, ann_module2.__dict__), |
---|
1507 | n/a | {'var': typing.ClassVar[ann_module2.CV]}) |
---|
1508 | n/a | self.assertEqual(gth(B, globals()), |
---|
1509 | n/a | {'y': int, 'x': ClassVar[Optional[B]]}) |
---|
1510 | n/a | self.assertEqual(gth(CSub, globals()), |
---|
1511 | n/a | {'z': ClassVar[CSub], 'y': int, 'x': ClassVar[Optional[B]]}) |
---|
1512 | n/a | self.assertEqual(gth(G), {'lst': ClassVar[List[T]]}) |
---|
1513 | n/a | |
---|
1514 | n/a | |
---|
1515 | n/a | class CollectionsAbcTests(BaseTestCase): |
---|
1516 | n/a | |
---|
1517 | n/a | def test_hashable(self): |
---|
1518 | n/a | self.assertIsInstance(42, typing.Hashable) |
---|
1519 | n/a | self.assertNotIsInstance([], typing.Hashable) |
---|
1520 | n/a | |
---|
1521 | n/a | def test_iterable(self): |
---|
1522 | n/a | self.assertIsInstance([], typing.Iterable) |
---|
1523 | n/a | # Due to ABC caching, the second time takes a separate code |
---|
1524 | n/a | # path and could fail. So call this a few times. |
---|
1525 | n/a | self.assertIsInstance([], typing.Iterable) |
---|
1526 | n/a | self.assertIsInstance([], typing.Iterable) |
---|
1527 | n/a | self.assertNotIsInstance(42, typing.Iterable) |
---|
1528 | n/a | # Just in case, also test issubclass() a few times. |
---|
1529 | n/a | self.assertIsSubclass(list, typing.Iterable) |
---|
1530 | n/a | self.assertIsSubclass(list, typing.Iterable) |
---|
1531 | n/a | |
---|
1532 | n/a | def test_iterator(self): |
---|
1533 | n/a | it = iter([]) |
---|
1534 | n/a | self.assertIsInstance(it, typing.Iterator) |
---|
1535 | n/a | self.assertNotIsInstance(42, typing.Iterator) |
---|
1536 | n/a | |
---|
1537 | n/a | @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') |
---|
1538 | n/a | def test_awaitable(self): |
---|
1539 | n/a | ns = {} |
---|
1540 | n/a | exec( |
---|
1541 | n/a | "async def foo() -> typing.Awaitable[int]:\n" |
---|
1542 | n/a | " return await AwaitableWrapper(42)\n", |
---|
1543 | n/a | globals(), ns) |
---|
1544 | n/a | foo = ns['foo'] |
---|
1545 | n/a | g = foo() |
---|
1546 | n/a | self.assertIsInstance(g, typing.Awaitable) |
---|
1547 | n/a | self.assertNotIsInstance(foo, typing.Awaitable) |
---|
1548 | n/a | g.send(None) # Run foo() till completion, to avoid warning. |
---|
1549 | n/a | |
---|
1550 | n/a | @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') |
---|
1551 | n/a | def test_coroutine(self): |
---|
1552 | n/a | ns = {} |
---|
1553 | n/a | exec( |
---|
1554 | n/a | "async def foo():\n" |
---|
1555 | n/a | " return\n", |
---|
1556 | n/a | globals(), ns) |
---|
1557 | n/a | foo = ns['foo'] |
---|
1558 | n/a | g = foo() |
---|
1559 | n/a | self.assertIsInstance(g, typing.Coroutine) |
---|
1560 | n/a | with self.assertRaises(TypeError): |
---|
1561 | n/a | isinstance(g, typing.Coroutine[int]) |
---|
1562 | n/a | self.assertNotIsInstance(foo, typing.Coroutine) |
---|
1563 | n/a | try: |
---|
1564 | n/a | g.send(None) |
---|
1565 | n/a | except StopIteration: |
---|
1566 | n/a | pass |
---|
1567 | n/a | |
---|
1568 | n/a | @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') |
---|
1569 | n/a | def test_async_iterable(self): |
---|
1570 | n/a | base_it = range(10) # type: Iterator[int] |
---|
1571 | n/a | it = AsyncIteratorWrapper(base_it) |
---|
1572 | n/a | self.assertIsInstance(it, typing.AsyncIterable) |
---|
1573 | n/a | self.assertIsInstance(it, typing.AsyncIterable) |
---|
1574 | n/a | self.assertNotIsInstance(42, typing.AsyncIterable) |
---|
1575 | n/a | |
---|
1576 | n/a | @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') |
---|
1577 | n/a | def test_async_iterator(self): |
---|
1578 | n/a | base_it = range(10) # type: Iterator[int] |
---|
1579 | n/a | it = AsyncIteratorWrapper(base_it) |
---|
1580 | n/a | self.assertIsInstance(it, typing.AsyncIterator) |
---|
1581 | n/a | self.assertNotIsInstance(42, typing.AsyncIterator) |
---|
1582 | n/a | |
---|
1583 | n/a | def test_sized(self): |
---|
1584 | n/a | self.assertIsInstance([], typing.Sized) |
---|
1585 | n/a | self.assertNotIsInstance(42, typing.Sized) |
---|
1586 | n/a | |
---|
1587 | n/a | def test_container(self): |
---|
1588 | n/a | self.assertIsInstance([], typing.Container) |
---|
1589 | n/a | self.assertNotIsInstance(42, typing.Container) |
---|
1590 | n/a | |
---|
1591 | n/a | def test_collection(self): |
---|
1592 | n/a | if hasattr(typing, 'Collection'): |
---|
1593 | n/a | self.assertIsInstance(tuple(), typing.Collection) |
---|
1594 | n/a | self.assertIsInstance(frozenset(), typing.Collection) |
---|
1595 | n/a | self.assertIsSubclass(dict, typing.Collection) |
---|
1596 | n/a | self.assertNotIsInstance(42, typing.Collection) |
---|
1597 | n/a | |
---|
1598 | n/a | def test_abstractset(self): |
---|
1599 | n/a | self.assertIsInstance(set(), typing.AbstractSet) |
---|
1600 | n/a | self.assertNotIsInstance(42, typing.AbstractSet) |
---|
1601 | n/a | |
---|
1602 | n/a | def test_mutableset(self): |
---|
1603 | n/a | self.assertIsInstance(set(), typing.MutableSet) |
---|
1604 | n/a | self.assertNotIsInstance(frozenset(), typing.MutableSet) |
---|
1605 | n/a | |
---|
1606 | n/a | def test_mapping(self): |
---|
1607 | n/a | self.assertIsInstance({}, typing.Mapping) |
---|
1608 | n/a | self.assertNotIsInstance(42, typing.Mapping) |
---|
1609 | n/a | |
---|
1610 | n/a | def test_mutablemapping(self): |
---|
1611 | n/a | self.assertIsInstance({}, typing.MutableMapping) |
---|
1612 | n/a | self.assertNotIsInstance(42, typing.MutableMapping) |
---|
1613 | n/a | |
---|
1614 | n/a | def test_sequence(self): |
---|
1615 | n/a | self.assertIsInstance([], typing.Sequence) |
---|
1616 | n/a | self.assertNotIsInstance(42, typing.Sequence) |
---|
1617 | n/a | |
---|
1618 | n/a | def test_mutablesequence(self): |
---|
1619 | n/a | self.assertIsInstance([], typing.MutableSequence) |
---|
1620 | n/a | self.assertNotIsInstance((), typing.MutableSequence) |
---|
1621 | n/a | |
---|
1622 | n/a | def test_bytestring(self): |
---|
1623 | n/a | self.assertIsInstance(b'', typing.ByteString) |
---|
1624 | n/a | self.assertIsInstance(bytearray(b''), typing.ByteString) |
---|
1625 | n/a | |
---|
1626 | n/a | def test_list(self): |
---|
1627 | n/a | self.assertIsSubclass(list, typing.List) |
---|
1628 | n/a | |
---|
1629 | n/a | def test_deque(self): |
---|
1630 | n/a | self.assertIsSubclass(collections.deque, typing.Deque) |
---|
1631 | n/a | |
---|
1632 | n/a | def test_set(self): |
---|
1633 | n/a | self.assertIsSubclass(set, typing.Set) |
---|
1634 | n/a | self.assertNotIsSubclass(frozenset, typing.Set) |
---|
1635 | n/a | |
---|
1636 | n/a | def test_frozenset(self): |
---|
1637 | n/a | self.assertIsSubclass(frozenset, typing.FrozenSet) |
---|
1638 | n/a | self.assertNotIsSubclass(set, typing.FrozenSet) |
---|
1639 | n/a | |
---|
1640 | n/a | def test_dict(self): |
---|
1641 | n/a | self.assertIsSubclass(dict, typing.Dict) |
---|
1642 | n/a | |
---|
1643 | n/a | def test_no_list_instantiation(self): |
---|
1644 | n/a | with self.assertRaises(TypeError): |
---|
1645 | n/a | typing.List() |
---|
1646 | n/a | with self.assertRaises(TypeError): |
---|
1647 | n/a | typing.List[T]() |
---|
1648 | n/a | with self.assertRaises(TypeError): |
---|
1649 | n/a | typing.List[int]() |
---|
1650 | n/a | |
---|
1651 | n/a | def test_list_subclass(self): |
---|
1652 | n/a | |
---|
1653 | n/a | class MyList(typing.List[int]): |
---|
1654 | n/a | pass |
---|
1655 | n/a | |
---|
1656 | n/a | a = MyList() |
---|
1657 | n/a | self.assertIsInstance(a, MyList) |
---|
1658 | n/a | self.assertIsInstance(a, typing.Sequence) |
---|
1659 | n/a | |
---|
1660 | n/a | self.assertIsSubclass(MyList, list) |
---|
1661 | n/a | self.assertNotIsSubclass(list, MyList) |
---|
1662 | n/a | |
---|
1663 | n/a | def test_no_dict_instantiation(self): |
---|
1664 | n/a | with self.assertRaises(TypeError): |
---|
1665 | n/a | typing.Dict() |
---|
1666 | n/a | with self.assertRaises(TypeError): |
---|
1667 | n/a | typing.Dict[KT, VT]() |
---|
1668 | n/a | with self.assertRaises(TypeError): |
---|
1669 | n/a | typing.Dict[str, int]() |
---|
1670 | n/a | |
---|
1671 | n/a | def test_dict_subclass(self): |
---|
1672 | n/a | |
---|
1673 | n/a | class MyDict(typing.Dict[str, int]): |
---|
1674 | n/a | pass |
---|
1675 | n/a | |
---|
1676 | n/a | d = MyDict() |
---|
1677 | n/a | self.assertIsInstance(d, MyDict) |
---|
1678 | n/a | self.assertIsInstance(d, typing.MutableMapping) |
---|
1679 | n/a | |
---|
1680 | n/a | self.assertIsSubclass(MyDict, dict) |
---|
1681 | n/a | self.assertNotIsSubclass(dict, MyDict) |
---|
1682 | n/a | |
---|
1683 | n/a | def test_no_defaultdict_instantiation(self): |
---|
1684 | n/a | with self.assertRaises(TypeError): |
---|
1685 | n/a | typing.DefaultDict() |
---|
1686 | n/a | with self.assertRaises(TypeError): |
---|
1687 | n/a | typing.DefaultDict[KT, VT]() |
---|
1688 | n/a | with self.assertRaises(TypeError): |
---|
1689 | n/a | typing.DefaultDict[str, int]() |
---|
1690 | n/a | |
---|
1691 | n/a | def test_defaultdict_subclass(self): |
---|
1692 | n/a | |
---|
1693 | n/a | class MyDefDict(typing.DefaultDict[str, int]): |
---|
1694 | n/a | pass |
---|
1695 | n/a | |
---|
1696 | n/a | dd = MyDefDict() |
---|
1697 | n/a | self.assertIsInstance(dd, MyDefDict) |
---|
1698 | n/a | |
---|
1699 | n/a | self.assertIsSubclass(MyDefDict, collections.defaultdict) |
---|
1700 | n/a | self.assertNotIsSubclass(collections.defaultdict, MyDefDict) |
---|
1701 | n/a | |
---|
1702 | n/a | def test_no_deque_instantiation(self): |
---|
1703 | n/a | with self.assertRaises(TypeError): |
---|
1704 | n/a | typing.Deque() |
---|
1705 | n/a | with self.assertRaises(TypeError): |
---|
1706 | n/a | typing.Deque[T]() |
---|
1707 | n/a | with self.assertRaises(TypeError): |
---|
1708 | n/a | typing.Deque[int]() |
---|
1709 | n/a | |
---|
1710 | n/a | def test_no_set_instantiation(self): |
---|
1711 | n/a | with self.assertRaises(TypeError): |
---|
1712 | n/a | typing.Set() |
---|
1713 | n/a | with self.assertRaises(TypeError): |
---|
1714 | n/a | typing.Set[T]() |
---|
1715 | n/a | with self.assertRaises(TypeError): |
---|
1716 | n/a | typing.Set[int]() |
---|
1717 | n/a | |
---|
1718 | n/a | def test_set_subclass_instantiation(self): |
---|
1719 | n/a | |
---|
1720 | n/a | class MySet(typing.Set[int]): |
---|
1721 | n/a | pass |
---|
1722 | n/a | |
---|
1723 | n/a | d = MySet() |
---|
1724 | n/a | self.assertIsInstance(d, MySet) |
---|
1725 | n/a | |
---|
1726 | n/a | def test_no_frozenset_instantiation(self): |
---|
1727 | n/a | with self.assertRaises(TypeError): |
---|
1728 | n/a | typing.FrozenSet() |
---|
1729 | n/a | with self.assertRaises(TypeError): |
---|
1730 | n/a | typing.FrozenSet[T]() |
---|
1731 | n/a | with self.assertRaises(TypeError): |
---|
1732 | n/a | typing.FrozenSet[int]() |
---|
1733 | n/a | |
---|
1734 | n/a | def test_frozenset_subclass_instantiation(self): |
---|
1735 | n/a | |
---|
1736 | n/a | class MyFrozenSet(typing.FrozenSet[int]): |
---|
1737 | n/a | pass |
---|
1738 | n/a | |
---|
1739 | n/a | d = MyFrozenSet() |
---|
1740 | n/a | self.assertIsInstance(d, MyFrozenSet) |
---|
1741 | n/a | |
---|
1742 | n/a | def test_no_tuple_instantiation(self): |
---|
1743 | n/a | with self.assertRaises(TypeError): |
---|
1744 | n/a | Tuple() |
---|
1745 | n/a | with self.assertRaises(TypeError): |
---|
1746 | n/a | Tuple[T]() |
---|
1747 | n/a | with self.assertRaises(TypeError): |
---|
1748 | n/a | Tuple[int]() |
---|
1749 | n/a | |
---|
1750 | n/a | def test_generator(self): |
---|
1751 | n/a | def foo(): |
---|
1752 | n/a | yield 42 |
---|
1753 | n/a | g = foo() |
---|
1754 | n/a | self.assertIsSubclass(type(g), typing.Generator) |
---|
1755 | n/a | |
---|
1756 | n/a | def test_no_generator_instantiation(self): |
---|
1757 | n/a | with self.assertRaises(TypeError): |
---|
1758 | n/a | typing.Generator() |
---|
1759 | n/a | with self.assertRaises(TypeError): |
---|
1760 | n/a | typing.Generator[T, T, T]() |
---|
1761 | n/a | with self.assertRaises(TypeError): |
---|
1762 | n/a | typing.Generator[int, int, int]() |
---|
1763 | n/a | |
---|
1764 | n/a | @skipUnless(PY36, 'Python 3.6 required') |
---|
1765 | n/a | def test_async_generator(self): |
---|
1766 | n/a | ns = {} |
---|
1767 | n/a | exec("async def f():\n" |
---|
1768 | n/a | " yield 42\n", globals(), ns) |
---|
1769 | n/a | g = ns['f']() |
---|
1770 | n/a | self.assertIsSubclass(type(g), typing.AsyncGenerator) |
---|
1771 | n/a | |
---|
1772 | n/a | @skipUnless(PY36, 'Python 3.6 required') |
---|
1773 | n/a | def test_no_async_generator_instantiation(self): |
---|
1774 | n/a | with self.assertRaises(TypeError): |
---|
1775 | n/a | typing.AsyncGenerator() |
---|
1776 | n/a | with self.assertRaises(TypeError): |
---|
1777 | n/a | typing.AsyncGenerator[T, T]() |
---|
1778 | n/a | with self.assertRaises(TypeError): |
---|
1779 | n/a | typing.AsyncGenerator[int, int]() |
---|
1780 | n/a | |
---|
1781 | n/a | def test_subclassing(self): |
---|
1782 | n/a | |
---|
1783 | n/a | class MMA(typing.MutableMapping): |
---|
1784 | n/a | pass |
---|
1785 | n/a | |
---|
1786 | n/a | with self.assertRaises(TypeError): # It's abstract |
---|
1787 | n/a | MMA() |
---|
1788 | n/a | |
---|
1789 | n/a | class MMC(MMA): |
---|
1790 | n/a | def __getitem__(self, k): |
---|
1791 | n/a | return None |
---|
1792 | n/a | def __setitem__(self, k, v): |
---|
1793 | n/a | pass |
---|
1794 | n/a | def __delitem__(self, k): |
---|
1795 | n/a | pass |
---|
1796 | n/a | def __iter__(self): |
---|
1797 | n/a | return iter(()) |
---|
1798 | n/a | def __len__(self): |
---|
1799 | n/a | return 0 |
---|
1800 | n/a | |
---|
1801 | n/a | self.assertEqual(len(MMC()), 0) |
---|
1802 | n/a | assert callable(MMC.update) |
---|
1803 | n/a | self.assertIsInstance(MMC(), typing.Mapping) |
---|
1804 | n/a | |
---|
1805 | n/a | class MMB(typing.MutableMapping[KT, VT]): |
---|
1806 | n/a | def __getitem__(self, k): |
---|
1807 | n/a | return None |
---|
1808 | n/a | def __setitem__(self, k, v): |
---|
1809 | n/a | pass |
---|
1810 | n/a | def __delitem__(self, k): |
---|
1811 | n/a | pass |
---|
1812 | n/a | def __iter__(self): |
---|
1813 | n/a | return iter(()) |
---|
1814 | n/a | def __len__(self): |
---|
1815 | n/a | return 0 |
---|
1816 | n/a | |
---|
1817 | n/a | self.assertEqual(len(MMB()), 0) |
---|
1818 | n/a | self.assertEqual(len(MMB[str, str]()), 0) |
---|
1819 | n/a | self.assertEqual(len(MMB[KT, VT]()), 0) |
---|
1820 | n/a | |
---|
1821 | n/a | self.assertNotIsSubclass(dict, MMA) |
---|
1822 | n/a | self.assertNotIsSubclass(dict, MMB) |
---|
1823 | n/a | |
---|
1824 | n/a | self.assertIsSubclass(MMA, typing.Mapping) |
---|
1825 | n/a | self.assertIsSubclass(MMB, typing.Mapping) |
---|
1826 | n/a | self.assertIsSubclass(MMC, typing.Mapping) |
---|
1827 | n/a | |
---|
1828 | n/a | self.assertIsInstance(MMB[KT, VT](), typing.Mapping) |
---|
1829 | n/a | self.assertIsInstance(MMB[KT, VT](), collections.Mapping) |
---|
1830 | n/a | |
---|
1831 | n/a | self.assertIsSubclass(MMA, collections.Mapping) |
---|
1832 | n/a | self.assertIsSubclass(MMB, collections.Mapping) |
---|
1833 | n/a | self.assertIsSubclass(MMC, collections.Mapping) |
---|
1834 | n/a | |
---|
1835 | n/a | self.assertIsSubclass(MMB[str, str], typing.Mapping) |
---|
1836 | n/a | self.assertIsSubclass(MMC, MMA) |
---|
1837 | n/a | |
---|
1838 | n/a | class I(typing.Iterable): ... |
---|
1839 | n/a | self.assertNotIsSubclass(list, I) |
---|
1840 | n/a | |
---|
1841 | n/a | class G(typing.Generator[int, int, int]): ... |
---|
1842 | n/a | def g(): yield 0 |
---|
1843 | n/a | self.assertIsSubclass(G, typing.Generator) |
---|
1844 | n/a | self.assertIsSubclass(G, typing.Iterable) |
---|
1845 | n/a | if hasattr(collections, 'Generator'): |
---|
1846 | n/a | self.assertIsSubclass(G, collections.Generator) |
---|
1847 | n/a | self.assertIsSubclass(G, collections.Iterable) |
---|
1848 | n/a | self.assertNotIsSubclass(type(g), G) |
---|
1849 | n/a | |
---|
1850 | n/a | @skipUnless(PY36, 'Python 3.6 required') |
---|
1851 | n/a | def test_subclassing_async_generator(self): |
---|
1852 | n/a | class G(typing.AsyncGenerator[int, int]): |
---|
1853 | n/a | def asend(self, value): |
---|
1854 | n/a | pass |
---|
1855 | n/a | def athrow(self, typ, val=None, tb=None): |
---|
1856 | n/a | pass |
---|
1857 | n/a | |
---|
1858 | n/a | ns = {} |
---|
1859 | n/a | exec('async def g(): yield 0', globals(), ns) |
---|
1860 | n/a | g = ns['g'] |
---|
1861 | n/a | self.assertIsSubclass(G, typing.AsyncGenerator) |
---|
1862 | n/a | self.assertIsSubclass(G, typing.AsyncIterable) |
---|
1863 | n/a | self.assertIsSubclass(G, collections.AsyncGenerator) |
---|
1864 | n/a | self.assertIsSubclass(G, collections.AsyncIterable) |
---|
1865 | n/a | self.assertNotIsSubclass(type(g), G) |
---|
1866 | n/a | |
---|
1867 | n/a | instance = G() |
---|
1868 | n/a | self.assertIsInstance(instance, typing.AsyncGenerator) |
---|
1869 | n/a | self.assertIsInstance(instance, typing.AsyncIterable) |
---|
1870 | n/a | self.assertIsInstance(instance, collections.AsyncGenerator) |
---|
1871 | n/a | self.assertIsInstance(instance, collections.AsyncIterable) |
---|
1872 | n/a | self.assertNotIsInstance(type(g), G) |
---|
1873 | n/a | self.assertNotIsInstance(g, G) |
---|
1874 | n/a | |
---|
1875 | n/a | def test_subclassing_subclasshook(self): |
---|
1876 | n/a | |
---|
1877 | n/a | class Base(typing.Iterable): |
---|
1878 | n/a | @classmethod |
---|
1879 | n/a | def __subclasshook__(cls, other): |
---|
1880 | n/a | if other.__name__ == 'Foo': |
---|
1881 | n/a | return True |
---|
1882 | n/a | else: |
---|
1883 | n/a | return False |
---|
1884 | n/a | |
---|
1885 | n/a | class C(Base): ... |
---|
1886 | n/a | class Foo: ... |
---|
1887 | n/a | class Bar: ... |
---|
1888 | n/a | self.assertIsSubclass(Foo, Base) |
---|
1889 | n/a | self.assertIsSubclass(Foo, C) |
---|
1890 | n/a | self.assertNotIsSubclass(Bar, C) |
---|
1891 | n/a | |
---|
1892 | n/a | def test_subclassing_register(self): |
---|
1893 | n/a | |
---|
1894 | n/a | class A(typing.Container): ... |
---|
1895 | n/a | class B(A): ... |
---|
1896 | n/a | |
---|
1897 | n/a | class C: ... |
---|
1898 | n/a | A.register(C) |
---|
1899 | n/a | self.assertIsSubclass(C, A) |
---|
1900 | n/a | self.assertNotIsSubclass(C, B) |
---|
1901 | n/a | |
---|
1902 | n/a | class D: ... |
---|
1903 | n/a | B.register(D) |
---|
1904 | n/a | self.assertIsSubclass(D, A) |
---|
1905 | n/a | self.assertIsSubclass(D, B) |
---|
1906 | n/a | |
---|
1907 | n/a | class M(): ... |
---|
1908 | n/a | collections.MutableMapping.register(M) |
---|
1909 | n/a | self.assertIsSubclass(M, typing.Mapping) |
---|
1910 | n/a | |
---|
1911 | n/a | def test_collections_as_base(self): |
---|
1912 | n/a | |
---|
1913 | n/a | class M(collections.Mapping): ... |
---|
1914 | n/a | self.assertIsSubclass(M, typing.Mapping) |
---|
1915 | n/a | self.assertIsSubclass(M, typing.Iterable) |
---|
1916 | n/a | |
---|
1917 | n/a | class S(collections.MutableSequence): ... |
---|
1918 | n/a | self.assertIsSubclass(S, typing.MutableSequence) |
---|
1919 | n/a | self.assertIsSubclass(S, typing.Iterable) |
---|
1920 | n/a | |
---|
1921 | n/a | class I(collections.Iterable): ... |
---|
1922 | n/a | self.assertIsSubclass(I, typing.Iterable) |
---|
1923 | n/a | |
---|
1924 | n/a | class A(collections.Mapping, metaclass=abc.ABCMeta): ... |
---|
1925 | n/a | class B: ... |
---|
1926 | n/a | A.register(B) |
---|
1927 | n/a | self.assertIsSubclass(B, typing.Mapping) |
---|
1928 | n/a | |
---|
1929 | n/a | |
---|
1930 | n/a | class OtherABCTests(BaseTestCase): |
---|
1931 | n/a | |
---|
1932 | n/a | @skipUnless(hasattr(typing, 'ContextManager'), |
---|
1933 | n/a | 'requires typing.ContextManager') |
---|
1934 | n/a | def test_contextmanager(self): |
---|
1935 | n/a | @contextlib.contextmanager |
---|
1936 | n/a | def manager(): |
---|
1937 | n/a | yield 42 |
---|
1938 | n/a | |
---|
1939 | n/a | cm = manager() |
---|
1940 | n/a | self.assertIsInstance(cm, typing.ContextManager) |
---|
1941 | n/a | self.assertNotIsInstance(42, typing.ContextManager) |
---|
1942 | n/a | |
---|
1943 | n/a | |
---|
1944 | n/a | class TypeTests(BaseTestCase): |
---|
1945 | n/a | |
---|
1946 | n/a | def test_type_basic(self): |
---|
1947 | n/a | |
---|
1948 | n/a | class User: pass |
---|
1949 | n/a | class BasicUser(User): pass |
---|
1950 | n/a | class ProUser(User): pass |
---|
1951 | n/a | |
---|
1952 | n/a | def new_user(user_class: Type[User]) -> User: |
---|
1953 | n/a | return user_class() |
---|
1954 | n/a | |
---|
1955 | n/a | new_user(BasicUser) |
---|
1956 | n/a | |
---|
1957 | n/a | def test_type_typevar(self): |
---|
1958 | n/a | |
---|
1959 | n/a | class User: pass |
---|
1960 | n/a | class BasicUser(User): pass |
---|
1961 | n/a | class ProUser(User): pass |
---|
1962 | n/a | |
---|
1963 | n/a | U = TypeVar('U', bound=User) |
---|
1964 | n/a | |
---|
1965 | n/a | def new_user(user_class: Type[U]) -> U: |
---|
1966 | n/a | return user_class() |
---|
1967 | n/a | |
---|
1968 | n/a | new_user(BasicUser) |
---|
1969 | n/a | |
---|
1970 | n/a | def test_type_optional(self): |
---|
1971 | n/a | A = Optional[Type[BaseException]] |
---|
1972 | n/a | |
---|
1973 | n/a | def foo(a: A) -> Optional[BaseException]: |
---|
1974 | n/a | if a is None: |
---|
1975 | n/a | return None |
---|
1976 | n/a | else: |
---|
1977 | n/a | return a() |
---|
1978 | n/a | |
---|
1979 | n/a | assert isinstance(foo(KeyboardInterrupt), KeyboardInterrupt) |
---|
1980 | n/a | assert foo(None) is None |
---|
1981 | n/a | |
---|
1982 | n/a | |
---|
1983 | n/a | class NewTypeTests(BaseTestCase): |
---|
1984 | n/a | |
---|
1985 | n/a | def test_basic(self): |
---|
1986 | n/a | UserId = NewType('UserId', int) |
---|
1987 | n/a | UserName = NewType('UserName', str) |
---|
1988 | n/a | self.assertIsInstance(UserId(5), int) |
---|
1989 | n/a | self.assertIsInstance(UserName('Joe'), str) |
---|
1990 | n/a | self.assertEqual(UserId(5) + 1, 6) |
---|
1991 | n/a | |
---|
1992 | n/a | def test_errors(self): |
---|
1993 | n/a | UserId = NewType('UserId', int) |
---|
1994 | n/a | UserName = NewType('UserName', str) |
---|
1995 | n/a | with self.assertRaises(TypeError): |
---|
1996 | n/a | issubclass(UserId, int) |
---|
1997 | n/a | with self.assertRaises(TypeError): |
---|
1998 | n/a | class D(UserName): |
---|
1999 | n/a | pass |
---|
2000 | n/a | |
---|
2001 | n/a | |
---|
2002 | n/a | class NamedTupleTests(BaseTestCase): |
---|
2003 | n/a | |
---|
2004 | n/a | def test_basics(self): |
---|
2005 | n/a | Emp = NamedTuple('Emp', [('name', str), ('id', int)]) |
---|
2006 | n/a | self.assertIsSubclass(Emp, tuple) |
---|
2007 | n/a | joe = Emp('Joe', 42) |
---|
2008 | n/a | jim = Emp(name='Jim', id=1) |
---|
2009 | n/a | self.assertIsInstance(joe, Emp) |
---|
2010 | n/a | self.assertIsInstance(joe, tuple) |
---|
2011 | n/a | self.assertEqual(joe.name, 'Joe') |
---|
2012 | n/a | self.assertEqual(joe.id, 42) |
---|
2013 | n/a | self.assertEqual(jim.name, 'Jim') |
---|
2014 | n/a | self.assertEqual(jim.id, 1) |
---|
2015 | n/a | self.assertEqual(Emp.__name__, 'Emp') |
---|
2016 | n/a | self.assertEqual(Emp._fields, ('name', 'id')) |
---|
2017 | n/a | self.assertEqual(Emp.__annotations__, |
---|
2018 | n/a | collections.OrderedDict([('name', str), ('id', int)])) |
---|
2019 | n/a | self.assertIs(Emp._field_types, Emp.__annotations__) |
---|
2020 | n/a | |
---|
2021 | n/a | @skipUnless(PY36, 'Python 3.6 required') |
---|
2022 | n/a | def test_annotation_usage(self): |
---|
2023 | n/a | tim = CoolEmployee('Tim', 9000) |
---|
2024 | n/a | self.assertIsInstance(tim, CoolEmployee) |
---|
2025 | n/a | self.assertIsInstance(tim, tuple) |
---|
2026 | n/a | self.assertEqual(tim.name, 'Tim') |
---|
2027 | n/a | self.assertEqual(tim.cool, 9000) |
---|
2028 | n/a | self.assertEqual(CoolEmployee.__name__, 'CoolEmployee') |
---|
2029 | n/a | self.assertEqual(CoolEmployee._fields, ('name', 'cool')) |
---|
2030 | n/a | self.assertEqual(CoolEmployee.__annotations__, |
---|
2031 | n/a | collections.OrderedDict(name=str, cool=int)) |
---|
2032 | n/a | self.assertIs(CoolEmployee._field_types, CoolEmployee.__annotations__) |
---|
2033 | n/a | |
---|
2034 | n/a | @skipUnless(PY36, 'Python 3.6 required') |
---|
2035 | n/a | def test_annotation_usage_with_default(self): |
---|
2036 | n/a | jelle = CoolEmployeeWithDefault('Jelle') |
---|
2037 | n/a | self.assertIsInstance(jelle, CoolEmployeeWithDefault) |
---|
2038 | n/a | self.assertIsInstance(jelle, tuple) |
---|
2039 | n/a | self.assertEqual(jelle.name, 'Jelle') |
---|
2040 | n/a | self.assertEqual(jelle.cool, 0) |
---|
2041 | n/a | cooler_employee = CoolEmployeeWithDefault('Sjoerd', 1) |
---|
2042 | n/a | self.assertEqual(cooler_employee.cool, 1) |
---|
2043 | n/a | |
---|
2044 | n/a | self.assertEqual(CoolEmployeeWithDefault.__name__, 'CoolEmployeeWithDefault') |
---|
2045 | n/a | self.assertEqual(CoolEmployeeWithDefault._fields, ('name', 'cool')) |
---|
2046 | n/a | self.assertEqual(CoolEmployeeWithDefault._field_types, dict(name=str, cool=int)) |
---|
2047 | n/a | self.assertEqual(CoolEmployeeWithDefault._field_defaults, dict(cool=0)) |
---|
2048 | n/a | |
---|
2049 | n/a | with self.assertRaises(TypeError): |
---|
2050 | n/a | exec(""" |
---|
2051 | n/a | class NonDefaultAfterDefault(NamedTuple): |
---|
2052 | n/a | x: int = 3 |
---|
2053 | n/a | y: int |
---|
2054 | n/a | """) |
---|
2055 | n/a | |
---|
2056 | n/a | @skipUnless(PY36, 'Python 3.6 required') |
---|
2057 | n/a | def test_annotation_usage_with_methods(self): |
---|
2058 | n/a | self.assertEquals(XMeth(1).double(), 2) |
---|
2059 | n/a | self.assertEquals(XMeth(42).x, XMeth(42)[0]) |
---|
2060 | n/a | self.assertEquals(XMethBad(1)._fields, ('x',)) |
---|
2061 | n/a | self.assertEquals(XMethBad(1).__annotations__, {'x': int}) |
---|
2062 | n/a | |
---|
2063 | n/a | @skipUnless(PY36, 'Python 3.6 required') |
---|
2064 | n/a | def test_namedtuple_keyword_usage(self): |
---|
2065 | n/a | LocalEmployee = NamedTuple("LocalEmployee", name=str, age=int) |
---|
2066 | n/a | nick = LocalEmployee('Nick', 25) |
---|
2067 | n/a | self.assertIsInstance(nick, tuple) |
---|
2068 | n/a | self.assertEqual(nick.name, 'Nick') |
---|
2069 | n/a | self.assertEqual(LocalEmployee.__name__, 'LocalEmployee') |
---|
2070 | n/a | self.assertEqual(LocalEmployee._fields, ('name', 'age')) |
---|
2071 | n/a | self.assertEqual(LocalEmployee.__annotations__, dict(name=str, age=int)) |
---|
2072 | n/a | self.assertIs(LocalEmployee._field_types, LocalEmployee.__annotations__) |
---|
2073 | n/a | with self.assertRaises(TypeError): |
---|
2074 | n/a | NamedTuple('Name', [('x', int)], y=str) |
---|
2075 | n/a | with self.assertRaises(TypeError): |
---|
2076 | n/a | NamedTuple('Name', x=1, y='a') |
---|
2077 | n/a | |
---|
2078 | n/a | def test_pickle(self): |
---|
2079 | n/a | global Emp # pickle wants to reference the class by name |
---|
2080 | n/a | Emp = NamedTuple('Emp', [('name', str), ('id', int)]) |
---|
2081 | n/a | jane = Emp('jane', 37) |
---|
2082 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
2083 | n/a | z = pickle.dumps(jane, proto) |
---|
2084 | n/a | jane2 = pickle.loads(z) |
---|
2085 | n/a | self.assertEqual(jane2, jane) |
---|
2086 | n/a | |
---|
2087 | n/a | |
---|
2088 | n/a | class IOTests(BaseTestCase): |
---|
2089 | n/a | |
---|
2090 | n/a | def test_io(self): |
---|
2091 | n/a | |
---|
2092 | n/a | def stuff(a: IO) -> AnyStr: |
---|
2093 | n/a | return a.readline() |
---|
2094 | n/a | |
---|
2095 | n/a | a = stuff.__annotations__['a'] |
---|
2096 | n/a | self.assertEqual(a.__parameters__, (AnyStr,)) |
---|
2097 | n/a | |
---|
2098 | n/a | def test_textio(self): |
---|
2099 | n/a | |
---|
2100 | n/a | def stuff(a: TextIO) -> str: |
---|
2101 | n/a | return a.readline() |
---|
2102 | n/a | |
---|
2103 | n/a | a = stuff.__annotations__['a'] |
---|
2104 | n/a | self.assertEqual(a.__parameters__, ()) |
---|
2105 | n/a | |
---|
2106 | n/a | def test_binaryio(self): |
---|
2107 | n/a | |
---|
2108 | n/a | def stuff(a: BinaryIO) -> bytes: |
---|
2109 | n/a | return a.readline() |
---|
2110 | n/a | |
---|
2111 | n/a | a = stuff.__annotations__['a'] |
---|
2112 | n/a | self.assertEqual(a.__parameters__, ()) |
---|
2113 | n/a | |
---|
2114 | n/a | def test_io_submodule(self): |
---|
2115 | n/a | from typing.io import IO, TextIO, BinaryIO, __all__, __name__ |
---|
2116 | n/a | self.assertIs(IO, typing.IO) |
---|
2117 | n/a | self.assertIs(TextIO, typing.TextIO) |
---|
2118 | n/a | self.assertIs(BinaryIO, typing.BinaryIO) |
---|
2119 | n/a | self.assertEqual(set(__all__), set(['IO', 'TextIO', 'BinaryIO'])) |
---|
2120 | n/a | self.assertEqual(__name__, 'typing.io') |
---|
2121 | n/a | |
---|
2122 | n/a | |
---|
2123 | n/a | class RETests(BaseTestCase): |
---|
2124 | n/a | # Much of this is really testing _TypeAlias. |
---|
2125 | n/a | |
---|
2126 | n/a | def test_basics(self): |
---|
2127 | n/a | pat = re.compile('[a-z]+', re.I) |
---|
2128 | n/a | self.assertIsSubclass(pat.__class__, Pattern) |
---|
2129 | n/a | self.assertIsSubclass(type(pat), Pattern) |
---|
2130 | n/a | self.assertIsInstance(pat, Pattern) |
---|
2131 | n/a | |
---|
2132 | n/a | mat = pat.search('12345abcde.....') |
---|
2133 | n/a | self.assertIsSubclass(mat.__class__, Match) |
---|
2134 | n/a | self.assertIsSubclass(type(mat), Match) |
---|
2135 | n/a | self.assertIsInstance(mat, Match) |
---|
2136 | n/a | |
---|
2137 | n/a | # these should just work |
---|
2138 | n/a | Pattern[Union[str, bytes]] |
---|
2139 | n/a | Match[Union[bytes, str]] |
---|
2140 | n/a | |
---|
2141 | n/a | def test_errors(self): |
---|
2142 | n/a | with self.assertRaises(TypeError): |
---|
2143 | n/a | # Doesn't fit AnyStr. |
---|
2144 | n/a | Pattern[int] |
---|
2145 | n/a | with self.assertRaises(TypeError): |
---|
2146 | n/a | # Can't change type vars? |
---|
2147 | n/a | Match[T] |
---|
2148 | n/a | m = Match[Union[str, bytes]] |
---|
2149 | n/a | with self.assertRaises(TypeError): |
---|
2150 | n/a | # Too complicated? |
---|
2151 | n/a | m[str] |
---|
2152 | n/a | with self.assertRaises(TypeError): |
---|
2153 | n/a | # We don't support isinstance(). |
---|
2154 | n/a | isinstance(42, Pattern[str]) |
---|
2155 | n/a | |
---|
2156 | n/a | def test_repr(self): |
---|
2157 | n/a | self.assertEqual(repr(Pattern), 'Pattern[~AnyStr]') |
---|
2158 | n/a | self.assertEqual(repr(Pattern[str]), 'Pattern[str]') |
---|
2159 | n/a | self.assertEqual(repr(Pattern[bytes]), 'Pattern[bytes]') |
---|
2160 | n/a | self.assertEqual(repr(Match), 'Match[~AnyStr]') |
---|
2161 | n/a | self.assertEqual(repr(Match[str]), 'Match[str]') |
---|
2162 | n/a | self.assertEqual(repr(Match[bytes]), 'Match[bytes]') |
---|
2163 | n/a | |
---|
2164 | n/a | def test_re_submodule(self): |
---|
2165 | n/a | from typing.re import Match, Pattern, __all__, __name__ |
---|
2166 | n/a | self.assertIs(Match, typing.Match) |
---|
2167 | n/a | self.assertIs(Pattern, typing.Pattern) |
---|
2168 | n/a | self.assertEqual(set(__all__), set(['Match', 'Pattern'])) |
---|
2169 | n/a | self.assertEqual(__name__, 'typing.re') |
---|
2170 | n/a | |
---|
2171 | n/a | def test_cannot_subclass(self): |
---|
2172 | n/a | with self.assertRaises(TypeError) as ex: |
---|
2173 | n/a | |
---|
2174 | n/a | class A(typing.Match): |
---|
2175 | n/a | pass |
---|
2176 | n/a | |
---|
2177 | n/a | self.assertEqual(str(ex.exception), |
---|
2178 | n/a | "Cannot subclass typing._TypeAlias") |
---|
2179 | n/a | |
---|
2180 | n/a | |
---|
2181 | n/a | class AllTests(BaseTestCase): |
---|
2182 | n/a | """Tests for __all__.""" |
---|
2183 | n/a | |
---|
2184 | n/a | def test_all(self): |
---|
2185 | n/a | from typing import __all__ as a |
---|
2186 | n/a | # Just spot-check the first and last of every category. |
---|
2187 | n/a | self.assertIn('AbstractSet', a) |
---|
2188 | n/a | self.assertIn('ValuesView', a) |
---|
2189 | n/a | self.assertIn('cast', a) |
---|
2190 | n/a | self.assertIn('overload', a) |
---|
2191 | n/a | if hasattr(contextlib, 'AbstractContextManager'): |
---|
2192 | n/a | self.assertIn('ContextManager', a) |
---|
2193 | n/a | # Check that io and re are not exported. |
---|
2194 | n/a | self.assertNotIn('io', a) |
---|
2195 | n/a | self.assertNotIn('re', a) |
---|
2196 | n/a | # Spot-check that stdlib modules aren't exported. |
---|
2197 | n/a | self.assertNotIn('os', a) |
---|
2198 | n/a | self.assertNotIn('sys', a) |
---|
2199 | n/a | # Check that Text is defined. |
---|
2200 | n/a | self.assertIn('Text', a) |
---|
2201 | n/a | |
---|
2202 | n/a | |
---|
2203 | n/a | if __name__ == '__main__': |
---|
2204 | n/a | main() |
---|