-
-
Notifications
You must be signed in to change notification settings - Fork 111
/
test_typing_extensions.py
3691 lines (3076 loc) · 122 KB
/
test_typing_extensions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
import abc
import contextlib
import collections
from collections import defaultdict
import collections.abc
import copy
from functools import lru_cache
import inspect
import pickle
import subprocess
import types
from unittest import TestCase, main, skipUnless, skipIf
from unittest.mock import patch
from test import ann_module, ann_module2, ann_module3
import typing
from typing import TypeVar, Optional, Union, AnyStr
from typing import T, KT, VT # Not in __all__.
from typing import Tuple, List, Dict, Iterable, Iterator, Callable
from typing import Generic
from typing import no_type_check
import typing_extensions
from typing_extensions import NoReturn, Any, ClassVar, Final, IntVar, Literal, Type, NewType, TypedDict, Self
from typing_extensions import TypeAlias, ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs, TypeGuard
from typing_extensions import Awaitable, AsyncIterator, AsyncContextManager, Required, NotRequired
from typing_extensions import Protocol, runtime, runtime_checkable, Annotated, final, is_typeddict
from typing_extensions import TypeVarTuple, Unpack, dataclass_transform, reveal_type, Never, assert_never, LiteralString
from typing_extensions import assert_type, get_type_hints, get_origin, get_args
from typing_extensions import clear_overloads, get_overloads, overload
from typing_extensions import NamedTuple
from typing_extensions import override, deprecated
from _typed_dict_test_helper import Foo, FooGeneric
import warnings
# Flags used to mark tests that only apply after a specific
# version of the typing module.
TYPING_3_8_0 = sys.version_info[:3] >= (3, 8, 0)
TYPING_3_9_0 = sys.version_info[:3] >= (3, 9, 0)
TYPING_3_10_0 = sys.version_info[:3] >= (3, 10, 0)
# 3.11 makes runtime type checks (_type_check) more lenient.
TYPING_3_11_0 = sys.version_info[:3] >= (3, 11, 0)
# https://github.com/python/cpython/pull/27017 was backported into some 3.9 and 3.10
# versions, but not all
HAS_FORWARD_MODULE = "module" in inspect.signature(typing._type_check).parameters
class BaseTestCase(TestCase):
def assertIsSubclass(self, cls, class_or_tuple, msg=None):
if not issubclass(cls, class_or_tuple):
message = f'{cls!r} is not a subclass of {repr(class_or_tuple)}'
if msg is not None:
message += f' : {msg}'
raise self.failureException(message)
def assertNotIsSubclass(self, cls, class_or_tuple, msg=None):
if issubclass(cls, class_or_tuple):
message = f'{cls!r} is a subclass of {repr(class_or_tuple)}'
if msg is not None:
message += f' : {msg}'
raise self.failureException(message)
class Employee:
pass
class BottomTypeTestsMixin:
bottom_type: ClassVar[Any]
def test_equality(self):
self.assertEqual(self.bottom_type, self.bottom_type)
self.assertIs(self.bottom_type, self.bottom_type)
self.assertNotEqual(self.bottom_type, None)
def test_get_origin(self):
self.assertIs(get_origin(self.bottom_type), None)
def test_instance_type_error(self):
with self.assertRaises(TypeError):
isinstance(42, self.bottom_type)
def test_subclass_type_error(self):
with self.assertRaises(TypeError):
issubclass(Employee, self.bottom_type)
with self.assertRaises(TypeError):
issubclass(NoReturn, self.bottom_type)
def test_not_generic(self):
with self.assertRaises(TypeError):
self.bottom_type[int]
def test_cannot_subclass(self):
with self.assertRaises(TypeError):
class A(self.bottom_type):
pass
with self.assertRaises(TypeError):
class A(type(self.bottom_type)):
pass
def test_cannot_instantiate(self):
with self.assertRaises(TypeError):
self.bottom_type()
with self.assertRaises(TypeError):
type(self.bottom_type)()
def test_pickle(self):
for proto in range(pickle.HIGHEST_PROTOCOL):
pickled = pickle.dumps(self.bottom_type, protocol=proto)
self.assertIs(self.bottom_type, pickle.loads(pickled))
class NoReturnTests(BottomTypeTestsMixin, BaseTestCase):
bottom_type = NoReturn
def test_repr(self):
if hasattr(typing, 'NoReturn'):
self.assertEqual(repr(NoReturn), 'typing.NoReturn')
else:
self.assertEqual(repr(NoReturn), 'typing_extensions.NoReturn')
def test_get_type_hints(self):
def some(arg: NoReturn) -> NoReturn: ...
def some_str(arg: 'NoReturn') -> 'typing.NoReturn': ...
expected = {'arg': NoReturn, 'return': NoReturn}
targets = [some]
# On 3.7.0 and 3.7.1, https://github.com/python/cpython/pull/10772
# wasn't applied yet and NoReturn fails _type_check.
if not ((3, 7, 0) <= sys.version_info < (3, 7, 2)):
targets.append(some_str)
for target in targets:
with self.subTest(target=target):
self.assertEqual(gth(target), expected)
def test_not_equality(self):
self.assertNotEqual(NoReturn, Never)
self.assertNotEqual(Never, NoReturn)
class NeverTests(BottomTypeTestsMixin, BaseTestCase):
bottom_type = Never
def test_repr(self):
if hasattr(typing, 'Never'):
self.assertEqual(repr(Never), 'typing.Never')
else:
self.assertEqual(repr(Never), 'typing_extensions.Never')
def test_get_type_hints(self):
def some(arg: Never) -> Never: ...
def some_str(arg: 'Never') -> 'typing_extensions.Never': ...
expected = {'arg': Never, 'return': Never}
for target in [some, some_str]:
with self.subTest(target=target):
self.assertEqual(gth(target), expected)
class AssertNeverTests(BaseTestCase):
def test_exception(self):
with self.assertRaises(AssertionError):
assert_never(None)
class OverrideTests(BaseTestCase):
def test_override(self):
class Base:
def normal_method(self): ...
@staticmethod
def static_method_good_order(): ...
@staticmethod
def static_method_bad_order(): ...
@staticmethod
def decorator_with_slots(): ...
class Derived(Base):
@override
def normal_method(self):
return 42
@staticmethod
@override
def static_method_good_order():
return 42
@override
@staticmethod
def static_method_bad_order():
return 42
self.assertIsSubclass(Derived, Base)
instance = Derived()
self.assertEqual(instance.normal_method(), 42)
self.assertIs(True, instance.normal_method.__override__)
self.assertEqual(Derived.static_method_good_order(), 42)
self.assertIs(True, Derived.static_method_good_order.__override__)
self.assertEqual(Derived.static_method_bad_order(), 42)
self.assertIs(False, hasattr(Derived.static_method_bad_order, "__override__"))
class DeprecatedTests(BaseTestCase):
def test_dunder_deprecated(self):
@deprecated("A will go away soon")
class A:
pass
self.assertEqual(A.__deprecated__, "A will go away soon")
self.assertIsInstance(A, type)
@deprecated("b will go away soon")
def b():
pass
self.assertEqual(b.__deprecated__, "b will go away soon")
self.assertIsInstance(b, types.FunctionType)
@overload
@deprecated("no more ints")
def h(x: int) -> int: ...
@overload
def h(x: str) -> str: ...
def h(x):
return x
overloads = get_overloads(h)
self.assertEqual(len(overloads), 2)
self.assertEqual(overloads[0].__deprecated__, "no more ints")
def test_class(self):
@deprecated("A will go away soon")
class A:
pass
with self.assertWarnsRegex(DeprecationWarning, "A will go away soon"):
A()
with self.assertRaises(TypeError):
A(42)
@deprecated("HasInit will go away soon")
class HasInit:
def __init__(self, x):
self.x = x
with self.assertWarnsRegex(DeprecationWarning, "HasInit will go away soon"):
instance = HasInit(42)
self.assertEqual(instance.x, 42)
has_new_called = False
@deprecated("HasNew will go away soon")
class HasNew:
def __new__(cls, x):
nonlocal has_new_called
has_new_called = True
return super().__new__(cls)
def __init__(self, x) -> None:
self.x = x
with self.assertWarnsRegex(DeprecationWarning, "HasNew will go away soon"):
instance = HasNew(42)
self.assertEqual(instance.x, 42)
self.assertTrue(has_new_called)
new_base_called = False
class NewBase:
def __new__(cls, x):
nonlocal new_base_called
new_base_called = True
return super().__new__(cls)
def __init__(self, x) -> None:
self.x = x
@deprecated("HasInheritedNew will go away soon")
class HasInheritedNew(NewBase):
pass
with self.assertWarnsRegex(DeprecationWarning, "HasInheritedNew will go away soon"):
instance = HasInheritedNew(42)
self.assertEqual(instance.x, 42)
self.assertTrue(new_base_called)
def test_function(self):
@deprecated("b will go away soon")
def b():
pass
with self.assertWarnsRegex(DeprecationWarning, "b will go away soon"):
b()
def test_method(self):
class Capybara:
@deprecated("x will go away soon")
def x(self):
pass
instance = Capybara()
with self.assertWarnsRegex(DeprecationWarning, "x will go away soon"):
instance.x()
def test_property(self):
class Capybara:
@property
@deprecated("x will go away soon")
def x(self):
pass
@property
def no_more_setting(self):
return 42
@no_more_setting.setter
@deprecated("no more setting")
def no_more_setting(self, value):
pass
instance = Capybara()
with self.assertWarnsRegex(DeprecationWarning, "x will go away soon"):
instance.x
with warnings.catch_warnings():
warnings.simplefilter("error")
self.assertEqual(instance.no_more_setting, 42)
with self.assertWarnsRegex(DeprecationWarning, "no more setting"):
instance.no_more_setting = 42
def test_category(self):
@deprecated("c will go away soon", category=RuntimeWarning)
def c():
pass
with self.assertWarnsRegex(RuntimeWarning, "c will go away soon"):
c()
def test_turn_off_warnings(self):
@deprecated("d will go away soon", category=None)
def d():
pass
with warnings.catch_warnings():
warnings.simplefilter("error")
d()
class AnyTests(BaseTestCase):
def test_can_subclass(self):
class Mock(Any): pass
self.assertTrue(issubclass(Mock, Any))
self.assertIsInstance(Mock(), Mock)
class Something: pass
self.assertFalse(issubclass(Something, Any))
self.assertNotIsInstance(Something(), Mock)
class MockSomething(Something, Mock): pass
self.assertTrue(issubclass(MockSomething, Any))
ms = MockSomething()
self.assertIsInstance(ms, MockSomething)
self.assertIsInstance(ms, Something)
self.assertIsInstance(ms, Mock)
class SubclassesAny(Any):
...
def test_repr(self):
if sys.version_info >= (3, 11):
mod_name = 'typing'
else:
mod_name = 'typing_extensions'
self.assertEqual(repr(Any), f"{mod_name}.Any")
if sys.version_info < (3, 11): # skip for now on 3.11+ see python/cpython#95987
self.assertEqual(repr(self.SubclassesAny), "<class 'test_typing_extensions.AnyTests.SubclassesAny'>")
def test_instantiation(self):
with self.assertRaises(TypeError):
Any()
self.SubclassesAny()
def test_isinstance(self):
with self.assertRaises(TypeError):
isinstance(object(), Any)
isinstance(object(), self.SubclassesAny)
class ClassVarTests(BaseTestCase):
def test_basics(self):
if not TYPING_3_11_0:
with self.assertRaises(TypeError):
ClassVar[1]
with self.assertRaises(TypeError):
ClassVar[int, str]
with self.assertRaises(TypeError):
ClassVar[int][str]
def test_repr(self):
if hasattr(typing, 'ClassVar'):
mod_name = 'typing'
else:
mod_name = 'typing_extensions'
self.assertEqual(repr(ClassVar), mod_name + '.ClassVar')
cv = ClassVar[int]
self.assertEqual(repr(cv), mod_name + '.ClassVar[int]')
cv = ClassVar[Employee]
self.assertEqual(repr(cv), mod_name + f'.ClassVar[{__name__}.Employee]')
def test_cannot_subclass(self):
with self.assertRaises(TypeError):
class C(type(ClassVar)):
pass
with self.assertRaises(TypeError):
class C(type(ClassVar[int])):
pass
def test_cannot_init(self):
with self.assertRaises(TypeError):
ClassVar()
with self.assertRaises(TypeError):
type(ClassVar)()
with self.assertRaises(TypeError):
type(ClassVar[Optional[int]])()
def test_no_isinstance(self):
with self.assertRaises(TypeError):
isinstance(1, ClassVar[int])
with self.assertRaises(TypeError):
issubclass(int, ClassVar)
class FinalTests(BaseTestCase):
def test_basics(self):
if not TYPING_3_11_0:
with self.assertRaises(TypeError):
Final[1]
with self.assertRaises(TypeError):
Final[int, str]
with self.assertRaises(TypeError):
Final[int][str]
def test_repr(self):
if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):
mod_name = 'typing'
else:
mod_name = 'typing_extensions'
self.assertEqual(repr(Final), mod_name + '.Final')
cv = Final[int]
self.assertEqual(repr(cv), mod_name + '.Final[int]')
cv = Final[Employee]
self.assertEqual(repr(cv), mod_name + f'.Final[{__name__}.Employee]')
def test_cannot_subclass(self):
with self.assertRaises(TypeError):
class C(type(Final)):
pass
with self.assertRaises(TypeError):
class C(type(Final[int])):
pass
def test_cannot_init(self):
with self.assertRaises(TypeError):
Final()
with self.assertRaises(TypeError):
type(Final)()
with self.assertRaises(TypeError):
type(Final[Optional[int]])()
def test_no_isinstance(self):
with self.assertRaises(TypeError):
isinstance(1, Final[int])
with self.assertRaises(TypeError):
issubclass(int, Final)
class RequiredTests(BaseTestCase):
def test_basics(self):
if not TYPING_3_11_0:
with self.assertRaises(TypeError):
Required[1]
with self.assertRaises(TypeError):
Required[int, str]
with self.assertRaises(TypeError):
Required[int][str]
def test_repr(self):
if hasattr(typing, 'Required'):
mod_name = 'typing'
else:
mod_name = 'typing_extensions'
self.assertEqual(repr(Required), mod_name + '.Required')
cv = Required[int]
self.assertEqual(repr(cv), mod_name + '.Required[int]')
cv = Required[Employee]
self.assertEqual(repr(cv), mod_name + '.Required[%s.Employee]' % __name__)
def test_cannot_subclass(self):
with self.assertRaises(TypeError):
class C(type(Required)):
pass
with self.assertRaises(TypeError):
class C(type(Required[int])):
pass
def test_cannot_init(self):
with self.assertRaises(TypeError):
Required()
with self.assertRaises(TypeError):
type(Required)()
with self.assertRaises(TypeError):
type(Required[Optional[int]])()
def test_no_isinstance(self):
with self.assertRaises(TypeError):
isinstance(1, Required[int])
with self.assertRaises(TypeError):
issubclass(int, Required)
class NotRequiredTests(BaseTestCase):
def test_basics(self):
if not TYPING_3_11_0:
with self.assertRaises(TypeError):
NotRequired[1]
with self.assertRaises(TypeError):
NotRequired[int, str]
with self.assertRaises(TypeError):
NotRequired[int][str]
def test_repr(self):
if hasattr(typing, 'NotRequired'):
mod_name = 'typing'
else:
mod_name = 'typing_extensions'
self.assertEqual(repr(NotRequired), mod_name + '.NotRequired')
cv = NotRequired[int]
self.assertEqual(repr(cv), mod_name + '.NotRequired[int]')
cv = NotRequired[Employee]
self.assertEqual(repr(cv), mod_name + '.NotRequired[%s.Employee]' % __name__)
def test_cannot_subclass(self):
with self.assertRaises(TypeError):
class C(type(NotRequired)):
pass
with self.assertRaises(TypeError):
class C(type(NotRequired[int])):
pass
def test_cannot_init(self):
with self.assertRaises(TypeError):
NotRequired()
with self.assertRaises(TypeError):
type(NotRequired)()
with self.assertRaises(TypeError):
type(NotRequired[Optional[int]])()
def test_no_isinstance(self):
with self.assertRaises(TypeError):
isinstance(1, NotRequired[int])
with self.assertRaises(TypeError):
issubclass(int, NotRequired)
class IntVarTests(BaseTestCase):
def test_valid(self):
T_ints = IntVar("T_ints") # noqa
def test_invalid(self):
with self.assertRaises(TypeError):
T_ints = IntVar("T_ints", int)
with self.assertRaises(TypeError):
T_ints = IntVar("T_ints", bound=int)
with self.assertRaises(TypeError):
T_ints = IntVar("T_ints", covariant=True) # noqa
class LiteralTests(BaseTestCase):
def test_basics(self):
Literal[1]
Literal[1, 2, 3]
Literal["x", "y", "z"]
Literal[None]
def test_illegal_parameters_do_not_raise_runtime_errors(self):
# Type checkers should reject these types, but we do not
# raise errors at runtime to maintain maximum flexibility
Literal[int]
Literal[Literal[1, 2], Literal[4, 5]]
Literal[3j + 2, ..., ()]
Literal[b"foo", u"bar"]
Literal[{"foo": 3, "bar": 4}]
Literal[T]
def test_literals_inside_other_types(self):
List[Literal[1, 2, 3]]
List[Literal[("foo", "bar", "baz")]]
def test_repr(self):
if hasattr(typing, 'Literal'):
mod_name = 'typing'
else:
mod_name = 'typing_extensions'
self.assertEqual(repr(Literal[1]), mod_name + ".Literal[1]")
self.assertEqual(repr(Literal[1, True, "foo"]), mod_name + ".Literal[1, True, 'foo']")
self.assertEqual(repr(Literal[int]), mod_name + ".Literal[int]")
self.assertEqual(repr(Literal), mod_name + ".Literal")
self.assertEqual(repr(Literal[None]), mod_name + ".Literal[None]")
def test_cannot_init(self):
with self.assertRaises(TypeError):
Literal()
with self.assertRaises(TypeError):
Literal[1]()
with self.assertRaises(TypeError):
type(Literal)()
with self.assertRaises(TypeError):
type(Literal[1])()
def test_no_isinstance_or_issubclass(self):
with self.assertRaises(TypeError):
isinstance(1, Literal[1])
with self.assertRaises(TypeError):
isinstance(int, Literal[1])
with self.assertRaises(TypeError):
issubclass(1, Literal[1])
with self.assertRaises(TypeError):
issubclass(int, Literal[1])
def test_no_subclassing(self):
with self.assertRaises(TypeError):
class Foo(Literal[1]): pass
with self.assertRaises(TypeError):
class Bar(Literal): pass
def test_no_multiple_subscripts(self):
with self.assertRaises(TypeError):
Literal[1][1]
class MethodHolder:
@classmethod
def clsmethod(cls): ...
@staticmethod
def stmethod(): ...
def method(self): ...
if TYPING_3_11_0:
registry_holder = typing
else:
registry_holder = typing_extensions
class OverloadTests(BaseTestCase):
def test_overload_fails(self):
with self.assertRaises(RuntimeError):
@overload
def blah():
pass
blah()
def test_overload_succeeds(self):
@overload
def blah():
pass
def blah():
pass
blah()
@skipIf(
sys.implementation.name == "pypy",
"sum() and print() are not compiled in pypy"
)
@patch(
f"{registry_holder.__name__}._overload_registry",
defaultdict(lambda: defaultdict(dict))
)
def test_overload_on_compiled_functions(self):
registry = registry_holder._overload_registry
# The registry starts out empty:
self.assertEqual(registry, {})
# This should just not fail:
overload(sum)
overload(print)
# No overloads are recorded:
self.assertEqual(get_overloads(sum), [])
self.assertEqual(get_overloads(print), [])
def set_up_overloads(self):
def blah():
pass
overload1 = blah
overload(blah)
def blah():
pass
overload2 = blah
overload(blah)
def blah():
pass
return blah, [overload1, overload2]
# Make sure we don't clear the global overload registry
@patch(
f"{registry_holder.__name__}._overload_registry",
defaultdict(lambda: defaultdict(dict))
)
def test_overload_registry(self):
registry = registry_holder._overload_registry
# The registry starts out empty
self.assertEqual(registry, {})
impl, overloads = self.set_up_overloads()
self.assertNotEqual(registry, {})
self.assertEqual(list(get_overloads(impl)), overloads)
def some_other_func(): pass
overload(some_other_func)
other_overload = some_other_func
def some_other_func(): pass
self.assertEqual(list(get_overloads(some_other_func)), [other_overload])
# Unrelated function still has no overloads:
def not_overloaded(): pass
self.assertEqual(list(get_overloads(not_overloaded)), [])
# Make sure that after we clear all overloads, the registry is
# completely empty.
clear_overloads()
self.assertEqual(registry, {})
self.assertEqual(get_overloads(impl), [])
# Querying a function with no overloads shouldn't change the registry.
def the_only_one(): pass
self.assertEqual(get_overloads(the_only_one), [])
self.assertEqual(registry, {})
def test_overload_registry_repeated(self):
for _ in range(2):
impl, overloads = self.set_up_overloads()
self.assertEqual(list(get_overloads(impl)), overloads)
class AssertTypeTests(BaseTestCase):
def test_basics(self):
arg = 42
self.assertIs(assert_type(arg, int), arg)
self.assertIs(assert_type(arg, Union[str, float]), arg)
self.assertIs(assert_type(arg, AnyStr), arg)
self.assertIs(assert_type(arg, None), arg)
def test_errors(self):
# Bogus calls are not expected to fail.
arg = 42
self.assertIs(assert_type(arg, 42), arg)
self.assertIs(assert_type(arg, 'hello'), arg)
T_a = TypeVar('T_a')
class AwaitableWrapper(Awaitable[T_a]):
def __init__(self, value):
self.value = value
def __await__(self) -> typing.Iterator[T_a]:
yield
return self.value
class AsyncIteratorWrapper(AsyncIterator[T_a]):
def __init__(self, value: Iterable[T_a]):
self.value = value
def __aiter__(self) -> AsyncIterator[T_a]:
return self
async def __anext__(self) -> T_a:
data = await self.value
if data:
return data
else:
raise StopAsyncIteration
class ACM:
async def __aenter__(self) -> int:
return 42
async def __aexit__(self, etype, eval, tb):
return None
class A:
y: float
class B(A):
x: ClassVar[Optional['B']] = None
y: int
b: int
class CSub(B):
z: ClassVar['CSub'] = B()
class G(Generic[T]):
lst: ClassVar[List[T]] = []
class Loop:
attr: Final['Loop']
class NoneAndForward:
parent: 'NoneAndForward'
meaning: None
class XRepr(NamedTuple):
x: int
y: int = 1
def __str__(self):
return f'{self.x} -> {self.y}'
def __add__(self, other):
return 0
@runtime
class HasCallProtocol(Protocol):
__call__: typing.Callable
async def g_with(am: AsyncContextManager[int]):
x: int
async with am as x:
return x
try:
g_with(ACM()).send(None)
except StopIteration as e:
assert e.args[0] == 42
Label = TypedDict('Label', [('label', str)])
class Point2D(TypedDict):
x: int
y: int
class Point2Dor3D(Point2D, total=False):
z: int
class LabelPoint2D(Point2D, Label): ...
class Options(TypedDict, total=False):
log_level: int
log_path: str
class BaseAnimal(TypedDict):
name: str
class Animal(BaseAnimal, total=False):
voice: str
tail: bool
class Cat(Animal):
fur_color: str
class TotalMovie(TypedDict):
title: str
year: NotRequired[int]
class NontotalMovie(TypedDict, total=False):
title: Required[str]
year: int
class AnnotatedMovie(TypedDict):
title: Annotated[Required[str], "foobar"]
year: NotRequired[Annotated[int, 2000]]
gth = get_type_hints
class GetTypeHintTests(BaseTestCase):
def test_get_type_hints_modules(self):
ann_module_type_hints = {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str}
if (TYPING_3_11_0
or (TYPING_3_10_0 and sys.version_info.releaselevel in {'candidate', 'final'})):
# More tests were added in 3.10rc1.
ann_module_type_hints['u'] = int | float
self.assertEqual(gth(ann_module), ann_module_type_hints)
self.assertEqual(gth(ann_module2), {})
self.assertEqual(gth(ann_module3), {})
def test_get_type_hints_classes(self):
self.assertEqual(gth(ann_module.C, ann_module.__dict__),
{'y': Optional[ann_module.C]})
self.assertIsInstance(gth(ann_module.j_class), dict)
self.assertEqual(gth(ann_module.M), {'123': 123, 'o': type})
self.assertEqual(gth(ann_module.D),
{'j': str, 'k': str, 'y': Optional[ann_module.C]})
self.assertEqual(gth(ann_module.Y), {'z': int})
self.assertEqual(gth(ann_module.h_class),
{'y': Optional[ann_module.C]})
self.assertEqual(gth(ann_module.S), {'x': str, 'y': str})
self.assertEqual(gth(ann_module.foo), {'x': int})
self.assertEqual(gth(NoneAndForward, globals()),
{'parent': NoneAndForward, 'meaning': type(None)})
def test_respect_no_type_check(self):
@no_type_check
class NoTpCheck:
class Inn:
def __init__(self, x: 'not a type'): ... # noqa
self.assertTrue(NoTpCheck.__no_type_check__)
self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__)
self.assertEqual(gth(ann_module2.NTC.meth), {})
class ABase(Generic[T]):
def meth(x: int): ...
@no_type_check
class Der(ABase): ...
self.assertEqual(gth(ABase.meth), {'x': int})
def test_get_type_hints_ClassVar(self):
self.assertEqual(gth(ann_module2.CV, ann_module2.__dict__),
{'var': ClassVar[ann_module2.CV]})
self.assertEqual(gth(B, globals()),
{'y': int, 'x': ClassVar[Optional[B]], 'b': int})
self.assertEqual(gth(CSub, globals()),
{'z': ClassVar[CSub], 'y': int, 'b': int,
'x': ClassVar[Optional[B]]})
self.assertEqual(gth(G), {'lst': ClassVar[List[T]]})
def test_final_forward_ref(self):
self.assertEqual(gth(Loop, globals())['attr'], Final[Loop])
self.assertNotEqual(gth(Loop, globals())['attr'], Final[int])
self.assertNotEqual(gth(Loop, globals())['attr'], Final)
class GetUtilitiesTestCase(TestCase):
def test_get_origin(self):
T = TypeVar('T')
P = ParamSpec('P')
Ts = TypeVarTuple('Ts')
class C(Generic[T]): pass
self.assertIs(get_origin(C[int]), C)
self.assertIs(get_origin(C[T]), C)
self.assertIs(get_origin(int), None)
self.assertIs(get_origin(ClassVar[int]), ClassVar)
self.assertIs(get_origin(Union[int, str]), Union)
self.assertIs(get_origin(Literal[42, 43]), Literal)
self.assertIs(get_origin(Final[List[int]]), Final)
self.assertIs(get_origin(Generic), Generic)
self.assertIs(get_origin(Generic[T]), Generic)
self.assertIs(get_origin(List[Tuple[T, T]][int]), list)
self.assertIs(get_origin(Annotated[T, 'thing']), Annotated)
self.assertIs(get_origin(List), list)
self.assertIs(get_origin(Tuple), tuple)
self.assertIs(get_origin(Callable), collections.abc.Callable)
if sys.version_info >= (3, 9):
self.assertIs(get_origin(list[int]), list)
self.assertIs(get_origin(list), None)
self.assertIs(get_origin(P.args), P)
self.assertIs(get_origin(P.kwargs), P)
self.assertIs(get_origin(Required[int]), Required)
self.assertIs(get_origin(NotRequired[int]), NotRequired)
self.assertIs(get_origin(Unpack[Ts]), Unpack)
self.assertIs(get_origin(Unpack), None)
def test_get_args(self):
T = TypeVar('T')
Ts = TypeVarTuple('Ts')
class C(Generic[T]): pass
self.assertEqual(get_args(C[int]), (int,))
self.assertEqual(get_args(C[T]), (T,))
self.assertEqual(get_args(int), ())
self.assertEqual(get_args(ClassVar[int]), (int,))
self.assertEqual(get_args(Union[int, str]), (int, str))
self.assertEqual(get_args(Literal[42, 43]), (42, 43))
self.assertEqual(get_args(Final[List[int]]), (List[int],))
self.assertEqual(get_args(Union[int, Tuple[T, int]][str]),
(int, Tuple[str, int]))
self.assertEqual(get_args(typing.Dict[int, Tuple[T, T]][Optional[int]]),
(int, Tuple[Optional[int], Optional[int]]))