ยปCore Development>Code coverage>Lib/test/test_typing.py

Python code coverage for Lib/test/test_typing.py

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