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