8
8
import collections .abc
9
9
import copy
10
10
from functools import lru_cache
11
+ import importlib
11
12
import inspect
12
13
import pickle
13
14
import subprocess
15
+ import tempfile
14
16
import types
17
+ from pathlib import Path
15
18
from unittest import TestCase , main , skipUnless , skipIf
16
19
from unittest .mock import patch
17
- from test import ann_module , ann_module2 , ann_module3
18
20
import typing
19
21
from typing import TypeVar , Optional , Union , AnyStr
20
22
from typing import T , KT , VT # Not in __all__.
21
23
from typing import Tuple , List , Dict , Iterable , Iterator , Callable
22
24
from typing import Generic
23
25
from typing import no_type_check
26
+ import warnings
27
+
24
28
import typing_extensions
25
29
from typing_extensions import NoReturn , Any , ClassVar , Final , IntVar , Literal , Type , NewType , TypedDict , Self
26
30
from typing_extensions import TypeAlias , ParamSpec , Concatenate , ParamSpecArgs , ParamSpecKwargs , TypeGuard
32
36
from typing_extensions import NamedTuple
33
37
from typing_extensions import override , deprecated , Buffer
34
38
from _typed_dict_test_helper import Foo , FooGeneric
35
- import warnings
36
39
37
40
# Flags used to mark tests that only apply after a specific
38
41
# version of the typing module.
47
50
# versions, but not all
48
51
HAS_FORWARD_MODULE = "module" in inspect .signature (typing ._type_check ).parameters
49
52
53
+ ANN_MODULE_SOURCE = '''\
54
+ from typing import Optional
55
+ from functools import wraps
56
+
57
+ __annotations__[1] = 2
58
+
59
+ class C:
60
+
61
+ x = 5; y: Optional['C'] = None
62
+
63
+ from typing import Tuple
64
+ x: int = 5; y: str = x; f: Tuple[int, int]
65
+
66
+ class M(type):
67
+
68
+ __annotations__['123'] = 123
69
+ o: type = object
70
+
71
+ (pars): bool = True
72
+
73
+ class D(C):
74
+ j: str = 'hi'; k: str= 'bye'
75
+
76
+ from types import new_class
77
+ h_class = new_class('H', (C,))
78
+ j_class = new_class('J')
79
+
80
+ class F():
81
+ z: int = 5
82
+ def __init__(self, x):
83
+ pass
84
+
85
+ class Y(F):
86
+ def __init__(self):
87
+ super(F, self).__init__(123)
88
+
89
+ class Meta(type):
90
+ def __new__(meta, name, bases, namespace):
91
+ return super().__new__(meta, name, bases, namespace)
92
+
93
+ class S(metaclass = Meta):
94
+ x: str = 'something'
95
+ y: str = 'something else'
96
+
97
+ def foo(x: int = 10):
98
+ def bar(y: List[str]):
99
+ x: str = 'yes'
100
+ bar()
101
+
102
+ def dec(func):
103
+ @wraps(func)
104
+ def wrapper(*args, **kwargs):
105
+ return func(*args, **kwargs)
106
+ return wrapper
107
+ '''
108
+
109
+ ANN_MODULE_2_SOURCE = '''\
110
+ from typing import no_type_check, ClassVar
111
+
112
+ i: int = 1
113
+ j: int
114
+ x: float = i/10
115
+
116
+ def f():
117
+ class C: ...
118
+ return C()
119
+
120
+ f().new_attr: object = object()
121
+
122
+ class C:
123
+ def __init__(self, x: int) -> None:
124
+ self.x = x
125
+
126
+ c = C(5)
127
+ c.new_attr: int = 10
128
+
129
+ __annotations__ = {}
130
+
131
+
132
+ @no_type_check
133
+ class NTC:
134
+ def meth(self, param: complex) -> None:
135
+ ...
136
+
137
+ class CV:
138
+ var: ClassVar['CV']
139
+
140
+ CV.var = CV()
141
+ '''
142
+
143
+ ANN_MODULE_3_SOURCE = '''\
144
+ def f_bad_ann():
145
+ __annotations__[1] = 2
146
+
147
+ class C_OK:
148
+ def __init__(self, x: int) -> None:
149
+ self.x: no_such_name = x # This one is OK as proposed by Guido
150
+
151
+ class D_bad_ann:
152
+ def __init__(self, x: int) -> None:
153
+ sfel.y: int = 0
154
+
155
+ def g_bad_ann():
156
+ no_such_name.attr: int = 0
157
+ '''
158
+
50
159
51
160
class BaseTestCase (TestCase ):
52
161
def assertIsSubclass (self , cls , class_or_tuple , msg = None ):
@@ -384,8 +493,13 @@ def test_repr(self):
384
493
else :
385
494
mod_name = 'typing_extensions'
386
495
self .assertEqual (repr (Any ), f"{ mod_name } .Any" )
387
- if sys .version_info < (3 , 11 ): # skip for now on 3.11+ see python/cpython#95987
388
- self .assertEqual (repr (self .SubclassesAny ), "<class 'test_typing_extensions.AnyTests.SubclassesAny'>" )
496
+
497
+ @skipIf (sys .version_info [:3 ] == (3 , 11 , 0 ), "A bug was fixed in 3.11.1" )
498
+ def test_repr_on_Any_subclass (self ):
499
+ self .assertEqual (
500
+ repr (self .SubclassesAny ),
501
+ f"<class '{ self .SubclassesAny .__module__ } .AnyTests.SubclassesAny'>"
502
+ )
389
503
390
504
def test_instantiation (self ):
391
505
with self .assertRaises (TypeError ):
@@ -944,28 +1058,42 @@ class AnnotatedMovie(TypedDict):
944
1058
945
1059
946
1060
class GetTypeHintTests (BaseTestCase ):
1061
+ @classmethod
1062
+ def setUpClass (cls ):
1063
+ with tempfile .TemporaryDirectory () as tempdir :
1064
+ sys .path .append (tempdir )
1065
+ Path (tempdir , "ann_module.py" ).write_text (ANN_MODULE_SOURCE )
1066
+ Path (tempdir , "ann_module2.py" ).write_text (ANN_MODULE_2_SOURCE )
1067
+ Path (tempdir , "ann_module3.py" ).write_text (ANN_MODULE_3_SOURCE )
1068
+ cls .ann_module = importlib .import_module ("ann_module" )
1069
+ cls .ann_module2 = importlib .import_module ("ann_module2" )
1070
+ cls .ann_module3 = importlib .import_module ("ann_module3" )
1071
+ sys .path .pop ()
1072
+
1073
+ @classmethod
1074
+ def tearDownClass (cls ):
1075
+ for modname in "ann_module" , "ann_module2" , "ann_module3" :
1076
+ delattr (cls , modname )
1077
+ del sys .modules [modname ]
1078
+
947
1079
def test_get_type_hints_modules (self ):
948
1080
ann_module_type_hints = {1 : 2 , 'f' : Tuple [int , int ], 'x' : int , 'y' : str }
949
- if (TYPING_3_11_0
950
- or (TYPING_3_10_0 and sys .version_info .releaselevel in {'candidate' , 'final' })):
951
- # More tests were added in 3.10rc1.
952
- ann_module_type_hints ['u' ] = int | float
953
- self .assertEqual (gth (ann_module ), ann_module_type_hints )
954
- self .assertEqual (gth (ann_module2 ), {})
955
- self .assertEqual (gth (ann_module3 ), {})
1081
+ self .assertEqual (gth (self .ann_module ), ann_module_type_hints )
1082
+ self .assertEqual (gth (self .ann_module2 ), {})
1083
+ self .assertEqual (gth (self .ann_module3 ), {})
956
1084
957
1085
def test_get_type_hints_classes (self ):
958
- self .assertEqual (gth (ann_module .C , ann_module .__dict__ ),
959
- {'y' : Optional [ann_module .C ]})
960
- self .assertIsInstance (gth (ann_module .j_class ), dict )
961
- self .assertEqual (gth (ann_module .M ), {'123' : 123 , 'o' : type })
962
- self .assertEqual (gth (ann_module .D ),
963
- {'j' : str , 'k' : str , 'y' : Optional [ann_module .C ]})
964
- self .assertEqual (gth (ann_module .Y ), {'z' : int })
965
- self .assertEqual (gth (ann_module .h_class ),
966
- {'y' : Optional [ann_module .C ]})
967
- self .assertEqual (gth (ann_module .S ), {'x' : str , 'y' : str })
968
- self .assertEqual (gth (ann_module .foo ), {'x' : int })
1086
+ self .assertEqual (gth (self . ann_module .C , self . ann_module .__dict__ ),
1087
+ {'y' : Optional [self . ann_module .C ]})
1088
+ self .assertIsInstance (gth (self . ann_module .j_class ), dict )
1089
+ self .assertEqual (gth (self . ann_module .M ), {'123' : 123 , 'o' : type })
1090
+ self .assertEqual (gth (self . ann_module .D ),
1091
+ {'j' : str , 'k' : str , 'y' : Optional [self . ann_module .C ]})
1092
+ self .assertEqual (gth (self . ann_module .Y ), {'z' : int })
1093
+ self .assertEqual (gth (self . ann_module .h_class ),
1094
+ {'y' : Optional [self . ann_module .C ]})
1095
+ self .assertEqual (gth (self . ann_module .S ), {'x' : str , 'y' : str })
1096
+ self .assertEqual (gth (self . ann_module .foo ), {'x' : int })
969
1097
self .assertEqual (gth (NoneAndForward , globals ()),
970
1098
{'parent' : NoneAndForward , 'meaning' : type (None )})
971
1099
@@ -976,16 +1104,16 @@ class Inn:
976
1104
def __init__ (self , x : 'not a type' ): ...
977
1105
self .assertTrue (NoTpCheck .__no_type_check__ )
978
1106
self .assertTrue (NoTpCheck .Inn .__init__ .__no_type_check__ )
979
- self .assertEqual (gth (ann_module2 .NTC .meth ), {})
1107
+ self .assertEqual (gth (self . ann_module2 .NTC .meth ), {})
980
1108
class ABase (Generic [T ]):
981
1109
def meth (x : int ): ...
982
1110
@no_type_check
983
1111
class Der (ABase ): ...
984
1112
self .assertEqual (gth (ABase .meth ), {'x' : int })
985
1113
986
1114
def test_get_type_hints_ClassVar (self ):
987
- self .assertEqual (gth (ann_module2 .CV , ann_module2 .__dict__ ),
988
- {'var' : ClassVar [ann_module2 .CV ]})
1115
+ self .assertEqual (gth (self . ann_module2 .CV , self . ann_module2 .__dict__ ),
1116
+ {'var' : ClassVar [self . ann_module2 .CV ]})
989
1117
self .assertEqual (gth (B , globals ()),
990
1118
{'y' : int , 'x' : ClassVar [Optional [B ]], 'b' : int })
991
1119
self .assertEqual (gth (CSub , globals ()),
0 commit comments