-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
test_typing_extensions.py
8292 lines (6830 loc) · 282 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 abc
import asyncio
import collections
import collections.abc
import contextlib
import copy
import functools
import gc
import importlib
import inspect
import io
import itertools
import pickle
import re
import subprocess
import sys
import tempfile
import textwrap
import types
import typing
import warnings
from collections import defaultdict
from functools import lru_cache
from pathlib import Path
from unittest import TestCase, main, skipIf, skipUnless
from unittest.mock import patch
import typing_extensions
from _typed_dict_test_helper import Foo, FooGeneric, VeryAnnotated
from typing_extensions import (
_PEP_649_OR_749_IMPLEMENTED,
Annotated,
Any,
AnyStr,
AsyncContextManager,
AsyncIterator,
Awaitable,
Buffer,
Callable,
ClassVar,
Concatenate,
Dict,
Doc,
Final,
Format,
Generic,
IntVar,
Iterable,
Iterator,
List,
Literal,
LiteralString,
NamedTuple,
Never,
NewType,
NoDefault,
NoReturn,
NotRequired,
Optional,
ParamSpec,
ParamSpecArgs,
ParamSpecKwargs,
Protocol,
ReadOnly,
Required,
Self,
Set,
Tuple,
Type,
TypeAlias,
TypeAliasType,
TypedDict,
TypeForm,
TypeGuard,
TypeIs,
TypeVar,
TypeVarTuple,
Union,
Unpack,
assert_never,
assert_type,
clear_overloads,
dataclass_transform,
deprecated,
final,
get_annotations,
get_args,
get_origin,
get_original_bases,
get_overloads,
get_protocol_members,
get_type_hints,
is_protocol,
is_typeddict,
no_type_check,
overload,
override,
reveal_type,
runtime,
runtime_checkable,
)
NoneType = type(None)
T = TypeVar("T")
KT = TypeVar("KT")
VT = TypeVar("VT")
# Flags used to mark tests that only apply after a specific
# version of the typing module.
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)
# 3.12 changes the representation of Unpack[] (PEP 692)
# and adds PEP 695 to CPython's grammar
TYPING_3_12_0 = sys.version_info[:3] >= (3, 12, 0)
# @deprecated works differently in Python 3.12
TYPING_3_12_ONLY = (3, 12) <= sys.version_info < (3, 13)
# 3.13 drops support for the keyword argument syntax of TypedDict
TYPING_3_13_0 = sys.version_info[:3] >= (3, 13, 0)
# 3.13.0.rc1 fixes a problem with @deprecated
TYPING_3_13_0_RC = sys.version_info[:4] >= (3, 13, 0, "candidate")
# 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
skip_if_py313_beta_1 = skipIf(
sys.version_info[:5] == (3, 13, 0, 'beta', 1),
"Bugfixes will be released in 3.13.0b2"
)
ANN_MODULE_SOURCE = '''\
import sys
from typing import List, Optional
from functools import wraps
try:
__annotations__[1] = 2
except NameError:
assert sys.version_info >= (3, 14)
class C:
x = 5; y: Optional['C'] = None
from typing import Tuple
x: int = 5; y: str = x; f: Tuple[int, int]
class M(type):
try:
__annotations__['123'] = 123
except NameError:
assert sys.version_info >= (3, 14)
o: type = object
(pars): bool = True
class D(C):
j: str = 'hi'; k: str= 'bye'
from types import new_class
h_class = new_class('H', (C,))
j_class = new_class('J')
class F():
z: int = 5
def __init__(self, x):
pass
class Y(F):
def __init__(self):
super(F, self).__init__(123)
class Meta(type):
def __new__(meta, name, bases, namespace):
return super().__new__(meta, name, bases, namespace)
class S(metaclass = Meta):
x: str = 'something'
y: str = 'something else'
def foo(x: int = 10):
def bar(y: List[str]):
x: str = 'yes'
bar()
def dec(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
'''
ANN_MODULE_2_SOURCE = '''\
from typing import no_type_check, ClassVar
i: int = 1
j: int
x: float = i/10
def f():
class C: ...
return C()
f().new_attr: object = object()
class C:
def __init__(self, x: int) -> None:
self.x = x
c = C(5)
c.new_attr: int = 10
__annotations__ = {}
@no_type_check
class NTC:
def meth(self, param: complex) -> None:
...
class CV:
var: ClassVar['CV']
CV.var = CV()
'''
ANN_MODULE_3_SOURCE = '''\
def f_bad_ann():
__annotations__[1] = 2
class C_OK:
def __init__(self, x: int) -> None:
self.x: no_such_name = x # This one is OK as proposed by Guido
class D_bad_ann:
def __init__(self, x: int) -> None:
sfel.y: int = 0
def g_bad_ann():
no_such_name.attr: int = 0
'''
STOCK_ANNOTATIONS = """
a:int=3
b:str="foo"
class MyClass:
a:int=4
b:str="bar"
def __init__(self, a, b):
self.a = a
self.b = b
def __eq__(self, other):
return isinstance(other, MyClass) and self.a == other.a and self.b == other.b
def function(a:int, b:str) -> MyClass:
return MyClass(a, b)
def function2(a:int, b:"str", c:MyClass) -> MyClass:
pass
def function3(a:"int", b:"str", c:"MyClass"):
pass
class UnannotatedClass:
pass
def unannotated_function(a, b, c): pass
"""
STRINGIZED_ANNOTATIONS = """
from __future__ import annotations
a:int=3
b:str="foo"
class MyClass:
a:int=4
b:str="bar"
def __init__(self, a, b):
self.a = a
self.b = b
def __eq__(self, other):
return isinstance(other, MyClass) and self.a == other.a and self.b == other.b
def function(a:int, b:str) -> MyClass:
return MyClass(a, b)
def function2(a:int, b:"str", c:MyClass) -> MyClass:
pass
def function3(a:"int", b:"str", c:"MyClass"):
pass
class UnannotatedClass:
pass
def unannotated_function(a, b, c): pass
class MyClassWithLocalAnnotations:
mytype = int
x: mytype
"""
STRINGIZED_ANNOTATIONS_2 = """
from __future__ import annotations
def foo(a, b, c): pass
"""
if TYPING_3_12_0:
STRINGIZED_ANNOTATIONS_PEP_695 = textwrap.dedent(
"""
from __future__ import annotations
from typing import Callable, Unpack
class A[T, *Ts, **P]:
x: T
y: tuple[*Ts]
z: Callable[P, str]
class B[T, *Ts, **P]:
T = int
Ts = str
P = bytes
x: T
y: Ts
z: P
Eggs = int
Spam = str
class C[Eggs, **Spam]:
x: Eggs
y: Spam
def generic_function[T, *Ts, **P](
x: T, *y: Unpack[Ts], z: P.args, zz: P.kwargs
) -> None: ...
def generic_function_2[Eggs, **Spam](x: Eggs, y: Spam): pass
class D:
Foo = int
Bar = str
def generic_method[Foo, **Bar](
self, x: Foo, y: Bar
) -> None: ...
def generic_method_2[Eggs, **Spam](self, x: Eggs, y: Spam): pass
# Eggs is `int` in globals, a TypeVar in type_params, and `str` in locals:
class E[Eggs]:
Eggs = str
x: Eggs
def nested():
from types import SimpleNamespace
from typing_extensions import get_annotations
Eggs = bytes
Spam = memoryview
class F[Eggs, **Spam]:
x: Eggs
y: Spam
def generic_method[Eggs, **Spam](self, x: Eggs, y: Spam): pass
def generic_function[Eggs, **Spam](x: Eggs, y: Spam): pass
# Eggs is `int` in globals, `bytes` in the function scope,
# a TypeVar in the type_params, and `str` in locals:
class G[Eggs]:
Eggs = str
x: Eggs
return SimpleNamespace(
F=F,
F_annotations=get_annotations(F, eval_str=True),
F_meth_annotations=get_annotations(F.generic_method, eval_str=True),
G_annotations=get_annotations(G, eval_str=True),
generic_func=generic_function,
generic_func_annotations=get_annotations(generic_function, eval_str=True)
)
"""
)
else:
STRINGIZED_ANNOTATIONS_PEP_695 = None
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 {class_or_tuple!r}'
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 {class_or_tuple!r}'
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 B(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}
for target in some, some_str:
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)
value = "some value"
with self.assertRaisesRegex(AssertionError, value):
assert_never(value)
# Make sure a huge value doesn't get printed in its entirety
huge_value = "a" * 10000
with self.assertRaises(AssertionError) as cm:
assert_never(huge_value)
self.assertLess(
len(cm.exception.args[0]),
typing_extensions._ASSERT_NEVER_REPR_MAX_LENGTH * 2,
)
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.assertWarnsRegex(DeprecationWarning, "A will go away soon"):
with self.assertRaises(TypeError):
A(42)
def test_class_with_init(self):
@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)
def test_class_with_new(self):
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)
def test_class_with_inherited_new(self):
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_class_with_new_but_no_init(self):
new_called = False
@deprecated("HasNewNoInit will go away soon")
class HasNewNoInit:
def __new__(cls, x):
nonlocal new_called
new_called = True
obj = super().__new__(cls)
obj.x = x
return obj
with self.assertWarnsRegex(DeprecationWarning, "HasNewNoInit will go away soon"):
instance = HasNewNoInit(42)
self.assertEqual(instance.x, 42)
self.assertTrue(new_called)
def test_mixin_class(self):
@deprecated("Mixin will go away soon")
class Mixin:
pass
class Base:
def __init__(self, a) -> None:
self.a = a
with self.assertWarnsRegex(DeprecationWarning, "Mixin will go away soon"):
class Child(Base, Mixin):
pass
instance = Child(42)
self.assertEqual(instance.a, 42)
def test_existing_init_subclass(self):
@deprecated("C will go away soon")
class C:
def __init_subclass__(cls) -> None:
cls.inited = True
with self.assertWarnsRegex(DeprecationWarning, "C will go away soon"):
C()
with self.assertWarnsRegex(DeprecationWarning, "C will go away soon"):
class D(C):
pass
self.assertTrue(D.inited)
self.assertIsInstance(D(), D) # no deprecation
def test_existing_init_subclass_in_base(self):
class Base:
def __init_subclass__(cls, x) -> None:
cls.inited = x
@deprecated("C will go away soon")
class C(Base, x=42):
pass
self.assertEqual(C.inited, 42)
with self.assertWarnsRegex(DeprecationWarning, "C will go away soon"):
C()
with self.assertWarnsRegex(DeprecationWarning, "C will go away soon"):
class D(C, x=3):
pass
self.assertEqual(D.inited, 3)
def test_init_subclass_has_correct_cls(self):
init_subclass_saw = None
@deprecated("Base will go away soon")
class Base:
def __init_subclass__(cls) -> None:
nonlocal init_subclass_saw
init_subclass_saw = cls
self.assertIsNone(init_subclass_saw)
with self.assertWarnsRegex(DeprecationWarning, "Base will go away soon"):
class C(Base):
pass
self.assertIs(init_subclass_saw, C)
def test_init_subclass_with_explicit_classmethod(self):
init_subclass_saw = None
@deprecated("Base will go away soon")
class Base:
@classmethod
def __init_subclass__(cls) -> None:
nonlocal init_subclass_saw
init_subclass_saw = cls
self.assertIsNone(init_subclass_saw)
with self.assertWarnsRegex(DeprecationWarning, "Base will go away soon"):
class C(Base):
pass
self.assertIs(init_subclass_saw, C)
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()
def test_only_strings_allowed(self):
with self.assertRaisesRegex(
TypeError,
"Expected an object of type str for 'message', not 'type'"
):
@deprecated
class Foo: ...
with self.assertRaisesRegex(
TypeError,
"Expected an object of type str for 'message', not 'function'"
):
@deprecated
def foo(): ...
def test_no_retained_references_to_wrapper_instance(self):
@deprecated('depr')
def d(): pass
self.assertFalse(any(
isinstance(cell.cell_contents, deprecated) for cell in d.__closure__
))
@deprecated("depr")
def func():
pass
@deprecated("depr")
async def coro():
pass
class Cls:
@deprecated("depr")
def func(self):
pass
@deprecated("depr")
async def coro(self):
pass
class DeprecatedCoroTests(BaseTestCase):
def test_asyncio_iscoroutinefunction(self):
self.assertFalse(asyncio.coroutines.iscoroutinefunction(func))
self.assertFalse(asyncio.coroutines.iscoroutinefunction(Cls.func))
self.assertTrue(asyncio.coroutines.iscoroutinefunction(coro))
self.assertTrue(asyncio.coroutines.iscoroutinefunction(Cls.coro))
@skipUnless(TYPING_3_12_ONLY or TYPING_3_13_0_RC, "inspect.iscoroutinefunction works differently on Python < 3.12")
def test_inspect_iscoroutinefunction(self):
self.assertFalse(inspect.iscoroutinefunction(func))
self.assertFalse(inspect.iscoroutinefunction(Cls.func))
self.assertTrue(inspect.iscoroutinefunction(coro))
self.assertTrue(inspect.iscoroutinefunction(Cls.coro))
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")
@skipIf(sys.version_info[:3] == (3, 11, 0), "A bug was fixed in 3.11.1")
def test_repr_on_Any_subclass(self):
self.assertEqual(
repr(self.SubclassesAny),
f"<class '{self.SubclassesAny.__module__}.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 D(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):
self.assertEqual(repr(Final), 'typing.Final')
cv = Final[int]
self.assertEqual(repr(cv), 'typing.Final[int]')
cv = Final[Employee]